hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0922437bc3347633bc351167a197d2e806a690c4
2,117
cpp
C++
source/Scaffold/Status.cpp
taozhijiang/tzmonitor
8ed45bff1c4e437867fac36e2b7d642b49c06c1b
[ "BSD-3-Clause" ]
1
2018-06-27T13:28:36.000Z
2018-06-27T13:28:36.000Z
source/Scaffold/Status.cpp
taozhijiang/tzmonitor
8ed45bff1c4e437867fac36e2b7d642b49c06c1b
[ "BSD-3-Clause" ]
null
null
null
source/Scaffold/Status.cpp
taozhijiang/tzmonitor
8ed45bff1c4e437867fac36e2b7d642b49c06c1b
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 2019 TAO Zhijiang<taozhijiang@gmail.com> * * Licensed under the BSD-3-Clause license, see LICENSE for full information. * */ #include <Scaffold/Status.h> namespace tzrpc { Status& Status::instance() { static Status helper; return helper; } int Status::register_status_callback(const std::string& name, StatusCallable func) { if (name.empty() || !func){ log_err("invalid name or func param."); return -1; } std::lock_guard<std::mutex> lock(lock_); calls_.push_back({name, func}); log_debug("register status for %s success.", name.c_str()); return 0; } int Status::module_status(std::string& module, std::string& name, std::string& val) { module = "tzrpc"; name = "Status"; std::stringstream ss; ss << "registered status: " << std::endl; int i = 1; for (auto it = calls_.begin(); it != calls_.end(); ++it) { ss << "\t" << i++ << ". "<< it->first << std::endl; } val = ss.str(); return 0; } int Status::collect_status(std::string& output) { std::lock_guard<std::mutex> lock(lock_); std::vector<std::pair<std::string, std::string>> results; for (auto iter = calls_.begin(); iter != calls_.end(); ++iter) { std::string strModule; std::string strName; std::string strValue; int ret = iter->second(strModule, strName, strValue); if (ret == 0) { std::string real = strModule + ":" + strName; results.push_back({real,strValue}); } else { log_err("call collect_status of %s failed with: %d", iter->first.c_str(), ret); } } std::stringstream ss; ss << std::endl << std::endl <<" *** SYSTEM RUNTIME STATUS *** " << std::endl << std::endl; for (auto iter = results.begin(); iter != results.end(); ++iter) { ss << "[" << iter->first << "]" << std::endl; ss << iter->second << std::endl; ss << " ------------------------------- " << std::endl; ss << std::endl; } output = ss.str(); return 0; } } // end namespace tzhttpd
24.616279
97
0.553141
[ "vector" ]
092f86bcebb892bc61faf0cf4bfc48c2a553d910
882
cpp
C++
13.Roman_to_Integer/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
13.Roman_to_Integer/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
13.Roman_to_Integer/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
/* 针对所有逆序的情况,额外多做了一次减法 */ #include <cstdlib> #include <vector> #include <string> #include <cassert> #include <algorithm> #include <sstream> #include <map> using namespace std; class Solution { public: int romanToInt(string s) { map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; int val = roman[s[0]]; for (auto i = 1; i < s.size(); ++i) { val += roman[s[i]]; if (s[i - 1] == 'I' && (s[i] == 'V' || s[i] == 'X')) { val -= 2; } else if (s[i - 1] == 'X' && (s[i] == 'L' || s[i] == 'C')) { val -= 20; } else if (s[i - 1] == 'C' && (s[i] == 'D' || s[i] == 'M')) { val -= 200; } else { ; } } return val; } };
24.5
111
0.35941
[ "vector" ]
09398c817aca3983edee7c472de861b5bc73bc09
76,491
inl
C++
src/cryptonote_protocol/cryptonote_protocol_handler.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
src/cryptonote_protocol/cryptonote_protocol_handler.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
src/cryptonote_protocol/cryptonote_protocol_handler.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
/// @file /// @author rfree (current maintainer/user in monero.cc project - most of code is from CryptoNote) /// @brief This is the original cryptonote protocol network-events handler, modified by us // Copyright (c) 2014-2020, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers // (may contain code and/or modifications by other developers) // developer rfree: this code is caller of our new network code, and is modded; e.g. for rate limiting #include <boost/interprocess/detail/atomic.hpp> #include <list> #include <ctime> #include "cryptonote_basic/cryptonote_format_utils.h" #include "profile_tools.h" #include "net/network_throttle-detail.hpp" #include "common/pruning.h" #include "common/util.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "net.cn" #define MLOG_P2P_MESSAGE(x) MCINFO("net.p2p.msg", peer_cxt << x) #define MLOGIF_P2P_MESSAGE(init, test, x) \ do { \ const auto level = el::Level::Info; \ const char *cat = "net.p2p.msg"; \ if (ELPP->vRegistry()->allowed(level, cat)) { \ init; \ if (test) \ el::base::Writer(level, el::Color::Default, __FILE__, __LINE__, ELPP_FUNC, el::base::DispatchAction::NormalLog).construct(cat) << x; \ } \ } while(0) #define MLOG_PEER_STATE(x) \ MCINFO(MONERO_DEFAULT_LOG_CATEGORY, peer_cxt << "[" << epee::string_tools::to_string_hex(peer_cxt.m_pruning_seed) << "] state: " << x << " in state " << cryptonote::get_protocol_state_string(peer_cxt.m_state)) #define BLOCK_QUEUE_NSPANS_THRESHOLD 10 // chunks of N blocks #define BLOCK_QUEUE_SIZE_THRESHOLD (100*1024*1024) // MB #define BLOCK_QUEUE_FORCE_DOWNLOAD_NEAR_BLOCKS 1000 #define REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY (5 * 1000000) // microseconds #define REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD (30 * 1000000) // microseconds #define IDLE_PEER_KICK_TIME (240 * 1000000) // microseconds #define NON_RESPONSIVE_PEER_KICK_TIME (20 * 1000000) // microseconds #define PASSIVE_PEER_KICK_TIME (60 * 1000000) // microseconds #define DROP_ON_SYNC_WEDGE_THRESHOLD (30 * 1000000000ull) // nanoseconds #define LAST_ACTIVITY_STALL_THRESHOLD (2.0f) // seconds #define DROP_PEERS_ON_SCORE -2 namespace cryptonote { //----------------------------------------------------------------------------------------------------------------------- template<class t_core> t_cryptonote_protocol_handler<t_core>::t_cryptonote_protocol_handler(t_core& rcore, nodetool::i_p2p_endpoint<cryptonote_peer_context>* p2p, bool offline):m_core(rcore),m_p2p(p2p),m_syncronized_connections_count(0),m_synchronized(offline),m_ask_for_txpool_complement(true),m_stopping(false),m_no_sync(false) { if(!m_p2p) m_p2p = &m_p2p_stub; } //----------------------------------------------------------------------------------------------------------------------- template<class t_core> bool t_cryptonote_protocol_handler<t_core>::init(const boost::program_options::variables_map& vm) { m_sync_timer.pause(); m_sync_timer.reset(); m_add_timer.pause(); m_add_timer.reset(); m_last_add_end_time = 0; m_sync_spans_downloaded = 0; m_sync_old_spans_downloaded = 0; m_sync_bad_spans_downloaded = 0; m_sync_download_objects_size = 0; m_block_download_max_size = command_line::get_arg(vm, cryptonote::arg_block_download_max_size); return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::deinit() { return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::set_p2p_endpoint(nodetool::i_p2p_endpoint<cryptonote_peer_context>* p2p) { if(p2p) m_p2p = p2p; else m_p2p = &m_p2p_stub; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::log_connections() { std::stringstream ss; ss.precision(1); double down_sum = 0.0; double down_curr_sum = 0.0; double up_sum = 0.0; double up_curr_sum = 0.0; ss << std::setw(30) << std::left << "Remote Host" << std::setw(20) << "Peer id" << std::setw(20) << "Support Flags" << std::setw(30) << "Recv/Sent (inactive,sec)" << std::setw(25) << "State" << std::setw(20) << "Livetime(sec)" << std::setw(12) << "Down (kB/s)" << std::setw(14) << "Down(now)" << std::setw(10) << "Up (kB/s)" << std::setw(13) << "Up(now)" << ENDL; m_p2p->for_each_connection([&](const cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { bool local_ip = peer_cxt.m_remote_address.is_local(); auto connection_time = time(NULL) - peer_cxt.m_started; ss << std::setw(30) << std::left << std::string(peer_cxt.m_is_income ? " [INC]":"[OUT]") + peer_cxt.m_remote_address.str() << std::setw(20) << nodetool::peerid_to_string(peer_id) << std::setw(20) << std::hex << support_flags << std::setw(30) << std::to_string(peer_cxt.m_recv_cnt)+ "(" + std::to_string(time(NULL) - peer_cxt.m_last_recv) + ")" + "/" + std::to_string(peer_cxt.m_send_cnt) + "(" + std::to_string(time(NULL) - peer_cxt.m_last_send) + ")" << std::setw(25) << get_protocol_state_string(peer_cxt.m_state) << std::setw(20) << std::to_string(time(NULL) - peer_cxt.m_started) << std::setw(12) << std::fixed << (connection_time == 0 ? 0.0 : peer_cxt.m_recv_cnt / connection_time / 1024) << std::setw(14) << std::fixed << peer_cxt.m_current_speed_down / 1024 << std::setw(10) << std::fixed << (connection_time == 0 ? 0.0 : peer_cxt.m_send_cnt / connection_time / 1024) << std::setw(13) << std::fixed << peer_cxt.m_current_speed_up / 1024 << (local_ip ? "[LAN]" : "") << std::left << (peer_cxt.m_remote_address.is_loopback() ? "[LOCALHOST]" : "") // 127.0.0.1 << ENDL; if (connection_time > 1) { down_sum += (peer_cxt.m_recv_cnt / connection_time / 1024); up_sum += (peer_cxt.m_send_cnt / connection_time / 1024); } down_curr_sum += (peer_cxt.m_current_speed_down / 1024); up_curr_sum += (peer_cxt.m_current_speed_up / 1024); return true; }); ss << ENDL << std::setw(125) << " " << std::setw(12) << down_sum << std::setw(14) << down_curr_sum << std::setw(10) << up_sum << std::setw(13) << up_curr_sum << ENDL; LOG_PRINT_L0("Connections: " << ENDL << ss.str()); } //------------------------------------------------------------------------------------------------------------------------ // Returns a list of connection_info objects describing each open p2p connection //------------------------------------------------------------------------------------------------------------------------ template<class t_core> std::list<connection_info> t_cryptonote_protocol_handler<t_core>::get_connections() { std::list<connection_info> connections; m_p2p->for_each_connection([&](const cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { connection_info cnx; auto timestamp = time(NULL); cnx.incoming = peer_cxt.m_is_income ? true : false; cnx.address = peer_cxt.m_remote_address.str(); cnx.host = peer_cxt.m_remote_address.host_str(); cnx.ip = ""; cnx.port = ""; if (peer_cxt.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id()) { cnx.ip = cnx.host; cnx.port = std::to_string(peer_cxt.m_remote_address.as<epee::net_utils::ipv4_network_address>().port()); } cnx.rpc_port = peer_cxt.m_rpc_port; cnx.rpc_credits_per_hash = peer_cxt.m_rpc_credits_per_hash; cnx.peer_id = nodetool::peerid_to_string(peer_id); cnx.support_flags = support_flags; cnx.recv_count = peer_cxt.m_recv_cnt; cnx.recv_idle_time = timestamp - std::max(peer_cxt.m_started, peer_cxt.m_last_recv); cnx.send_count = peer_cxt.m_send_cnt; cnx.send_idle_time = timestamp - std::max(peer_cxt.m_started, peer_cxt.m_last_send); cnx.state = get_protocol_state_string(peer_cxt.m_state); cnx.live_time = timestamp - peer_cxt.m_started; cnx.localhost = peer_cxt.m_remote_address.is_loopback(); cnx.local_ip = peer_cxt.m_remote_address.is_local(); auto connection_time = time(NULL) - peer_cxt.m_started; if (connection_time == 0) { cnx.avg_download = 0; cnx.avg_upload = 0; } else { cnx.avg_download = peer_cxt.m_recv_cnt / connection_time / 1024; cnx.avg_upload = peer_cxt.m_send_cnt / connection_time / 1024; } cnx.current_download = peer_cxt.m_current_speed_down / 1024; cnx.current_upload = peer_cxt.m_current_speed_up / 1024; cnx.connection_id = epee::string_tools::pod_to_hex(peer_cxt.m_connection_id); cnx.ssl = peer_cxt.m_ssl; cnx.height = peer_cxt.m_remote_chain_height; cnx.pruning_seed = peer_cxt.m_pruning_seed; cnx.address_type = (uint8_t)peer_cxt.m_remote_address.get_type_id(); connections.push_back(cnx); return true; }); return connections; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::get_payload_sync_data(CORE_SYNC_DATA& hshd) { m_core.get_blockchain_top(hshd.current_height, hshd.top_id); hshd.top_version = m_core.get_ideal_hard_fork_version(hshd.current_height); difficulty_type wide_cumulative_difficulty = m_core.get_block_cumulative_difficulty(hshd.current_height); hshd.cum_diff = (wide_cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>(); hshd.cumulative_difficulty_top64 = ((wide_cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>(); hshd.current_height +=1; hshd.pruning_seed = m_core.get_blockchain_pruning_seed(); return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::get_payload_sync_data(epee::byte_slice& data) { CORE_SYNC_DATA hsd = {}; get_payload_sync_data(hsd); epee::serialization::store_t_to_binary(hsd, data); return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_notify_new_fluffy_block(int command, NOTIFY_NEW_FLUFFY_BLOCK::request& req, cryptonote_peer_context& peer_cxt) { if(peer_cxt.m_state != cryptonote_peer_context::state_normal) return 1; if(!is_synchronized()) // can happen if a peer connection goes to normal but another thread still hasn't finished adding queued blocks { MDEBUG(peer_cxt, "Received new block while syncing, ignored"); return 1; } try{ const auto & new_block =parse_block_from_blob(req.b.block); // This is a second notification, we must have asked for some missing tx if(!peer_cxt.m_requested_objects.empty()) { // What we asked for != to what we received .. if(peer_cxt.m_requested_objects.size() != req.b.txs.size()) { MERROR(peer_cxt<<"NOTIFY_NEW_FLUFFY_BLOCK -> request/response mismatch, " << "block = " << epee::string_tools::pod_to_hex(get_blob_hash(req.b.block)) << ", requested = " << peer_cxt.m_requested_objects.size() << ", received = " << new_block.tx_hashes.size()<< ", dropping connection" ); drop_connection(peer_cxt, false, false); return 1; } } for(auto& tb: req.bce.tbs) { const auto tx = parse_tx_from_blob(tb.blob); tx_hash =get_transaction_hash(tx); // we might already have the tx that the peer // sent in our pool, so don't verify again.. if(!m_core.pool_has_tx(tx_hash)) { MDEBUG("Incoming tx " << tx_hash << " not in pool, adding"); const auto tvc = m_core.handle_incoming_tx(tx_blob, relay_method::block, true); if(tvc.m_verifivation_failed) { LOG_PRINT_CCONTEXT_L1("Block verification failed: transaction verification failed, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } // future todo: // tx should only not be added to pool if verification failed, but // maybe in the future could not be added for other reasons // according to monero-moo so keep track of these separately .. // } } std::vector<crypto::hash> missing_tx_hashes; for(auto& tx_hash: new_block.tx_hashes) { if (!m_core.pool_has_tx(tx_hash) ) { missing_tx_hashes.push_back(tx_hash); } } if(!missing_tx_hashes.empty()) // drats, we don't have everything.. { // request non-mempool txs NOTIFY_REQUEST_FLUFFY_MISSING_TX::request missing_tx_req; missing_tx_req.block_hash = get_block_hash(new_block); missing_tx_req.cur_chain_height = req.cur_chain_height; missing_tx_req.missing_tx_hashes = std::move(missing_tx_hashes); MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_hashes.size()=" << missing_tx_req.missing_tx_indices.size() ); post_notify<NOTIFY_REQUEST_FLUFFY_MISSING_TX>(missing_tx_req, peer_cxt); } else // whoo-hoo we've got em all .. { MDEBUG("We have all needed txes for this fluffy block"); const auto & b = parse_block_from_blob(req.bce.blob); block_verification_context bvc = m_core.get_blockchain().add_new_block(b); if( bvc.m_verifivation_failed ) { MERROR("Block verification failed, dropping connection"); drop_connection_with_score(peer_cxt, bvc.m_bad_pow ? P2P_IP_FAILS_BEFORE_BLOCK : 1, false); return 1; } if( bvc.m_added_to_main_chain ) { //TODO: Add here announce protocol usage relay_block(req.b.block,req.cur_chain_height, peer_cxt); } else if( bvc.m_marked_as_orphaned ) { peer_cxt.m_needed_blocks.clear(); peer_cxt.m_state = cryptonote_peer_context::state_synchronizing; NOTIFY_REQUEST_CHAIN::request r {m_core.get_blockchain().get_short_chain_history()}; peer_cxt.m_sync_start_height = m_core.get_chain_height(); peer_cxt.m_last_request_time = boost::posix_time::microsec_clock::universal_time(); peer_cxt.m_expect_response = NOTIFY_RESPONSE_CHAIN_ENTRY::ID; MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() ); post_notify<NOTIFY_REQUEST_CHAIN>(r, peer_cxt); MLOG_PEER_STATE("requesting chain"); } } } catch(const std::exception &ex) { MERROR(ex.what()); drop_connection(peer_cxt, false, false); return 1; } return 1; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_request_fluffy_missing_tx(int command, NOTIFY_REQUEST_FLUFFY_MISSING_TX::request& arg, cryptonote_peer_context& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_FLUFFY_MISSING_TX (" << arg.missing_tx_hashes.size() << " txes), block hash " << arg.block_hash); if (peer_cxt.m_state == cryptonote_peer_context::state_before_handshake) { MERROR(peer_cxt<<"Requested fluffy tx before handshake, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } try{ block b; if (!m_core.get_block_by_hash(arg.block_hash, b)) { MERROR(peer_cxt<<"failed to find block: " << arg.block_hash << ", dropping connection"); drop_connection(peer_cxt, false, false); return 1; } NOTIFY_NEW_FLUFFY_BLOCK::request fluffy_response; fluffy_response.bce.blob = t_serializable_object_to_blob(b); fluffy_response.cur_chain_height = arg.cur_chain_height; const auto blobs=m_core.get_tx_pool().get_transaction_blobs(arg.missing_tx_hashes); for(auto& tx_blob: blobs) { fluffy_response.bce.tbs.push_back({tx_blob, crypto::null_hash}); } MLOG_P2P_MESSAGE ( "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: " << ", txs.size()=" << fluffy_response.bce.tbs.size() << ", rsp.cur_chain_height=" << fluffy_response.cur_chain_height ); post_notify<NOTIFY_NEW_FLUFFY_BLOCK>(fluffy_response, peer_cxt); return 1; }catch(std::exception & ex){ MERROR(peer_cxt<<"Requested fluffy tx missing, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_notify_get_txpool_complement(int command, NOTIFY_GET_TXPOOL_COMPLEMENT::request& arg, cryptonote_peer_context& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_GET_TXPOOL_COMPLEMENT (" << arg.hashes.size() << " txes)"); if(peer_cxt.m_state != cryptonote_peer_context::state_normal) return 1; try{ const auto &txes=m_core.get_tx_pool().get_transaction_blobs_ex(arg.hashes); NOTIFY_NEW_TRANSACTIONS::request new_txes; new_txes.txs = std::move(txes); MLOG_P2P_MESSAGE ( "-->>NOTIFY_NEW_TRANSACTIONS: " << ", txs.size()=" << new_txes.txs.size() ); post_notify<NOTIFY_NEW_TRANSACTIONS>(new_txes, peer_cxt); return 1; }catch(std::exception & ex){ MERROR(peer_cxt<<"failed to get txpool blobs"<<ex.what()); return 1; } } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_notify_new_transactions(int command, NOTIFY_NEW_TRANSACTIONS::request& arg, cryptonote_peer_context& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_NEW_TRANSACTIONS (" << arg.txs.size() << " txes)"); for (const auto &blob: arg.txs) MLOGIF_P2P_MESSAGE(cryptonote::transaction tx; crypto::hash hash; bool ret = cryptonote::parse_tx_from_blob(blob, tx, hash);, ret, "Including transaction " << hash); if(peer_cxt.m_state != cryptonote_peer_context::state_normal) return 1; // while syncing, core will lock for a long time, so we ignore // those txes as they aren't really needed anyway, and avoid a // long block before replying if(!is_synchronized()) { MDEBUG(peer_cxt, "Received new tx while syncing, ignored"); return 1; } /* If the txes were received over i2p/tor, the default is to "forward" with a randomized delay to further enhance the "white noise" behavior, potentially making it harder for ISP-level spies to determine which inbound link sent the tx. If the sender disabled "white noise" over i2p/tor, then the sender is "fluffing" (to only outbound) i2p/tor connections with the `dandelionpp_fluff` flag set. The receiver (hidden service) will immediately fluff in that scenario (i.e. this assumes that a sybil spy will be unable to link an IP to an i2p/tor connection). */ relay_method tx_relay = relay_method::stem ; std::vector<blobdata> stem_txs{}; std::vector<blobdata> fluff_txs{}; if (arg.dandelionpp_fluff) { tx_relay = relay_method::fluff; fluff_txs.reserve(arg.txs.size()); } else stem_txs.reserve(arg.txs.size()); for (auto& tx : arg.txs) { tx_verification_context tvc=m_core.handle_incoming_tx({tx, crypto::null_hash}, tx_relay, true); if (tvc.m_verifivation_failed) { LOG_PRINT_CCONTEXT_L1("Tx verification failed, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } switch (tvc.m_relay) { case relay_method::local: case relay_method::stem: stem_txs.push_back(std::move(tx)); break; case relay_method::block: case relay_method::fluff: fluff_txs.push_back(std::move(tx)); break; default: case relay_method::forward: // not supposed to happen here case relay_method::none: break; } } if (!stem_txs.empty()) { //TODO: add announce usage here arg.dandelionpp_fluff = false; arg.txs = std::move(stem_txs); relay_transactions(arg, peer_cxt.m_connection_id, peer_cxt.m_remote_address.get_zone(), relay_method::stem); } if (!fluff_txs.empty()) { //TODO: add announce usage here arg.dandelionpp_fluff = true; arg.txs = std::move(fluff_txs); relay_transactions(arg, peer_cxt.m_connection_id, peer_cxt.m_remote_address.get_zone(), relay_method::fluff); } return 1; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_request_get_blocks(int command, NOTIFY_REQUEST_GET_BLOCKS::request& req, cryptonote_peer_context& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_GET_BLOCKS " << req.span_start_height<<","<<req.span_len); if (peer_cxt.m_state == cryptonote_peer_context::state_before_handshake) { MERROR(peer_cxt<<"Requested objects before handshake, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } try{ NOTIFY_RESPONSE_GET_BLOCKS::request rsp; rsp.chain_heigth = m_core.get_blockchain().get_chain_height(); rsp.span_start_height=req.span_start_height; const auto & blocks= m_core.get_blockchain().get_blocks(req.span_start_height, req.span_len); for (auto & [bblob, b] : blocks) { block_complete_entry e{}; e.tbs=m_core.get_blockchain().get_transactions_blobs(b.tx_hashes ); e.blob = std::move(bblob); rsp.bces.push_back(std::move(e)); } peer_cxt.m_last_request_time = boost::posix_time::microsec_clock::universal_time(); post_notify<NOTIFY_RESPONSE_GET_BLOCKS>(rsp, peer_cxt); //handler_response_blocks_now(sizeof(rsp)); // XXX //handler_response_blocks_now(200); return 1; }catch(std::exception& ex){ MERROR(peer_cxt<<"failed to handle request NOTIFY_REQUEST_GET_BLOCKS, dropping connection"<<ex.what()); drop_connection(peer_cxt, false, false); return 1; } } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> double t_cryptonote_protocol_handler<t_core>::get_avg_block_size() { CRITICAL_REGION_LOCAL(m_buffer_mutex); if (m_avg_buffer.empty()) { MWARNING("m_avg_buffer.size() == 0"); return 500; } double avg = 0; for (const auto &element : m_avg_buffer) avg += element; return avg / m_avg_buffer.size(); } template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_response_get_objects(int command, NOTIFY_RESPONSE_GET_BLOCKS::request& rsp, cryptonote_peer_context& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_GET_BLOCKS (" << rsp.bces.size() << " blocks)"); MLOG_PEER_STATE("received objects"); if (peer_cxt.m_expect_response != NOTIFY_RESPONSE_GET_BLOCKS::ID) { MERROR(peer_cxt<<"Got NOTIFY_RESPONSE_GET_BLOCKS out of the blue, dropping connection"); drop_connection(peer_cxt, true, false); return 1; } if(rsp.bces.empty()) { MERROR(peer_cxt<<"sent wrong NOTIFY_HAVE_OBJECTS: no blocks"); drop_connection(peer_cxt, true, false); ++m_sync_bad_spans_downloaded; return 1; } const auto request_time = peer_cxt.m_last_request_time; peer_cxt.m_last_request_time = boost::date_time::not_a_date_time; peer_cxt.m_expect_response = 0; // calculate size of request size_t size = 0; size_t blocks_size = 0; for (const auto &element : rsp.bces) { blocks_size += element.blob.size(); for (const auto &tx : element.txs) blocks_size += tx.blob.size(); } size += blocks_size; { CRITICAL_REGION_LOCAL(m_buffer_mutex); m_avg_buffer.push_back(size); } ++m_sync_spans_downloaded; m_sync_download_objects_size += size; MDEBUG(peer_cxt << " downloaded " << size << " bytes worth of blocks"); const auto local_height =m_core.get_chain_height() ; if( rsp.chain_height <=local_height) { MERROR(peer_cxt<<"why sync with shorter chains?" << rsp.chain_height<<"/"<< local_height << ", dropping connection"); drop_connection(peer_cxt, false, false); ++m_sync_bad_spans_downloaded; return 1; } peer_cxt.m_remote_chain_height = rsp.chain_height; if (peer_cxt.m_remote_chain_height > m_core.get_target_blockchain_height()) m_core.set_target_blockchain_height(peer_cxt.m_remote_chain_height); uint64_t start_height = rsp.span_start_height; peer_cxt.m_requested_objects.clear(); const auto now = boost::posix_time::microsec_clock::universal_time(); { MLOG_YELLOW(el::Level::Debug, peer_cxt << " Got NEW BLOCKS inside of " << __FUNCTION__ << ": size: " << rsp.blocks.size()<< ", blocks: " << start_height << " - " << (start_height + rsp.bces.size() - 1)); // add that new span to the block queue const boost::posix_time::time_duration dt = now - request_time; const float rate = size * 1e6 / (dt.total_microseconds() + 1); MDEBUG(peer_cxt << " adding span: " << rsp.bces.size() << " at height " << start_height << ", " << dt.total_microseconds()/1e6 << " seconds, " << (rate/1024) << " kB/s, size now " << (m_block_queue.get_data_size() + blocks_size) / 1048576.f << " MB"); } m_block_queue.finish_span(start_height, rsp.bces, peer_cxt); // peer_cxt.m_last_known_hash = cryptonote::get_block_hash(b); if (!download_next_span(peer_cxt, true)) { MERROR(peer_cxt<<"Failed to request missing objects, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } try_add_next_span(peer_cxt); return 1; } // Get an estimate for the remaining sync time from given current to target blockchain height, in seconds template<class t_core> uint64_t t_cryptonote_protocol_handler<t_core>::get_estimated_remaining_sync_seconds(uint64_t cur_chain_height, uint64_t target_blockchain_height) { // The average sync speed varies so much, even averaged over quite long time periods like 10 minutes, // that using some sliding window would be difficult to implement without often leading to bad estimates. // The simplest strategy - always average sync speed over the maximum available interval i.e. since sync // started at all (from "m_sync_start_time" and "m_sync_start_height") - gives already useful results // and seems to be quite robust. Some quite special cases like "Internet connection suddenly becoming // much faster after syncing already a long time, and staying fast" are not well supported however. if (target_blockchain_height <= cur_chain_height) { // Syncing stuck, or other special circumstance: Avoid errors, simply give back 0 return 0; } const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); const boost::posix_time::time_duration sync_time = now - m_sync_start_time; cryptonote::network_type nettype = m_core.get_nettype(); // Don't simply use remaining number of blocks for the estimate but "sync weight" as provided by // "cumulative_block_sync_weight" which knows about strongly varying Monero mainnet block sizes uint64_t synced_weight = tools::cumulative_block_sync_weight(nettype, m_sync_start_height, cur_chain_height - m_sync_start_height); float us_per_weight = (float)sync_time.total_microseconds() / (float)synced_weight; uint64_t remaining_weight = tools::cumulative_block_sync_weight(nettype, cur_chain_height, target_blockchain_height - cur_chain_height); float remaining_us = us_per_weight * (float)remaining_weight; return (uint64_t)(remaining_us / 1e6); } // Return a textual remaining sync time estimate, or the empty string if waiting period not yet over template<class t_core> std::string t_cryptonote_protocol_handler<t_core>::get_periodic_sync_estimate(uint64_t cur_chain_height, uint64_t target_blockchain_height) { std::string text = ""; const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); boost::posix_time::time_duration period_sync_time = now - m_period_start_time; if (period_sync_time > boost::posix_time::minutes(2)) { // Period is over, time to report another estimate uint64_t remaining_seconds = get_estimated_remaining_sync_seconds(cur_chain_height, target_blockchain_height); text = tools::get_human_readable_timespan(remaining_seconds); // Start the new period m_period_start_time = now; } return text; } template<class t_core> int t_cryptonote_protocol_handler<t_core>::try_add_next_span(cryptonote_peer_context& peer_cxt) { // We try to lock the sync lock. If we can, it means no other thread is // currently adding blocks, so we do that for as long as we can from the // block queue. Then, we go back to download. const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock}; if (!sync.owns_lock()) { MINFO( "Failed to lock m_sync_lock, going back to download"); goto skip; } MDEBUG(" lock m_sync_lock, adding blocks to chain..."); MLOG_PEER_STATE("adding blocks"); m_add_timer.resume(); bool starting = true; epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([this, &starting]() { m_add_timer.pause(); if (!starting) m_last_add_end_time = tools::get_tick_count(); }); m_sync_start_time = boost::posix_time::microsec_clock::universal_time(); m_sync_start_height = m_core.get_chain_height(); m_period_start_time = m_sync_start_time; while (1) { const uint64_t local_height = m_core.get_chain_height(); uint64_t start_height; boost::uuids::uuid span_con_id; epee::net_utils::network_address span_origin; const auto & o_span = m_block_queue.get_next_span(start_height, v_sync_b_data, span_con_id, span_origin); if (!o_span) { MDEBUG(" no next span found, going back to download"); break; } const auto & span = o_span.value(); auto & v_sync_b_data = span.bces; MDEBUG(" next span in the queue has v_sync_b_data " << start_height << "-" << (start_height + v_sync_b_data.size() - 1)<< ", we need " << local_height); const boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time(); if (starting) { starting = false; if (m_last_add_end_time) { const uint64_t tnow = tools::get_tick_count(); const uint64_t ns = tools::ticks_to_ns(tnow - m_last_add_end_time); MINFO("Restarting adding block after idle for " << ns/1e9 << " seconds"); } } uint64_t block_process_time_full = 0, transactions_process_time_full = 0; size_t num_txs = 0, blockidx = 0; for(const auto& sync_b_data: v_sync_b_data) { if (m_stopping) { m_core.cleanup_handle_incoming_blocks(); return 1; } const auto block = parse_block_from_blob(sync_b_data.block); std::vector<BlobTx> tx_ps; txes.reserve(sync_b_data.txs.size()); for(auto & tb: sync_b_data.txs){ const auto & tx = parse_tx_from_blob_entry(tb); tx_ps.push_back({std::move(tx),std::move(tb.tx_blob)}); } // process transactions num_txs += tx_ps.size(); // process block TIME_MEASURE_START(block_process_time); block_verification_context bvc = m_core.get_blockchain().add_sync_block(block,tx_ps); // <--- process block if(bvc.m_verifivation_failed) { drop_connections(span_origin); // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it m_block_queue.remove_spans(span_con_id, start_height); return 1; } if(bvc.m_marked_as_orphaned) { drop_connections(span_origin); // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it m_block_queue.remove_spans(span_con_id, start_height); return 1; } TIME_MEASURE_FINISH(block_process_time); block_process_time_full += block_process_time; ++blockidx; } // each download block MDEBUG(peer_cxt << "Block process time (" << v_sync_b_data.size() << " v_sync_b_data, " << num_txs << " txs): " << block_process_time_full + transactions_process_time_full << " (" << transactions_process_time_full << "/" << block_process_time_full << ") ms"); m_block_queue.remove_spans(span_con_id, start_height); const uint64_t cur_chain_height = m_core.get_chain_height(); if (cur_chain_height > local_height) { const uint64_t target_blockchain_height = m_core.get_target_blockchain_height(); const boost::posix_time::time_duration dt = boost::posix_time::microsec_clock::universal_time() - start; std::string progress_message = ""; if (cur_chain_height < target_blockchain_height) { uint64_t completion_percent = (cur_chain_height * 100 / target_blockchain_height); if (completion_percent == 100) // never show 100% if not actually up to date completion_percent = 99; progress_message = " (" + std::to_string(completion_percent) + "%, "+ std::to_string(target_blockchain_height - cur_chain_height) + " left"; std::string time_message = get_periodic_sync_estimate(cur_chain_height, target_blockchain_height); if (!time_message.empty()) { uint64_t total_blocks_to_sync = target_blockchain_height - m_sync_start_height; uint64_t total_blocks_synced = cur_chain_height - m_sync_start_height; progress_message += ", " + std::to_string(total_blocks_synced * 100 / total_blocks_to_sync) + "% of total synced"; progress_message += ", estimated " + time_message + " left"; } progress_message += ")"; } const uint32_t previous_stripe = tools::get_pruning_stripe(local_height, target_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES); const uint32_t current_stripe = tools::get_pruning_stripe(cur_chain_height, target_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES); std::string timing_message = ""; timing_message = std::string(" (") + std::to_string(dt.total_microseconds()/1e6) + " sec, "+ std::to_string((cur_chain_height - local_height) * 1e6 / dt.total_microseconds())+ " v_sync_b_data/sec), " + std::to_string(m_block_queue.get_data_size() / 1048576.f) + " MB queued in "+ std::to_string(m_block_queue.get_num_filled_spans()) + " spans, stripe -> " + std::to_string(current_stripe); timing_message += std::string(": ") + m_block_queue.get_overview(cur_chain_height); MGINFO_YELLOW("Synced " << cur_chain_height << "/" << target_blockchain_height<< progress_message << timing_message); } } skip: return 1; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::notify_new_stripe(cryptonote_peer_context& peer_cxt, uint32_t stripe) { m_p2p->for_each_connection([&](cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags)->bool { if (peer_cxt.m_connection_id == peer_cxt.m_connection_id) return true; if (peer_cxt.m_state == cryptonote_peer_context::state_normal) { const uint32_t peer_stripe = tools::get_pruning_stripe(peer_cxt.m_pruning_seed); if (stripe && peer_stripe && peer_stripe != stripe) return true; peer_cxt.m_new_stripe_notification = true; LOG_PRINT_CCONTEXT_L2("requesting callback"); ++peer_cxt.m_callback_request_count; m_p2p->request_callback(peer_cxt); MLOG_PEER_STATE("requesting callback"); } return true; }); } #include "cryptonote_protocol_handler_idle.inl" //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_request_chain(int command, NOTIFY_REQUEST_CHAIN::request& arg, cryptonote_peer_context& peer_cxt) { try{ MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_CHAIN (" << arg.block_ids.size() << " blocks"); if (peer_cxt.m_state == cryptonote_peer_context::state_before_handshake) { MERROR(peer_cxt<<"Requested chain before handshake, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } NOTIFY_RESPONSE_CHAIN_ENTRY::request r; auto sync = find_blockchain_sync_info(remote, resp.m_block_ids, resp.start_height, resp.total_height); r.split_height=sync.split_height; r.chain_height = sync.top_height; r.m_block_ids=sync.hashes; if (r.m_block_ids.size() >= 2) { cryptonote::block b; if (!m_core.get_block_by_hash(r.m_block_ids[1], b)) { MERROR(peer_cxt<<"Failed to handle NOTIFY_REQUEST_CHAIN: first block not found"); return 1; } r.first_block = cryptonote::block_to_blob(b); } MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height=" << r.start_height << ", m_total_height=" << r.total_height << ", m_block_ids.size()=" << r.m_block_ids.size()); post_notify<NOTIFY_RESPONSE_CHAIN_ENTRY>(r, peer_cxt); return 1; } catch(std::exception &ex){ MERROR(peer_cxt<<"Failed to handle NOTIFY_REQUEST_CHAIN."); return 1; } } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> int t_cryptonote_protocol_handler<t_core>::handle_response_chain_entry(int command, NOTIFY_RESPONSE_CHAIN_ENTRY::request& arg, cryptonote_peer_peer_cxt& peer_cxt) { MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()=" << arg.m_block_ids.size() << ", m_start_height=" << arg.start_height << ", m_total_height=" << arg.top_height); MLOG_PEER_STATE("received chain"); if (peer_cxt.m_expect_response != NOTIFY_RESPONSE_CHAIN_ENTRY::ID) { MERROR(peer_cxt<<"Got NOTIFY_RESPONSE_CHAIN_ENTRY out of the blue, dropping connection"); drop_connection(peer_cxt, true, false); return 1; } if (arg.split_height + 1 > peer_cxt.m_sync_start_height) // we expect an overlapping block { MERROR(peer_cxt<<"Got NOTIFY_RESPONSE_CHAIN_ENTRY past expected height, dropping connection"); drop_connection(peer_cxt, true, false); return 1; } if(!arg.m_block_ids.size()) { MERROR(peer_cxt<<"sent empty m_block_ids, dropping connection"); drop_connection(peer_cxt, true, false); return 1; } if (arg.top_height < arg.m_block_ids.size() || arg.start_height > arg.top_height - arg.m_block_ids.size()) { MERROR(peer_cxt<<"sent invalid start/nblocks/height, dropping connection"); drop_connection(peer_cxt, true, false); return 1; } if (arg.top_height >= CRYPTONOTE_MAX_BLOCK_NUMBER || arg.m_block_ids.size() > BLOCKS_IDS_SYNCHRONIZING_MAX_COUNT) { MERROR(peer_cxt<<"sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with top_height=" << arg.top_height << " and block_ids=" << arg.m_block_ids.size()); drop_connection(peer_cxt, false, false); return 1; } peer_cxt.m_expect_response = 0; peer_cxt.m_last_request_time = boost::date_time::not_a_date_time; peer_cxt.m_remote_chain_height = arg.top_height; peer_cxt.m_last_response_height = arg.start_height + arg.m_block_ids.size()-1; peer_cxt.m_needed_blocks.clear(); peer_cxt.m_needed_blocks.reserve(arg.m_block_ids.size()); std::unordered_set<crypto::hash> blocks_found; bool first = true; bool expect_unknown = false; for (auto &bh : arg.m_block_ids) { if (!blocks_found.insert(bh).second) { MERROR(peer_cxt<<"Duplicate blocks in chain entry response, dropping connection"); drop_connection_with_score(peer_cxt, 5, false); return 1; } int where; const bool have_block = m_core.have_block_unlocked(bh, &where); if (first) { if (!have_block && !m_block_queue.requested(bh) && !m_block_queue.have_downloaded(bh)) { MERROR(peer_cxt<<"First block hash is unknown, dropping connection"); drop_connection_with_score(peer_cxt, 5, false); return 1; } if (!have_block) expect_unknown = true; } else { // after the first, blocks may be known or unknown, but if they are known, // they should be at the same height if on the main chain if (have_block) { switch (where) { default: case HAVE_BLOCK_INVALID: MERROR(peer_cxt<<"Block is invalid or known without known type, dropping connection"); drop_connection(peer_cxt, true, false); return 1; case HAVE_BLOCK_MAIN_CHAIN: if (expect_unknown) { MERROR(peer_cxt<<"Block is on the main chain, but we did not expect a known block, dropping connection"); drop_connection_with_score(peer_cxt, 5, false); return 1; } if (m_core.get_block_hash_by_height(arg.start_height + i) != bh) { MERROR(peer_cxt<<"Block is on the main chain, but not at the expected height, dropping connection"); drop_connection_with_score(peer_cxt, 5, false); return 1; } break; case HAVE_BLOCK_ALT_CHAIN: if (expect_unknown) { MERROR(peer_cxt<<"Block is on the alt chain, but we did not expect a known block, dropping connection"); drop_connection_with_score(peer_cxt, 5, false); return 1; } break; } } else expect_unknown = true; } peer_cxt.m_needed_blocks.push_back(bh); first = false; } if (!download_next_span(peer_cxt, false)) { MERROR(peer_cxt<<"Failed to request missing objects, dropping connection"); drop_connection(peer_cxt, false, false); return 1; } if (arg.top_height > m_core.get_target_blockchain_height()) m_core.set_target_blockchain_height(arg.top_height); peer_cxt.m_num_requested = 0; return 1; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> size_t t_cryptonote_protocol_handler<t_core>::skip_unneeded_hashes(cryptonote_peer_context& peer_cxt, bool check_block_queue) const { if(peer_cxt.m_needed_blocks.size()==0) return 0; // take out blocks we already have size_t i = 0; for(i=0;i<peer_cxt.m_needed_blocks.size();++i){ const auto & bh = peer_cxt.m_needed_blocks[i]; if ( !(m_core.have_block(bh) || (check_block_queue && m_block_queue.have_downloaded(bh)))) { break; } } // if we're popping the last hash, record it so we can ask again from that hash, // this prevents never being able to progress on peers we get old hash lists from if (i == peer_cxt.m_needed_blocks.size()) peer_cxt.m_last_known_hash = peer_cxt.m_needed_blocks[i-1]; if (i > 0) { MDEBUG(peer_cxt << "skipping " << i << "/" << peer_cxt.m_needed_blocks.size() << " blocks"); peer_cxt.m_needed_blocks = std::vector<crypto::hash>(peer_cxt.m_needed_blocks.begin() + i, peer_cxt.m_needed_blocks.end()); } return i; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::should_ask_for_pruned_data(cryptonote_peer_context& peer_cxt, uint64_t first_block_height, uint64_t nblocks, bool check_block_weights) const { return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::download_next_span(cryptonote_peer_context& peer_cxt, bool check_having_blocks) { // flush stale spans std::set<boost::uuids::uuid> live_connections; m_p2p->for_each_connection([&](cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{ live_connections.insert(peer_cxt.m_connection_id); return true; }); m_block_queue.flush_stale_spans(live_connections); // if we don't need to get next span, and the block queue is full enough, wait a bit do { size_t nspans = m_block_queue.get_num_filled_spans(); size_t size = m_block_queue.get_data_size(); const uint64_t cur_chain_height = m_core.get_chain_height(); const size_t block_queue_size_threshold = m_block_download_max_size ? m_block_download_max_size : BLOCK_QUEUE_SIZE_THRESHOLD; bool queue_proceed = nspans < BLOCK_QUEUE_NSPANS_THRESHOLD || size < block_queue_size_threshold; // get rid of blocks we already requested, or already have skip_unneeded_hashes(peer_cxt, true); if (peer_cxt.m_needed_blocks.empty() && peer_cxt.m_num_requested == 0) { if (peer_cxt.m_remote_chain_height > m_block_queue.get_next_needed_height(cur_chain_height)) { MERROR(peer_cxt << "Nothing we can request from this peer, and we did not request anything previously"); return false; } MDEBUG(peer_cxt << "Nothing to get from this peer, and it's not ahead of us, all done"); peer_cxt.m_state = cryptonote_peer_context::state_normal; return true; } uint64_t next_block_height; if (peer_cxt.m_needed_blocks.empty()) next_block_height = m_block_queue.get_next_needed_height(cur_chain_height); else next_block_height = peer_cxt.m_last_response_height - peer_cxt.m_needed_blocks.size() + 1; if (proceed) { if (peer_cxt.m_state != cryptonote_peer_context::state_standby) { MDEBUG(peer_cxt, "Block queue is " << nspans << " and " << size << ", resuming"); MLOG_PEER_STATE("resuming"); } break; } // this one triggers if all threads are in standby, which should not happen, // but happened at least once, so we unblock at least one thread if so boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock}; if (sync.owns_lock()) { bool filled = false; boost::posix_time::ptime time; boost::uuids::uuid connection_id; if (m_block_queue.has_next_span(m_core.get_chain_height(), filled, time, connection_id) && filled) { MDEBUG(peer_cxt, "No other thread is adding blocks, and next span needed is ready, resuming"); MLOG_PEER_STATE("resuming"); peer_cxt.m_state = cryptonote_peer_context::state_standby; ++peer_cxt.m_callback_request_count; m_p2p->request_callback(peer_cxt); return true; } else { sync.unlock(); // if this has gone on for too long, drop incoming connection to guard against some wedge state if (!peer_cxt.m_is_income) { const uint64_t now = tools::get_tick_count(); const uint64_t dt = now - m_last_add_end_time; if (m_last_add_end_time && tools::ticks_to_ns(dt) >= DROP_ON_SYNC_WEDGE_THRESHOLD) { MDEBUG(peer_cxt << "ns " << tools::ticks_to_ns(dt) << " from " << m_last_add_end_time << " and " << now); MDEBUG(peer_cxt << "Block addition seems to have wedged, dropping connection"); return false; } } } } if (peer_cxt.m_state != cryptonote_peer_context::state_standby) { if (!queue_proceed) MDEBUG(peer_cxt, "Block queue is " << nspans << " and " << size << ", pausing"); else if (!stripe_proceed_main && !stripe_proceed_secondary) MDEBUG(peer_cxt, "We do not have the stripe required to download another block, pausing"); peer_cxt.m_state = cryptonote_peer_context::state_standby; MLOG_PEER_STATE("pausing"); } return true; } while(0); peer_cxt.m_state = cryptonote_peer_context::state_synchronizing; MDEBUG(peer_cxt << " download_next_span: check " << check_having_blocks << ", m_needed_blocks " << peer_cxt.m_needed_blocks.size() << " lrh " << peer_cxt.m_last_response_height << ", chain "<< m_core.get_chain_height() ); if(peer_cxt.m_needed_blocks.size()) { //we know objects that we need, request this objects NOTIFY_REQUEST_GET_BLOCKS::request req; bool is_next = false; size_t count = 0; MDEBUG(peer_cxt << " span size is 0"); if (peer_cxt.m_last_response_height + 1 < peer_cxt.m_needed_blocks.size()) { MERROR(peer_cxt << " ERROR: inconsistent peer_cxt: lrh " << peer_cxt.m_last_response_height << ", nos " << peer_cxt.m_needed_blocks.size()); peer_cxt.m_needed_blocks.clear(); peer_cxt.m_last_response_height = 0; goto skip; } skip_unneeded_hashes(peer_cxt, false); if (peer_cxt.m_needed_blocks.empty() && peer_cxt.m_num_requested == 0) { if (peer_cxt.m_remote_chain_height > m_block_queue.get_next_needed_height(m_core.get_chain_height())) { MERROR(peer_cxt << "Nothing we can request from this peer, and we did not request anything previously"); return false; } MDEBUG(peer_cxt << "Nothing to get from this peer, and it's not ahead of us, all done"); peer_cxt.m_state = cryptonote_peer_context::state_normal; return true; } const uint64_t first_block_height = peer_cxt.m_last_response_height - peer_cxt.m_needed_blocks.size() + 1; const size_t batch_size = m_core.get_block_sync_batch_size(); const auto span = m_block_queue.start_span(first_block_height, peer_cxt.m_last_response_height, batch_size, peer_cxt.m_connection_id, peer_cxt.m_remote_address, peer_cxt.m_remote_chain_height, peer_cxt.m_needed_blocks); MDEBUG(peer_cxt << " span from " << first_block_height << ": " << span.first << "/" << span.second); MDEBUG(peer_cxt << " span: " << span.first << "/" << span.second << " (" << span.first << " - " << (span.first + span.second - 1) << ")"); if (span.second > 0) { if (!is_next) { const uint64_t first_context_block_height = peer_cxt.m_last_response_height - peer_cxt.m_needed_blocks.size() + 1; uint64_t skip = span.first - first_context_block_height; if (skip > peer_cxt.m_needed_blocks.size()) { MERROR("ERROR: skip " << skip << ", m_needed_blocks " << peer_cxt.m_needed_blocks.size() << ", first_context_block_height" << first_context_block_height); return false; } if (skip > 0) peer_cxt.m_needed_blocks = std::vector<crypto::hash>(peer_cxt.m_needed_blocks.begin() + skip, peer_cxt.m_needed_blocks.end()); if (peer_cxt.m_needed_blocks.size() < span.second) { MERROR("ERROR: span " << span.first << "/" << span.second << ", m_needed_blocks " << peer_cxt.m_needed_blocks.size()); return false; } req.blocks.reserve(req.blocks.size() + span.second); for (size_t n = 0; n < span.second; ++n) { const auto & bh = peer_cxt.m_needed_blocks[n]; req.blocks.push_back(bh); ++count; peer_cxt.m_requested_objects.insert(bh); } peer_cxt.m_needed_blocks = std::vector<crypto::hash>(peer_cxt.m_needed_blocks.begin() + span.second, peer_cxt.m_needed_blocks.end()); } // if we need to ask for full data and that peer does not have the right stripe, we can't ask it peer_cxt.m_last_request_time = boost::posix_time::microsec_clock::universal_time(); peer_cxt.m_sync_start_height = span.first; peer_cxt.m_expect_response = NOTIFY_RESPONSE_GET_BLOCKS::ID; MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_GET_BLOCKS: blocks.size()=" << req.blocks.size() << "requested blocks count=" << count ,< " from " << span.first << ", first hash " << req.blocks.front()); peer_cxt.m_num_requested += req.blocks.size(); post_notify<NOTIFY_REQUEST_GET_BLOCKS>(req, peer_cxt); MLOG_PEER_STATE("requesting objects"); return true; } // we can do nothing, so drop this peer to make room for others unless we think we've downloaded all we need const uint64_t blockchain_height = m_core.get_chain_height(); if (std::max(blockchain_height, m_block_queue.get_next_needed_height(blockchain_height)) >= m_core.get_target_blockchain_height()) { peer_cxt.m_state = cryptonote_peer_context::state_normal; MLOG_PEER_STATE("Nothing to do for now, switching to normal state"); return true; } MLOG_PEER_STATE("We can download nothing from this peer, dropping"); return false; } skip: peer_cxt.m_needed_blocks.clear(); // we might have been called from the "received chain entry" handler, and end up // here because we can't use any of those blocks (maybe because all of them are // actually already requested). In this case, if we can add blocks instead, do so if (m_core.get_chain_height() < m_core.get_target_blockchain_height()) { const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock}; if (sync.owns_lock()) { uint64_t start_height; std::vector<cryptonote::block_complete_entry> blocks; boost::uuids::uuid span_con_id; epee::net_utils::network_address span_origin; if (m_block_queue.get_next_span(start_height, blocks, span_con_id, span_origin, true)) { MDEBUG(peer_cxt, "No other thread is adding blocks, resuming"); MLOG_PEER_STATE("will try to add blocks next"); peer_cxt.m_state = cryptonote_peer_context::state_standby; ++peer_cxt.m_callback_request_count; m_p2p->request_callback(peer_cxt); return true; } } } if(peer_cxt.m_last_response_height < peer_cxt.m_remote_chain_height-1) {//we have to fetch more objects ids, request blockchain entry NOTIFY_REQUEST_CHAIN::request r {m_core.get_blockchain().get_short_chain_history()}; peer_cxt.m_sync_start_height = m_core.get_chain_height(); { // we'll want to start off from where we are on that peer, which may not be added yet if (peer_cxt.m_last_known_hash != crypto::null_hash && r.block_ids.front() != peer_cxt.m_last_known_hash) { peer_cxt.m_sync_start_height = std::numeric_limits<uint64_t>::max(); r.block_ids.push_front(peer_cxt.m_last_known_hash); } } peer_cxt.m_last_request_time = boost::posix_time::microsec_clock::universal_time(); peer_cxt.m_expect_response = NOTIFY_RESPONSE_CHAIN_ENTRY::ID; MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() << ", start_from_current_chain " << start_from_current_chain); post_notify<NOTIFY_REQUEST_CHAIN>(r, peer_cxt); MLOG_PEER_STATE("requesting chain"); }else { CHECK_AND_ASSERT_MES(peer_cxt.m_last_response_height == peer_cxt.m_remote_chain_height-1 && !peer_cxt.m_needed_blocks.size()&& !peer_cxt.m_requested_objects.size(), false, "request_missing_blocks final condition failed!" << "\r\nm_last_response_height=" << peer_cxt.m_last_response_height << "\r\nm_remote_blockchain_height=" << peer_cxt.m_remote_chain_height << "\r\nm_needed_objects.size()=" << peer_cxt.m_needed_blocks.size() << "\r\nm_requested_objects.size()=" << peer_cxt.m_requested_objects.size() << "\r\non connection [" << epee::net_utils::print_connection_context_short(peer_cxt)<< "]"); peer_cxt.m_state = cryptonote_peer_context::state_normal; if (peer_cxt.m_remote_chain_height >= m_core.get_target_blockchain_height()) { if (m_core.get_chain_height() >= m_core.get_target_blockchain_height()) { MGINFO_GREEN("SYNCHRONIZED OK"); on_connection_synchronized(); } } else { MINFO(peer_cxt << " we've reached this peer's blockchain height (theirs " << peer_cxt.m_remote_chain_height << ", our target " << m_core.get_target_blockchain_height()); } } return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::on_connection_synchronized() { bool val_expected = false; uint64_t cur_chain_height = m_core.get_chain_height(); if( m_synchronized.compare_exchange_strong(val_expected, true)) { if ((cur_chain_height > m_sync_start_height) && (m_sync_spans_downloaded > 0)) { uint64_t synced_blocks = cur_chain_height - m_sync_start_height; // Report only after syncing an "interesting" number of blocks: if (synced_blocks > 20) { const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); uint64_t synced_seconds = (now - m_sync_start_time).total_seconds(); if (synced_seconds == 0) { synced_seconds = 1; } float blocks_per_second = (1000 * synced_blocks / synced_seconds) / 1000.0f; MGINFO_YELLOW("Synced " << synced_blocks << " blocks in " << tools::get_human_readable_timespan(synced_seconds) << " (" << blocks_per_second << " blocks per second)"); } } MGINFO_YELLOW(ENDL << "**********************************************************************" << ENDL << "You are now synchronized with the network." << ENDL); m_sync_timer.pause(); { const uint64_t sync_time = m_sync_timer.value(); const uint64_t add_time = m_add_timer.value(); if (sync_time && add_time) { MCLOG_YELLOW(el::Level::Info, "sync-info", "Sync time: " << sync_time/1e9/60 << " min, idle time " << (100.f * (1.0f - add_time / (float)sync_time)) << "%" << ", " << (10 * m_sync_download_objects_size / 1024 / 1024) / 10.f << " MB downloaded, " << 100.0f * m_sync_old_spans_downloaded / m_sync_spans_downloaded << "% old spans, " << 100.0f * m_sync_bad_spans_downloaded / m_sync_spans_downloaded << "% bad spans"); } } } m_p2p->clear_used_stripe_peers(); // ask for txpool complement from any suitable node if we did not yet val_expected = true; if (m_ask_for_txpool_complement.compare_exchange_strong(val_expected, false)) { m_p2p->for_each_connection([&](cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags)->bool { if(peer_cxt.m_state < cryptonote_peer_context::state_synchronizing) { MDEBUG(peer_cxt << "not ready, ignoring"); return true; } if (!request_txpool_complement(peer_cxt)) { MERROR(peer_cxt << "Failed to request txpool complement"); return true; } return false; }); } return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> size_t t_cryptonote_protocol_handler<t_core>::get_synchronizing_connections_count() { size_t count = 0; m_p2p->for_each_connection([&](cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{ if(peer_cxt.m_state == cryptonote_peer_context::state_synchronizing) ++count; return true; }); return count; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::relay_block(const blobdata& blob, const uint64_t b_height, cryptonote_peer_context& exclude_context) { NOTIFY_NEW_FLUFFY_BLOCK::request fluffy_arg{}; fluffy_arg.cur_chain_height = b_height; fluffy_arg.b = blob; // sort peers between fluffy ones and others std::vector< boost::uuids::uuid> fluffyConnections; m_p2p->for_each_connection([this, &exclude_context, &fullConnections, &fluffyConnections](cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { // peer_id also filters out connections before handshake if (peer_id && exclude_context.m_connection_id != peer_cxt.m_connection_id ) { fluffyConnections.push_back( peer_cxt.m_connection_id); } return true; }); // send fluffy ones first, we want to encourage people to run that if (!fluffyConnections.empty()) { epee::levin::message_writer fluffyBlob{32 * 1024}; epee::serialization::store_t_to_binary(fluffy_arg, fluffyBlob.buffer); m_p2p->relay_notify_to_list(NOTIFY_NEW_FLUFFY_BLOCK::ID, std::move(fluffyBlob), std::move(fluffyConnections)); } return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::relay_transactions(NOTIFY_NEW_TRANSACTIONS::request& arg, const boost::uuids::uuid& source, epee::net_utils::zone zone, relay_method tx_relay) { /* Push all outgoing transactions to this function. The behavior needs to identify how the transaction is going to be relayed, and then update the local mempool before doing the relay. The code was already updating the DB twice on received transactions - it is difficult to workaround this due to the internal design. */ return m_p2p->send_txs(std::move(arg.txs), source, tx_relay) ; } template<class t_core> uint64_t t_cryptonote_protocol_handler<t_core>::get_chain_height()const { return m_core.get_chain_height(); } template<class t_core> void t_cryptonote_protocol_handler<t_core>::on_transactions_relayed(epee::span<const cryptonote::blobdata> tx_blobs, relay_method tx_relay) { m_core.on_transactions_relayed(tx_blobs,tx_relay); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::request_txpool_complement(cryptonote_peer_context &peer_cxt) { NOTIFY_GET_TXPOOL_COMPLEMENT::request r = {}; if (!m_core.get_pool_transaction_hashes(r.hashes, false)) { MERROR("Failed to get txpool hashes"); return false; } MLOG_P2P_MESSAGE("-->>NOTIFY_GET_TXPOOL_COMPLEMENT: hashes.size()=" << r.hashes.size() ); post_notify<NOTIFY_GET_TXPOOL_COMPLEMENT>(r, peer_cxt); MLOG_PEER_STATE("requesting txpool complement"); return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::hit_score(cryptonote_peer_context &peer_cxt, int32_t score) { if (score <= 0) { MERROR("Negative score hit"); return; } peer_cxt.m_score -= score; if (peer_cxt.m_score <= DROP_PEERS_ON_SCORE) drop_connection_with_score(peer_cxt, 5, false); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> std::string t_cryptonote_protocol_handler<t_core>::get_peers_overview() const { std::stringstream ss; const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); m_p2p->for_each_connection([&](const cryptonote_peer_context &ctx, nodetool::peerid_type peer_id, uint32_t support_flags) { const uint32_t stripe = tools::get_pruning_stripe(ctx.m_pruning_seed); char state_char = cryptonote::get_protocol_state_char(ctx.m_state); ss << stripe + state_char; if (ctx.m_last_request_time != boost::date_time::not_a_date_time) ss << (((now - ctx.m_last_request_time).total_microseconds() > IDLE_PEER_KICK_TIME) ? "!" : "?"); ss << + " "; return true; }); return ss.str(); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> std::pair<uint32_t, uint32_t> t_cryptonote_protocol_handler<t_core>::get_next_needed_pruning_stripe() const { const uint64_t cur_chain_height = m_core.get_chain_height(); const uint64_t want_height_from_block_queue = m_block_queue.get_next_needed_height(cur_chain_height); const uint64_t want_height = std::max(cur_chain_height, want_height_from_block_queue); uint64_t blockchain_height = m_core.get_target_blockchain_height(); // if we don't know the remote chain size yet, assume infinitely large so we get the right stripe if we're not near the tip if (blockchain_height == 0) blockchain_height = CRYPTONOTE_MAX_BLOCK_NUMBER; const uint32_t next_pruning_stripe = tools::get_pruning_stripe(want_height, blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES); if (next_pruning_stripe == 0) return std::make_pair(0, 0); // if we already have a few peers on this stripe, but none on next one, try next one unsigned int n_next = 0, n_subsequent = 0, n_others = 0; const uint32_t subsequent_pruning_stripe = 1 + next_pruning_stripe % (1<<CRYPTONOTE_PRUNING_LOG_STRIPES); m_p2p->for_each_connection([&](const cryptonote_peer_context &peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { if (peer_cxt.m_state >= cryptonote_peer_context::state_synchronizing) { if (peer_cxt.m_pruning_seed == 0 || tools::get_pruning_stripe(peer_cxt.m_pruning_seed) == next_pruning_stripe) ++n_next; else if (tools::get_pruning_stripe(peer_cxt.m_pruning_seed) == subsequent_pruning_stripe) ++n_subsequent; else ++n_others; } return true; }); const bool use_next = (n_next > m_max_out_peers / 2 && n_subsequent <= 1) || (n_next > 2 && n_subsequent == 0); const uint32_t ret_stripe = use_next ? subsequent_pruning_stripe: next_pruning_stripe; MIDEBUG(const std::string po = get_peers_overview(), "get_next_needed_pruning_stripe: want height " << want_height << " (" << cur_chain_height << " from blockchain, " << want_height_from_block_queue << " from block queue), stripe " << next_pruning_stripe << " (" << n_next << "/" << m_max_out_peers << " on it and " << n_subsequent << " on " << subsequent_pruning_stripe << ", " << n_others << " others) -> " << ret_stripe << " (+" << (ret_stripe - next_pruning_stripe + (1 << CRYPTONOTE_PRUNING_LOG_STRIPES)) % (1 << CRYPTONOTE_PRUNING_LOG_STRIPES) << "), current peers " << po); return std::make_pair(next_pruning_stripe, ret_stripe); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::needs_new_sync_connections() const { const uint64_t target = m_core.get_target_blockchain_height(); const uint64_t height = m_core.get_chain_height(); if (target && target <= height) return false; size_t n_out_peers = 0; m_p2p->for_each_connection([&](cryptonote_peer_context& ctx, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{ if (!ctx.m_is_income) ++n_out_peers; return true; }); if (n_out_peers >= m_max_out_peers) return false; return true; } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> bool t_cryptonote_protocol_handler<t_core>::is_busy_syncing() { const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock}; return !sync.owns_lock(); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::drop_connection_with_score(cryptonote_peer_context &peer_cxt, unsigned score, bool flush_all_spans) { MDEBUG(peer_cxt<<"dropping connection id " << peer_cxt.m_connection_id << " (pruning seed " << epee::string_tools::to_string_hex(peer_cxt.m_pruning_seed) << "), score " << score << ", flush_all_spans " << flush_all_spans); if (score > 0) m_p2p->add_host_fail(peer_cxt.m_remote_address, score); m_block_queue.flush_spans(peer_cxt.m_connection_id, flush_all_spans); m_p2p->drop_connection(peer_cxt); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::drop_connection(cryptonote_peer_context &peer_cxt, bool add_fail, bool flush_all_spans) { return drop_connection_with_score(peer_cxt, add_fail ? 1 : 0, flush_all_spans); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::drop_connections(const epee::net_utils::network_address address) { MWARNING("dropping connections to " << address.str()); m_p2p->add_host_fail(address, 5); std::vector<boost::uuids::uuid> drop; m_p2p->for_each_connection([&](const auto& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { if (address.is_same_host(peer_cxt.m_remote_address)) drop.push_back(peer_cxt.m_connection_id); return true; }); for (const auto &id: drop) { m_block_queue.flush_spans(id, true); m_p2p->for_connection(id, [&](auto& peer_cxt, nodetool::peerid_type peer_id, uint32_t f)->bool{ drop_connection(peer_cxt, true, false); return true; }); } } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::on_connection_close(cryptonote_peer_context &peer_cxt) { uint64_t target = 0; m_p2p->for_each_connection([&](const cryptonote_peer_context& peer_cxt, nodetool::peerid_type peer_id, uint32_t support_flags) { if (peer_cxt.m_state >= cryptonote_peer_context::state_synchronizing && peer_cxt.m_connection_id != peer_cxt.m_connection_id) target = std::max(target, peer_cxt.m_remote_chain_height); return true; }); const uint64_t previous_target = m_core.get_target_blockchain_height(); if (target < previous_target) { MINFO("Target height decreasing from " << previous_target << " to " << target); m_core.set_target_blockchain_height(target); if (target == 0 && peer_cxt.m_state > cryptonote_peer_context::state_before_handshake && !m_stopping) { MCWARNING("global", "monerod is now disconnected from the network"); m_ask_for_txpool_complement = true; } } m_block_queue.flush_spans(peer_cxt.m_connection_id, false); MLOG_PEER_STATE("closed"); } //------------------------------------------------------------------------------------------------------------------------ template<class t_core> void t_cryptonote_protocol_handler<t_core>::stop() { m_stopping = true; m_core.stop(); } } // namespace
44.523283
404
0.630074
[ "vector" ]
093da4cb9f98c004876f1c52d5ca80a7b774069b
8,195
cpp
C++
codes/misc/LOJ_2092.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/misc/LOJ_2092.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/misc/LOJ_2092.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//misaka will carry me to master #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <functional> #include <numeric> #include <set> #include <map> #include <array> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() #define pb push_back #define mp make_pair #define kill(x, s) {int COND = x; if(COND){ cout << s << "\n"; return ; }} const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1, ll_max = 1e18; const int MX = 'HUG', int_max = 0x3f3f3f3f; struct { template<class T> operator T() { T x; std::cin >> x; return x; } } in; using namespace std; #define lc c[0] #define rc c[1] #define ile(u) (tr[tr[u].par].lc != u) struct splay_tree{ struct value{ ll val; int sz; ll aggr; ll mn, mx; int u; value(){val = sz = u = 0; aggr = 0ll; mx = -ll_max; mn = ll_max;} value(ll c, ll b, ll d, ll e, int s, int v){val = c, aggr = b, mn = d, mx = e, sz = s, u = v; } }; struct tag{ ll add, mul, rev; tag(ll a, ll b, ll c){ add = a, mul = b, rev = c; } tag(){ add = 0, mul = 1, rev = 0;} tag operator * (const tag& b) const{ if(isid()) return b; if(b.isid()) return *this; return tag( (1ll*mul*b.add%mod + add)%mod, 1ll*mul*b.mul%mod, rev^b.rev); } value operator + (const value& b) const{ if(isid()) return b; return value((1ll*mul*b.val +add), (1ll*mul*b.aggr +1ll*add*b.sz), 1ll*mul*b.mn +add, 1ll*mul*b.mx + add, b.sz, b.u); } bool isid() const{ return (add == 0) && (mul == 1) && (rev == 0); } //bool operator == (const tag& b) const{ //return (add == b.add) && (mul == b.mul) && (rev == b.rev); //} } ; struct node{ int par, pptr; int c[2]; value v; tag t; node(){ par =c[0] = c[1] = pptr = 0; } } ; vector<node> tr; vector<int> ptr; void pull(int u){ //assert(u); tr[u].v.aggr = (tr[tr[u].lc].v.aggr + tr[tr[u].rc].v.aggr + tr[u].v.val) %mod; tr[u].v.sz = tr[tr[u].lc].v.sz + tr[tr[u].rc].v.sz + 1; tr[u].v.mn = min({tr[u].v.val, tr[tr[u].lc].v.mn, tr[tr[u].rc].v.mn}); tr[u].v.mx = max({tr[u].v.val, tr[tr[u].lc].v.mx, tr[tr[u].rc].v.mx}); } void apply(int u, const tag& t){ if(!u || t.isid()) return ; //assert(t.mul == 1 && t.add == 0); tr[u].t = t * tr[u].t; tr[u].v = t + tr[u].v; //tr[u].aggr = t + tr[u].v; } void push(int u){ if(!u) return ; if(tr[u].t.isid()) return ; if(tr[u].t.rev){ swap(tr[u].lc, tr[u].rc); } apply(tr[u].lc, tr[u].t); apply(tr[u].rc, tr[u].t); tr[u].t = tag(); } splay_tree(){ node zero = node(); zero.v = value(); zero.t = tag(); tr.pb(zero); } splay_tree(int n){ *this = splay_tree(); ptr = vector<int>(n+5, 0); for(int i = 1; i<=n; i++){ node tmp = node(); tmp.v = value(0, 0, ll_max, -ll_max, 1, i); tmp.t = tag(); tmp.pptr = 0; ptr[i] = sz(tr); tr.pb(tmp); assert(ptr[i] == i); } } void pr(int u){ static int dep = 0; if(!u) return ; dep++; //push(u); pr(tr[u].lc); //if(tr[u].v.val) cerr << tr[u].v.u << " "; pr(tr[u].rc); dep--; if(dep == 0) cout << "\n"; } void rotate(int u, int dir){ int r = u; int g = tr[u].c[dir]; int a = tr[tr[u].c[dir]].c[dir^1]; //order of pushing: tr[u].par, u, g //changes to c push(tr[u].par); push(u); push(g); if(tr[r].par){ if(!ile(r)) tr[tr[r].par].lc = g; else tr[tr[r].par].rc = g; } assert(r && g); tr[g].c[dir^1] = r; tr[r].c[dir] = a; //changes to par tr[g].par = tr[r].par; tr[r].par = g; if(a) tr[a].par = r; //order of pulling: r, g, tr[g].par pull(r); pull(g); if(tr[g].par) pull(tr[g].par); } void prop_all(int u){ if(!u) return ; prop_all(tr[u].par); push(u); } void splay(int u){ prop_all(u); int pptr = 0; for(int j = u; j; j = tr[j].par){ if(tr[j].par == 0){ pptr = tr[j].pptr; tr[j].pptr = 0; } } while(tr[u].par){ int p = tr[u].par, gp = tr[p].par; //if(gp) push(gp); //if(p) push(p); //if(u) push(u); if(gp == 0){ //zig rotate(p, ile(u)); }else if(ile(p)^ile(u)){ //zig zag rotate(p, ile(u)); rotate(gp, ile(u)); }else{ //zig zig rotate(gp, ile(p)); rotate(p, ile(u)); } } tr[u].pptr = pptr; pull(u); assert(tr[0].lc == tr[0].rc && tr[0].rc == 0 && tr[0].pptr == 0); } int find(int u){ splay(ptr[u]); return ptr[u]; } void dettach(int v, int c){ //splay(v); push(v); int rem = tr[v].c[c]; if(!rem) return ; tr[v].c[c] = 0; tr[rem].par = 0; tr[rem].pptr = v; assert(rem != v); //pull(v); } }; #undef lc #undef rc #undef ile struct link_cut_tree{ splay_tree aux; link_cut_tree(){ aux = splay_tree(); } link_cut_tree(int n){ aux = splay_tree(n); } int access(int x){ int u = aux.find(x); aux.dettach(u, 1); int lca = u; while(aux.tr[u].pptr){ int v = aux.tr[u].pptr; lca = v; //aux.splay(v); //aux.pr(v); aux.splay(v); assert(aux.tr[v].par == 0); aux.dettach(v, 1); aux.tr[v].c[1] = u; //aux.pull(v); aux.tr[u].par = v; aux.tr[u].pptr = 0; //idk //aux.splay(u); //sunglas u = v; //assert(aux.tr[u].par == 0); } aux.splay(u); assert(aux.tr[u].par == 0); return aux.tr[lca].v.u; } void reroot(int x){ int u = aux.find(x); access(x); aux.splay(u); aux.apply(u, splay_tree::tag(0, 1, 1)); } int lca(int a, int b){ if(a == b){ access(a); return a; } access(a); return access(b); //trust? } void link(int a, int b){ reroot(b); aux.tr[aux.find(b)].pptr = aux.find(a); } void cut(int a, int b){ reroot(a); access(b); aux.dettach(aux.find(b), 0); aux.tr[aux.find(a)].pptr = 0; } void update(int a, int b, splay_tree::tag t){ //if(a == b){ //aux.splay(a); //aux.tr[aux.find(a)].v.val += t.add; //aux.pull(aux.find(a)); //aux.apply(aux.find(a), t); //return ; //} //cout << a << " " << b << "\n"; reroot(a); access(b); //aux.pr(b); aux.apply(aux.find(b), t); } void update(int u, int val){ aux.splay(u); aux.tr[aux.find(u)].v.val = val; } int parent(int x){ access(aux.find(x)); aux.splay(x); return aux.tr[x].c[0]; } ll sum(int a, int b){ reroot(a); access(b); return aux.tr[aux.find(b)].v.aggr; } ll qmin(int a, int b){ reroot(a); access(b); return aux.tr[aux.find(b)].v.mn; } ll qmax(int a, int b){ reroot(a); access(b); //aux.pr(b); return aux.tr[aux.find(b)].v.mx; } }; vector<array<int, 3>> adj[MX], queries[MX]; int isq[MX], ans[MX]; vector<pair<int, int>> range; //int n, q; void solve(){ int n = in, q = in; link_cut_tree lct = link_cut_tree(2*q+10); //better safe than sorry lct.update(1, 1); int st = q+1; range.pb(mp(1, n)); lct.link(st, 1); int nd = 1; for(int i = 1; i<=q; i++){ int op = in; if(op == 0){ int l = in, r = in; nd++; adj[l].pb({0, st, nd}); adj[r+1].pb({1, st, nd}); lct.update(nd, 1); //cout << nd << "\n"; range.pb(mp(l, r)); }else if(op == 1){ int l = in, r = in, u = in; l = max(l, range[u-1].first); r = min(r, range[u-1].second); if(l <= r){ lct.link(st, st+1); adj[l].pb({1, st, st+1}); adj[l].pb({0, st+1, u}); adj[r+1].pb({1, st+1, u}); adj[r+1].pb({0, st, st+1}); st++; } }else{ int l = in, u = in, v = in; queries[l].pb({i, u, v}); isq[i] = 1; } } for(int i = 1; i<=n; i++){ for(const auto& [op, u, v] : adj[i]){ if(op == 0){ lct.link(u, v); }else{ lct.cut(u, v); } } for(const auto& [ind, u, v] : queries[i]){ lct.reroot(1); //lct.aux.pr(1); int l = lct.lca(u, v); int cur = 0; //lct.access(u); cur += lct.sum(1, u); //cerr << cur << " "; lct.access(v); cur += lct.sum(1, v); //cerr << cur << " "; lct.access(l); cur += -2*lct.sum(1, l); //cerr << cur << "\n"; //cerr << u << " "<< v << " " << l << "\n"; ans[ind] = cur; } } for(int i = 1; i<=q; i++){ if(isq[i]){ cout << ans[i] << "\n"; } } } int main(){ cin.tie(0) -> sync_with_stdio(0); int T = 1; //cin >> T; for(int i = 1; i<=T; i++){ solve(); } return 0; }
19.987805
121
0.506284
[ "vector" ]
09461dc999e60af2ec031278241413283128f8d4
1,184
cc
C++
misc_cxx/vector2transform.cc
chenchr/PoseNet
d8c0d1071db21652a7cb4b2715747ef346c8f706
[ "MIT" ]
2
2018-05-09T03:35:42.000Z
2018-05-10T00:13:56.000Z
misc_cxx/vector2transform.cc
chenchr/PoseNet
d8c0d1071db21652a7cb4b2715747ef346c8f706
[ "MIT" ]
null
null
null
misc_cxx/vector2transform.cc
chenchr/PoseNet
d8c0d1071db21652a7cb4b2715747ef346c8f706
[ "MIT" ]
null
null
null
#include <Eigen/Dense> #include <Eigen/Geometry> #include <iostream> #include <fstream> #include <vector> using namespace std; void vector2transform(vector<double> &vec, Eigen::Matrix4d &t){ t(0,3) = vec[0]; t(1,3) = vec[1]; t(2,3) = vec[2]; Eigen::Quaterniond temp; temp.w() = vec[3]; temp.x() = vec[4]; temp.y() = vec[5]; temp.z() = vec[6]; t.block(0,0,3,3) = temp.toRotationMatrix(); } int main(){ string path_in = "/home/chenchr/ttx.txt"; fstream file_in(path_in, ios::in); vector<vector<double> > all; for(int i=0; i<10; ++i){ double x, y, z, qw, qx, qy, qz; char temp; file_in >> x >> temp >> y >> temp >> z >> temp >> qw >> temp >> qx >> temp >> qy >> temp >> qz; all.push_back({x, y, z, qw, qx, qy, qz}); } vector<Eigen::Matrix4d> all_T; for(int i=0; i<10; ++i){ all_T.push_back(Eigen::Matrix4d::Identity()); vector2transform(all[i], all_T[i]); } for(int i=0; i<10; ++i){ cout << i << ": " << endl; for(int j=0; j<7; ++j) cout << all[i][j] << " "; cout << endl; cout << all_T[i] << endl; } return 0; }
26.909091
103
0.51098
[ "geometry", "vector" ]
094a699f67d131bace59b0fee33994115b7cfa07
14,255
hh
C++
src/OpenMesh/Core/Mesh/SmartHandles.hh
marksisson/OpenMesh.OpenMesh
a936d398fbb840db6ec6abd504ac4dc775da6b3c
[ "BSD-3-Clause" ]
null
null
null
src/OpenMesh/Core/Mesh/SmartHandles.hh
marksisson/OpenMesh.OpenMesh
a936d398fbb840db6ec6abd504ac4dc775da6b3c
[ "BSD-3-Clause" ]
null
null
null
src/OpenMesh/Core/Mesh/SmartHandles.hh
marksisson/OpenMesh.OpenMesh
a936d398fbb840db6ec6abd504ac4dc775da6b3c
[ "BSD-3-Clause" ]
null
null
null
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2019, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * ========================================================================= */ #ifndef OPENMESH_POLYCONNECTIVITY_INTERFACE_INCLUDE #error Do not include this directly, include instead PolyConnectivity.hh #endif//OPENMESH_POLYCONNECTIVITY_INTERFACE_INCLUDE //== NAMESPACES =============================================================== namespace OpenMesh { //== FORWARD DECLARATION ====================================================== struct SmartVertexHandle; struct SmartHalfedgeHandle; struct SmartEdgeHandle; struct SmartFaceHandle; //== CLASS DEFINITION ========================================================= /// Base class for all smart handle types class OPENMESHDLLEXPORT SmartBaseHandle { public: explicit SmartBaseHandle(const PolyConnectivity* _mesh = nullptr) : mesh_(_mesh) {} /// Get the underlying mesh of this handle const PolyConnectivity* mesh() const { return mesh_; } // TODO: should operators ==, !=, < look at mesh_? private: const PolyConnectivity* mesh_; }; /// Smart version of VertexHandle contains a pointer to the corresponding mesh and allows easier access to navigation methods struct OPENMESHDLLEXPORT SmartVertexHandle : public SmartBaseHandle, VertexHandle { explicit SmartVertexHandle(int _idx=-1, const PolyConnectivity* _mesh = nullptr) : SmartBaseHandle(_mesh), VertexHandle(_idx) {} /// Returns an outgoing halfedge SmartHalfedgeHandle out() const; /// Returns an outgoing halfedge SmartHalfedgeHandle halfedge() const; // alias for out /// Returns an incoming halfedge SmartHalfedgeHandle in() const; /// Returns a range of faces incident to the vertex (PolyConnectivity::vf_range()) PolyConnectivity::ConstVertexFaceRange faces() const; /// Returns a range of edges incident to the vertex (PolyConnectivity::ve_range()) PolyConnectivity::ConstVertexEdgeRange edges() const; /// Returns a range of vertices adjacent to the vertex (PolyConnectivity::vv_range()) PolyConnectivity::ConstVertexVertexRange vertices() const; /// Returns a range of outgoing halfedges incident to the vertex (PolyConnectivity::voh_range()) PolyConnectivity::ConstVertexIHalfedgeRange incoming_halfedges() const; /// Returns a range of incoming halfedges incident to the vertex (PolyConnectivity::vih_range()) PolyConnectivity::ConstVertexOHalfedgeRange outgoing_halfedges() const; /// Returns valence of the vertex uint valence() const; /// Returns true iff the vertex is incident to a boundary halfedge bool is_boundary() const; /// Returns true iff (the mesh at) the vertex is two-manifold ? bool is_manifold() const; }; struct OPENMESHDLLEXPORT SmartHalfedgeHandle : public SmartBaseHandle, HalfedgeHandle { explicit SmartHalfedgeHandle(int _idx=-1, const PolyConnectivity* _mesh = nullptr) : SmartBaseHandle(_mesh), HalfedgeHandle(_idx) {} /// Returns next halfedge handle SmartHalfedgeHandle next() const; /// Returns previous halfedge handle SmartHalfedgeHandle prev() const; /// Returns opposite halfedge handle SmartHalfedgeHandle opp() const; /// Returns vertex pointed to by halfedge SmartVertexHandle to() const; /// Returns vertex at start of halfedge SmartVertexHandle from() const; /// Returns incident edge of halfedge SmartEdgeHandle edge() const; /// Returns incident face of halfedge SmartFaceHandle face() const; /// Returns true iff the halfedge is on the boundary (i.e. it has no corresponding face) bool is_boundary() const; }; struct OPENMESHDLLEXPORT SmartEdgeHandle : public SmartBaseHandle, EdgeHandle { explicit SmartEdgeHandle(int _idx=-1, const PolyConnectivity* _mesh = nullptr) : SmartBaseHandle(_mesh), EdgeHandle(_idx) {} /// Returns one of the two halfedges of the edge SmartHalfedgeHandle halfedge(unsigned int _i) const; /// Shorthand for halfedge() SmartHalfedgeHandle h(unsigned int _i) const; /// Shorthand for halfedge(0) SmartHalfedgeHandle h0() const; /// Shorthand for halfedge(1) SmartHalfedgeHandle h1() const; /// Returns one of the two incident vertices of the edge SmartVertexHandle vertex(unsigned int _i) const; /// Shorthand for vertex() SmartVertexHandle v(unsigned int _i) const; /// Shorthand for vertex(0) SmartVertexHandle v0() const; /// Shorthand for vertex(1) SmartVertexHandle v1() const; /// Returns true iff the edge lies on the boundary (i.e. one of the halfedges is boundary) bool is_boundary() const; }; struct OPENMESHDLLEXPORT SmartFaceHandle : public SmartBaseHandle, FaceHandle { explicit SmartFaceHandle(int _idx=-1, const PolyConnectivity* _mesh = nullptr) : SmartBaseHandle(_mesh), FaceHandle(_idx) {} /// Returns one of the halfedges of the face SmartHalfedgeHandle halfedge() const; /// Returns a range of vertices incident to the face (PolyConnectivity::fv_range()) PolyConnectivity::ConstFaceVertexRange vertices() const; /// Returns a range of halfedges of the face (PolyConnectivity::fh_range()) PolyConnectivity::ConstFaceHalfedgeRange halfedges() const; /// Returns a range of edges of the face (PolyConnectivity::fv_range()) PolyConnectivity::ConstFaceEdgeRange edges() const; /// Returns a range adjacent faces of the face (PolyConnectivity::ff_range()) PolyConnectivity::ConstFaceFaceRange faces() const; /// Returns the valence of the face uint valence() const; /// Returns true iff the face lies at the boundary (i.e. one of the edges is boundary) bool is_boundary() const; }; /// Creats a SmartVertexHandle from a VertexHandle and a Mesh inline SmartVertexHandle make_smart(VertexHandle _vh, const PolyConnectivity* _mesh) { return SmartVertexHandle (_vh.idx(), _mesh); } /// Creats a SmartHalfedgeHandle from a HalfedgeHandle and a Mesh inline SmartHalfedgeHandle make_smart(HalfedgeHandle _hh, const PolyConnectivity* _mesh) { return SmartHalfedgeHandle(_hh.idx(), _mesh); } /// Creats a SmartEdgeHandle from an EdgeHandle and a Mesh inline SmartEdgeHandle make_smart(EdgeHandle _eh, const PolyConnectivity* _mesh) { return SmartEdgeHandle (_eh.idx(), _mesh); } /// Creats a SmartFaceHandle from a FaceHandle and a Mesh inline SmartFaceHandle make_smart(FaceHandle _fh, const PolyConnectivity* _mesh) { return SmartFaceHandle (_fh.idx(), _mesh); } /// Creats a SmartVertexHandle from a VertexHandle and a Mesh inline SmartVertexHandle make_smart(VertexHandle _vh, const PolyConnectivity& _mesh) { return SmartVertexHandle (_vh.idx(), &_mesh); } /// Creats a SmartHalfedgeHandle from a HalfedgeHandle and a Mesh inline SmartHalfedgeHandle make_smart(HalfedgeHandle _hh, const PolyConnectivity& _mesh) { return SmartHalfedgeHandle(_hh.idx(), &_mesh); } /// Creats a SmartEdgeHandle from an EdgeHandle and a Mesh inline SmartEdgeHandle make_smart(EdgeHandle _eh, const PolyConnectivity& _mesh) { return SmartEdgeHandle (_eh.idx(), &_mesh); } /// Creats a SmartFaceHandle from a FaceHandle and a Mesh inline SmartFaceHandle make_smart(FaceHandle _fh, const PolyConnectivity& _mesh) { return SmartFaceHandle (_fh.idx(), &_mesh); } // helper to convert Handle Types to Smarthandle Types template <typename HandleT> struct SmartHandle; template <> struct SmartHandle<VertexHandle> { using type = SmartVertexHandle; }; template <> struct SmartHandle<HalfedgeHandle> { using type = SmartHalfedgeHandle; }; template <> struct SmartHandle<EdgeHandle> { using type = SmartEdgeHandle; }; template <> struct SmartHandle<FaceHandle> { using type = SmartFaceHandle; }; inline SmartHalfedgeHandle SmartVertexHandle::out() const { assert(mesh() != nullptr); return make_smart(mesh()->halfedge_handle(*this), mesh()); } inline SmartHalfedgeHandle SmartVertexHandle::halfedge() const { return out(); } inline SmartHalfedgeHandle SmartVertexHandle::in() const { return out().opp(); } inline uint SmartVertexHandle::valence() const { assert(mesh() != nullptr); return mesh()->valence(*this); } inline bool SmartVertexHandle::is_boundary() const { assert(mesh() != nullptr); return mesh()->is_boundary(*this); } inline bool SmartVertexHandle::is_manifold() const { assert(mesh() != nullptr); return mesh()->is_manifold(*this); } inline SmartHalfedgeHandle SmartHalfedgeHandle::next() const { assert(mesh() != nullptr); return make_smart(mesh()->next_halfedge_handle(*this), mesh()); } inline SmartHalfedgeHandle SmartHalfedgeHandle::prev() const { assert(mesh() != nullptr); return make_smart(mesh()->prev_halfedge_handle(*this), mesh()); } inline SmartHalfedgeHandle SmartHalfedgeHandle::opp() const { assert(mesh() != nullptr); return make_smart(mesh()->opposite_halfedge_handle(*this), mesh()); } inline SmartVertexHandle SmartHalfedgeHandle::to() const { assert(mesh() != nullptr); return make_smart(mesh()->to_vertex_handle(*this), mesh()); } inline SmartVertexHandle SmartHalfedgeHandle::from() const { assert(mesh() != nullptr); return make_smart(mesh()->from_vertex_handle(*this), mesh()); } inline SmartEdgeHandle SmartHalfedgeHandle::edge() const { assert(mesh() != nullptr); return make_smart(mesh()->edge_handle(*this), mesh()); } inline SmartFaceHandle SmartHalfedgeHandle::face() const { assert(mesh() != nullptr); return make_smart(mesh()->face_handle(*this), mesh()); } inline bool SmartHalfedgeHandle::is_boundary() const { assert(mesh() != nullptr); return mesh()->is_boundary(*this); } inline SmartHalfedgeHandle SmartEdgeHandle::halfedge(unsigned int _i) const { assert(mesh() != nullptr); return make_smart(mesh()->halfedge_handle(*this, _i), mesh()); } inline SmartHalfedgeHandle SmartEdgeHandle::h(unsigned int _i) const { return halfedge(_i); } inline SmartHalfedgeHandle SmartEdgeHandle::h0() const { return h(0); } inline SmartHalfedgeHandle SmartEdgeHandle::h1() const { return h(1); } inline SmartVertexHandle SmartEdgeHandle::vertex(unsigned int _i) const { return halfedge(_i).from(); } inline SmartVertexHandle SmartEdgeHandle::v(unsigned int _i) const { return vertex(_i); } inline SmartVertexHandle SmartEdgeHandle::v0() const { return v(0); } inline SmartVertexHandle SmartEdgeHandle::v1() const { return v(1); } inline bool SmartEdgeHandle::is_boundary() const { assert(mesh() != nullptr); return mesh()->is_boundary(*this); } inline SmartHalfedgeHandle SmartFaceHandle::halfedge() const { assert(mesh() != nullptr); return make_smart(mesh()->halfedge_handle(*this), mesh()); } inline uint SmartFaceHandle::valence() const { assert(mesh() != nullptr); return mesh()->valence(*this); } inline bool SmartFaceHandle::is_boundary() const { assert(mesh() != nullptr); return mesh()->is_boundary(*this); } //============================================================================= } // namespace OpenMesh //============================================================================= //=============================================================================
39.818436
139
0.642231
[ "mesh" ]
0952c57ae9873ae8b8ef9c4e0ff51bf7ff470fbe
3,078
cpp
C++
tc 160+/GeneralChess.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/GeneralChess.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/GeneralChess.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <map> #include <utility> using namespace std; const int di[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; const int dj[] = { -1, 1, 2, 2, 1, -1, -2, -2 }; class GeneralChess { public: vector <string> attackPositions(vector <string> pieces) { map< pair<int, int>, int > M; for (int i=0; i<(int)pieces.size(); ++i) { int r, c; sscanf(pieces[i].c_str(), "%d,%d", &r, &c); for (int d=0; d<8; ++d) ++M[make_pair(r+di[d], c+dj[d])]; } vector<string> sol; for (map< pair<int, int>, int>::const_iterator it=M.begin(); it!=M.end(); ++it) if (it->second == (int)pieces.size()) { ostringstream os; os << it->first.first << ',' << it->first.second; sol.push_back(os.str()); } return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { string Arr0[] = {"0,0"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "-2,-1", "-2,1", "-1,-2", "-1,2", "1,-2", "1,2", "2,-1", "2,1" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, attackPositions(Arg0)); } void test_case_1() { string Arr0[] = {"2,1", "-1,-2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "0,0", "1,-1" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, attackPositions(Arg0)); } void test_case_2() { string Arr0[] = {"0,0", "2,1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, attackPositions(Arg0)); } void test_case_3() { string Arr0[] = {"-1000,1000", "-999,999", "-999,997"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "-1001,998" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, attackPositions(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { GeneralChess ___test; ___test.run_test(-1); } // END CUT HERE
44.608696
339
0.57245
[ "vector" ]
0958dee6a96ed1bb304e20fd2ad8cf70a1ce99b3
9,329
cpp
C++
src/proteus/core/manager.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
4
2021-11-03T21:32:55.000Z
2022-02-17T17:13:16.000Z
src/proteus/core/manager.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
null
null
null
src/proteus/core/manager.cpp
Xilinx/inference-server
7477b7dc420ce4cd0d7e1d9914b71898e97d6814
[ "Apache-2.0" ]
2
2022-03-05T20:01:33.000Z
2022-03-25T06:00:35.000Z
// Copyright 2021 Xilinx Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file * @brief Implements how the shared mutable state of Proteus is managed as * Proteus runs */ #include "proteus/core/manager.hpp" #include <stdexcept> // for invalid_argument #include <thread> // for yield, thread #include <utility> // for pair, make_pair, move #include "proteus/build_options.hpp" // for PROTEUS_ENABLE_LOGGING, kMax... #include "proteus/core/worker_info.hpp" // for WorkerInfo #include "proteus/helpers/thread.hpp" // for setThreadName #include "proteus/workers/worker.hpp" // for Worker namespace proteus { Manager::Manager() { #ifdef PROTEUS_ENABLE_LOGGING this->logger_ = getLogger(); #endif update_queue_ = std::make_unique<UpdateCommandQueue>(); init(); } void Manager::init() { // default constructed threads are not joinable if (!update_thread_.joinable()) { update_thread_ = std::thread(&Manager::update_manager, this, update_queue_.get()); } } std::string Manager::loadWorker(std::string const& key, RequestParameters parameters) { std::shared_ptr<proteus::UpdateCommand> request; std::string retval; retval.reserve(kMaxModelNameSize); retval = ""; request = std::make_shared<UpdateCommand>(UpdateCommandType::Add, key, &parameters, &retval); update_queue_->enqueue(request); while (static_cast<std::string*>(request->retval)->empty() && request->eptr == nullptr) { std::this_thread::yield(); } if (request->eptr != nullptr) { std::rethrow_exception(request->eptr); } auto endpoint = *(static_cast<std::string*>(request->retval)); return endpoint; } void Manager::unloadWorker(const std::string& key) { if (this->endpoints_.exists(key)) { auto request = std::make_shared<UpdateCommand>(UpdateCommandType::Delete, key); update_queue_->enqueue(request); } } WorkerInfo* Manager::getWorker(const std::string& key) { auto* worker_info = this->endpoints_.get(key); if (worker_info == nullptr) { throw std::invalid_argument("worker " + key + " not found"); } return worker_info; } bool Manager::workerReady(const std::string& key) { auto metadata = this->getWorkerMetadata(key); return metadata.isReady(); } ModelMetadata Manager::getWorkerMetadata(const std::string& key) { auto* worker = this->getWorker(key); auto* foo = worker->workers_.begin()->second; return foo->getMetadata(); } void Manager::workerAllocate(std::string const& key, int num) { auto* worker = this->getWorker(key); auto request = std::make_shared<UpdateCommand>(UpdateCommandType::Allocate, key, &num); update_queue_->enqueue(request); while (!worker->inputSizeValid(num) && request->eptr == nullptr) { std::this_thread::yield(); } if (request->eptr != nullptr) { std::rethrow_exception(request->eptr); } } std::vector<std::string> Manager::getWorkerEndpoints() { return this->endpoints_.list(); } // TODO(varunsh): if multiple commands sent post-shutdown, they will linger // in the queue and may cause problems void Manager::shutdown() { auto request = std::make_shared<UpdateCommand>(UpdateCommandType::Shutdown); this->update_queue_->enqueue(request); if (this->update_thread_.joinable()) { this->update_thread_.join(); } } void Manager::update_manager(UpdateCommandQueue* input_queue) { SPDLOG_LOGGER_DEBUG(this->logger_, "Starting the Manager update thread"); setThreadName("manager"); std::shared_ptr<UpdateCommand> request; bool run = true; while (run) { input_queue->wait_dequeue(request); SPDLOG_LOGGER_DEBUG(this->logger_, "Got request in Manager update thread"); switch (request->cmd) { case UpdateCommandType::Shutdown: this->endpoints_.shutdown(); run = false; break; case UpdateCommandType::Delete: this->endpoints_.unload(request->key); break; case UpdateCommandType::Allocate: try { auto* worker_info = this->endpoints_.get(request->key); auto num = *static_cast<int*>(request->object); if (!worker_info->inputSizeValid(num)) { SPDLOG_LOGGER_DEBUG( this->logger_, "Allocating more buffers for worker " + request->key); worker_info->allocate(num); } } catch (...) { request->eptr = std::current_exception(); } break; case UpdateCommandType::Add: auto* parameters = static_cast<RequestParameters*>(request->object); try { auto endpoint = this->endpoints_.add(request->key, *parameters); static_cast<std::string*>(request->retval) ->assign(std::string{endpoint}); } catch (...) { request->eptr = std::current_exception(); } break; } } SPDLOG_LOGGER_DEBUG(this->logger_, "Ending update_thread"); } std::string Manager::Endpoints::load(const std::string& worker, RequestParameters* parameters) { if (worker_endpoints_.find(worker) == worker_endpoints_.end()) { // this is a brand-new worker we haven't seen before std::map<RequestParameters, std::string> map; map.insert(std::make_pair(*parameters, worker)); worker_endpoints_.insert(std::make_pair(worker, map)); worker_parameters_.insert(std::make_pair(worker, *parameters)); return worker; } auto& map = worker_endpoints_.at(worker); // we've seen this worker before but not with these parameters if (map.find(*parameters) == map.end()) { int index = 0; if (worker_indices_.find(worker) != worker_indices_.end()) { // technically, this can overflow and cause problems but that's unlikely index = worker_indices_.at(worker) + 1; } std::string url = worker + "-" + std::to_string(index); map.insert(std::make_pair(*parameters, url)); worker_indices_.insert_or_assign(worker, index); worker_parameters_.insert(std::make_pair(url, *parameters)); return url; } return map.at(*parameters); } void Manager::Endpoints::unload(const std::string& endpoint) { auto hyphen_pos = endpoint.find('-'); auto worker = hyphen_pos != std::string::npos ? endpoint.substr(0, hyphen_pos) : endpoint; auto* worker_info = this->get(endpoint); if (worker_info != nullptr) { worker_info->unload(); } // if it's a brand-new worker that failed or the last worker being unloaded, // clean up our parameters and endpoint metadata if (worker_info == nullptr || worker_info->getGroupSize() == 0) { this->workers_.erase(endpoint); if (worker_endpoints_.find(worker) != worker_endpoints_.end()) { auto& map = worker_endpoints_.at(worker); auto& parameters = worker_parameters_.at(endpoint); map.erase(parameters); if (map.empty()) { worker_endpoints_.erase(worker); worker_indices_.erase(worker); } worker_parameters_.erase(endpoint); } } } bool Manager::Endpoints::exists(const std::string& endpoint) { return workers_.find(endpoint) != workers_.end(); } std::vector<std::string> Manager::Endpoints::list() { std::vector<std::string> workers; workers.reserve(this->workers_.size()); for (const auto& [worker, _] : workers_) { workers.push_back(worker); } return workers; } WorkerInfo* Manager::Endpoints::get(const std::string& endpoint) { auto iterator = workers_.find(endpoint); if (iterator != workers_.end()) { return iterator->second.get(); } return nullptr; } std::string Manager::Endpoints::add(const std::string& worker, RequestParameters parameters) { bool share = true; if (parameters.has("share")) { share = parameters.get<bool>("share"); parameters.erase("share"); } auto endpoint = this->load(worker, &parameters); auto* worker_info = this->get(endpoint); // if the worker doesn't exist yet, we need to create it try { if (worker_info == nullptr) { auto new_worker = std::make_unique<WorkerInfo>(endpoint, &parameters); this->workers_.insert(std::make_pair(endpoint, std::move(new_worker))); // if the worker exists but the share parameter is false, we need to add // one } else if (!share) { worker_info->addAndStartWorker(endpoint, &parameters); } } catch (...) { // undo the load if the worker creation fails this->unload(endpoint); throw; } return endpoint; } void Manager::Endpoints::shutdown() { for (auto const& worker_info : this->workers_) { worker_info.second->shutdown(); } this->workers_.clear(); this->worker_endpoints_.clear(); this->worker_indices_.clear(); this->worker_parameters_.clear(); } } // namespace proteus
32.168966
80
0.666309
[ "object", "vector" ]
095fcd6ccaebe74ecb04cf0634c971a4b1fa3048
1,739
cpp
C++
llvm/tools/clang/lib/Basic/SanitizerBlacklist.cpp
zard49/kokkos-clang
c519a032853e6507075de1807c5730b8239ab936
[ "Unlicense" ]
5
2015-07-23T09:47:12.000Z
2019-11-28T01:34:01.000Z
llvm/tools/clang/lib/Basic/SanitizerBlacklist.cpp
losalamos/kokkos-clang
d68d9c63cea3dbaad33454e4ebc9df829bca24fe
[ "Unlicense" ]
1
2016-02-10T15:40:03.000Z
2016-02-10T15:40:03.000Z
3.7.0/cfe-3.7.0.src/lib/Basic/SanitizerBlacklist.cpp
androm3da/clang_sles
2ba6d0711546ad681883c42dfb8661b842806695
[ "MIT" ]
3
2015-10-28T18:21:02.000Z
2019-05-06T18:35:41.000Z
//===--- SanitizerBlacklist.cpp - Blacklist for sanitizers ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // User-provided blacklist used to disable/alter instrumentation done in // sanitizers. // //===----------------------------------------------------------------------===// #include "clang/Basic/SanitizerBlacklist.h" using namespace clang; SanitizerBlacklist::SanitizerBlacklist( const std::vector<std::string> &BlacklistPaths, SourceManager &SM) : SCL(llvm::SpecialCaseList::createOrDie(BlacklistPaths)), SM(SM) {} bool SanitizerBlacklist::isBlacklistedGlobal(StringRef GlobalName, StringRef Category) const { return SCL->inSection("global", GlobalName, Category); } bool SanitizerBlacklist::isBlacklistedType(StringRef MangledTypeName, StringRef Category) const { return SCL->inSection("type", MangledTypeName, Category); } bool SanitizerBlacklist::isBlacklistedFunction(StringRef FunctionName) const { return SCL->inSection("fun", FunctionName); } bool SanitizerBlacklist::isBlacklistedFile(StringRef FileName, StringRef Category) const { return SCL->inSection("src", FileName, Category); } bool SanitizerBlacklist::isBlacklistedLocation(SourceLocation Loc, StringRef Category) const { return !Loc.isInvalid() && isBlacklistedFile(SM.getFilename(SM.getFileLoc(Loc)), Category); }
37
80
0.60322
[ "vector" ]
8230c0397100fbecfcdc529fe5e7f02a864773db
1,246
cpp
C++
src/graphics/resources/texture.cpp
rationalis-petra/mecs
461eacff6b9449eb1a6bdf2f9faf45c6d2265d65
[ "MIT" ]
null
null
null
src/graphics/resources/texture.cpp
rationalis-petra/mecs
461eacff6b9449eb1a6bdf2f9faf45c6d2265d65
[ "MIT" ]
null
null
null
src/graphics/resources/texture.cpp
rationalis-petra/mecs
461eacff6b9449eb1a6bdf2f9faf45c6d2265d65
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <glad/glad.h> #include <GLFW/glfw3.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "engine.hpp" #ifndef NDEBUG #include <stdio.h> #endif using std::string; const string texture_path = "resources/textures/"; Texture::Texture(string path) { string resource_path = texture_path + path; int width, height, nr_channels; unsigned char* data = stbi_load(resource_path.c_str(), &width, &height, &nr_channels, STBI_rgb); #ifndef NDEBUG if (!data) { std::cerr << "error in load_texture: unable to load image from disk: " << path << std::endl; } #endif // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); } Texture::~Texture() {};
25.958333
98
0.745586
[ "object" ]
8235a0587eefa1e40f4dfecb01505bee309924e4
653
cpp
C++
node-SUSI-function-define.cpp
ADVANTECH-Corp/node-susi
77ff35d5f2c530dfda701eb4ad00afee9a25e7ff
[ "Apache-2.0" ]
null
null
null
node-SUSI-function-define.cpp
ADVANTECH-Corp/node-susi
77ff35d5f2c530dfda701eb4ad00afee9a25e7ff
[ "Apache-2.0" ]
null
null
null
node-SUSI-function-define.cpp
ADVANTECH-Corp/node-susi
77ff35d5f2c530dfda701eb4ad00afee9a25e7ff
[ "Apache-2.0" ]
null
null
null
//#include <node.h> #include <nan.h> #include "node-SUSI.h" using v8::FunctionTemplate; using v8::Handle; using v8::Object; using v8::String; // NativeExtension.cc represents the top level of the module. // C++ constructs that are exposed to javascript are exported here NAN_MODULE_INIT(Init) { NAN_EXPORT(target, getHardwareMonitor); NAN_EXPORT(target, getHardwareMonitorString); NAN_EXPORT(target, getVgaBacklight); NAN_EXPORT(target, setVgaBacklight); NAN_EXPORT(target, getGPIO); NAN_EXPORT(target, setGPIO); NAN_EXPORT(target, getWatchDog); NAN_EXPORT(target, setWatchDog); NAN_EXPORT(target, aString); } NODE_MODULE(node_SUSI, Init)
25.115385
66
0.771822
[ "object" ]
8235b118f05c0c0652cb1ce425162c58bfbd49f1
33,984
cc
C++
packager/mpd/base/dash_iop_mpd_notifier_unittest.cc
nevil/shaka-packager
a217cdce294b5162ae305a310b2e53e73c4d0481
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
packager/mpd/base/dash_iop_mpd_notifier_unittest.cc
nevil/shaka-packager
a217cdce294b5162ae305a310b2e53e73c4d0481
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
packager/mpd/base/dash_iop_mpd_notifier_unittest.cc
nevil/shaka-packager
a217cdce294b5162ae305a310b2e53e73c4d0481
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include <gmock/gmock.h> #include <gtest/gtest.h> #include "packager/base/files/file_path.h" #include "packager/base/files/file_util.h" #include "packager/mpd/base/dash_iop_mpd_notifier.h" #include "packager/mpd/base/mock_mpd_builder.h" #include "packager/mpd/base/mpd_builder.h" #include "packager/mpd/test/mpd_builder_test_helper.h" namespace edash_packager { using ::testing::_; using ::testing::Eq; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; namespace { const char kValidMediaInfo[] = "video_info {\n" " codec: 'avc1'\n" " width: 1280\n" " height: 720\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "container_type: 1\n"; const uint32_t kDefaultAdaptationSetId = 0u; const uint32_t kDefaultRepresentationId = 1u; const int kDefaultGroupId = -1; bool ElementEqual(const edash_packager::Element& lhs, const edash_packager::Element& rhs) { const bool all_equal_except_sublement_check = lhs.name == rhs.name && lhs.attributes.size() == rhs.attributes.size() && std::equal(lhs.attributes.begin(), lhs.attributes.end(), rhs.attributes.begin()) && lhs.content == rhs.content && lhs.subelements.size() == rhs.subelements.size(); if (!all_equal_except_sublement_check) { return false; } for (size_t i = 0; i < lhs.subelements.size(); ++i) { if (!ElementEqual(lhs.subelements[i], rhs.subelements[i])) return false; } return true; } bool ContentProtectionElementEqual( const edash_packager::ContentProtectionElement& lhs, const edash_packager::ContentProtectionElement& rhs) { const bool all_equal_except_sublement_check = lhs.value == rhs.value && lhs.scheme_id_uri == rhs.scheme_id_uri && lhs.additional_attributes.size() == rhs.additional_attributes.size() && std::equal(lhs.additional_attributes.begin(), lhs.additional_attributes.end(), rhs.additional_attributes.begin()) && lhs.subelements.size() == rhs.subelements.size(); if (!all_equal_except_sublement_check) return false; for (size_t i = 0; i < lhs.subelements.size(); ++i) { if (!ElementEqual(lhs.subelements[i], rhs.subelements[i])) return false; } return true; } MATCHER_P(ContentProtectionElementEq, expected, "") { return ContentProtectionElementEqual(arg, expected); } } // namespace // TODO(rkuroiwa): This is almost exactly the same as SimpleMpdNotifierTest but // replaced all SimpleMpd with DashIopMpd, // use typed tests // (https://code.google.com/p/googletest/wiki/AdvancedGuide#Typed_Tests); // also because SimpleMpdNotifier and DashIopMpdNotifier have common behavior // for most of the public functions. class DashIopMpdNotifierTest : public ::testing::TestWithParam<MpdBuilder::MpdType> { protected: DashIopMpdNotifierTest() : default_mock_adaptation_set_( new MockAdaptationSet(kDefaultAdaptationSetId)), default_mock_representation_( new MockRepresentation(kDefaultRepresentationId)) {} void SetUp() override { ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path_)); output_path_ = temp_file_path_.value(); ON_CALL(*default_mock_adaptation_set_, Group()) .WillByDefault(Return(kDefaultGroupId)); } void TearDown() override { base::DeleteFile(temp_file_path_, false /* non recursive, just 1 file */); } MpdBuilder::MpdType GetMpdBuilderType(const DashIopMpdNotifier& notifier) { return notifier.MpdBuilderForTesting()->type(); } void SetMpdBuilder(DashIopMpdNotifier* notifier, scoped_ptr<MpdBuilder> mpd_builder) { notifier->SetMpdBuilderForTesting(mpd_builder.Pass()); } MpdBuilder::MpdType mpd_type() { return GetParam(); } DashProfile dash_profile() { return mpd_type() == MpdBuilder::kStatic ? kOnDemandProfile : kLiveProfile; } // Use output_path_ for specifying the MPD output path so that // WriteMpdToFile() doesn't crash. std::string output_path_; const MpdOptions empty_mpd_option_; const std::vector<std::string> empty_base_urls_; // Default mocks that can be used for the tests. // IOW, if a test only requires one instance of // Mock{AdaptationSet,Representation}, these can be used. scoped_ptr<MockAdaptationSet> default_mock_adaptation_set_; scoped_ptr<MockRepresentation> default_mock_representation_; private: base::FilePath temp_file_path_; }; // Verify that it creates the correct MpdBuilder type using DashProfile passed // to the constructor. TEST_F(DashIopMpdNotifierTest, CreateCorrectMpdBuilderType) { DashIopMpdNotifier on_demand_notifier(kOnDemandProfile, empty_mpd_option_, empty_base_urls_, output_path_); EXPECT_TRUE(on_demand_notifier.Init()); EXPECT_EQ(MpdBuilder::kStatic, GetMpdBuilderType(on_demand_notifier)); DashIopMpdNotifier live_notifier(kLiveProfile, empty_mpd_option_, empty_base_urls_, output_path_); EXPECT_TRUE(live_notifier.Init()); EXPECT_EQ(MpdBuilder::kDynamic, GetMpdBuilderType(live_notifier)); } // Verify that basic VOD NotifyNewContainer() operation works. // No encrypted contents. TEST_P(DashIopMpdNotifierTest, NotifyNewContainer) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(default_mock_adaptation_set_.get())); EXPECT_CALL(*default_mock_adaptation_set_, AddRole(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(default_mock_representation_.get())); // This is for the Flush() below but adding expectation here because the next // lines Pass() the pointer. EXPECT_CALL(*mock_mpd_builder, ToString(_)).WillOnce(Return(true)); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer(ConvertToMediaInfo(kValidMediaInfo), &unused_container_id)); EXPECT_TRUE(notifier.Flush()); } // Verify that if the MediaInfo contains text information, then // MpdBuilder::ForceSetSegmentAlignment() is called. TEST_P(DashIopMpdNotifierTest, NotifyNewTextContainer) { const char kTextMediaInfo[] = "text_info {\n" " format: 'ttml'\n" " language: 'en'\n" "}\n" "container_type: CONTAINER_TEXT\n"; DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(StrEq("en"))) .WillOnce(Return(default_mock_adaptation_set_.get())); EXPECT_CALL(*default_mock_adaptation_set_, AddRole(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, ForceSetSegmentAlignment(true)); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(default_mock_representation_.get())); // This is for the Flush() below but adding expectation here because the next // lines Pass() the pointer. EXPECT_CALL(*mock_mpd_builder, ToString(_)).WillOnce(Return(true)); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer(ConvertToMediaInfo(kTextMediaInfo), &unused_container_id)); EXPECT_TRUE(notifier.Flush()); } // Verify VOD NotifyNewContainer() operation works with different // MediaInfo::ProtectedContent. // Two AdaptationSets should be created. // Different DRM so they won't be grouped. TEST_P(DashIopMpdNotifierTest, NotifyNewContainersWithDifferentProtectedContent) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); // Note they both have different (bogus) pssh, like real use case. // default Key ID = _default_key_id_ const char kSdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 640\n" " height: 360\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh1'\n" " }\n" " default_key_id: '_default_key_id_'\n" "}\n" "container_type: 1\n"; // default Key ID = .default.key.id. const char kHdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 1280\n" " height: 720\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'anotheruuid'\n" " name_version: 'SomeOtherProtection version 3'\n" " pssh: 'pssh2'\n" " }\n" " default_key_id: '.default.key.id.'\n" "}\n" "container_type: 1\n"; // Check that the right ContentProtectionElements for SD is created. // HD is the same case, so not checking. ContentProtectionElement mp4_protection; mp4_protection.scheme_id_uri = "urn:mpeg:dash:mp4protection:2011"; mp4_protection.value = "cenc"; // This should match the "_default_key_id_" above, but taking it as hex data // and converted to UUID format. mp4_protection.additional_attributes["cenc:default_KID"] = "5f646566-6175-6c74-5f6b-65795f69645f"; ContentProtectionElement sd_my_drm; sd_my_drm.scheme_id_uri = "urn:uuid:myuuid"; sd_my_drm.value = "MyContentProtection version 1"; Element cenc_pssh; cenc_pssh.name = "cenc:pssh"; cenc_pssh.content = "cHNzaDE="; // Base64 encoding of 'pssh1'. sd_my_drm.subelements.push_back(cenc_pssh); // Not using default mocks in this test so that we can keep track of // mocks by named mocks. const uint32_t kSdAdaptationSetId = 2u; const uint32_t kHdAdaptationSetId = 3u; scoped_ptr<MockAdaptationSet> sd_adaptation_set( new MockAdaptationSet(kSdAdaptationSetId)); scoped_ptr<MockAdaptationSet> hd_adaptation_set( new MockAdaptationSet(kHdAdaptationSetId)); ON_CALL(*sd_adaptation_set, Group()).WillByDefault(Return(kDefaultGroupId)); ON_CALL(*hd_adaptation_set, Group()).WillByDefault(Return(kDefaultGroupId)); EXPECT_CALL(*sd_adaptation_set, SetGroup(_)).Times(0); EXPECT_CALL(*hd_adaptation_set, SetGroup(_)).Times(0); const uint32_t kSdRepresentation = 4u; const uint32_t kHdRepresentation = 5u; scoped_ptr<MockRepresentation> sd_representation( new MockRepresentation(kSdRepresentation)); scoped_ptr<MockRepresentation> hd_representation( new MockRepresentation(kHdRepresentation)); InSequence in_sequence; EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(sd_adaptation_set.get())); EXPECT_CALL( *sd_adaptation_set, AddContentProtectionElement(ContentProtectionElementEq(mp4_protection))); EXPECT_CALL(*sd_adaptation_set, AddContentProtectionElement( ContentProtectionElementEq(sd_my_drm))); EXPECT_CALL(*sd_adaptation_set, AddRepresentation(_)) .WillOnce(Return(sd_representation.get())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(hd_adaptation_set.get())); // Called twice for the same reason as above. EXPECT_CALL(*hd_adaptation_set, AddContentProtectionElement(_)).Times(2); // Add main Role here for both. EXPECT_CALL(*sd_adaptation_set, AddRole(AdaptationSet::kRoleMain)); EXPECT_CALL(*hd_adaptation_set, AddRole(AdaptationSet::kRoleMain)); EXPECT_CALL(*hd_adaptation_set, AddRepresentation(_)) .WillOnce(Return(hd_representation.get())); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kSdProtectedContent), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kHdProtectedContent), &unused_container_id)); } // Verify VOD NotifyNewContainer() operation works with same // MediaInfo::ProtectedContent. Only one AdaptationSet should be // created. TEST_P(DashIopMpdNotifierTest, NotifyNewContainersWithSameProtectedContent) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); // These have the same default key ID and PSSH. const char kSdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 640\n" " height: 360\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'psshbox'\n" " }\n" " default_key_id: '.DEFAULT.KEY.ID.'\n" "}\n" "container_type: 1\n"; const char kHdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 1280\n" " height: 720\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'psshbox'\n" " }\n" " default_key_id: '.DEFAULT.KEY.ID.'\n" "}\n" "container_type: 1\n"; ContentProtectionElement mp4_protection; mp4_protection.scheme_id_uri = "urn:mpeg:dash:mp4protection:2011"; mp4_protection.value = "cenc"; // This should match the ".DEFAULT.KEY.ID." above, but taking it as hex data // and converted to UUID format. mp4_protection.additional_attributes["cenc:default_KID"] = "2e444546-4155-4c54-2e4b-45592e49442e"; ContentProtectionElement my_drm; my_drm.scheme_id_uri = "urn:uuid:myuuid"; my_drm.value = "MyContentProtection version 1"; Element cenc_pssh; cenc_pssh.name = "cenc:pssh"; cenc_pssh.content = "cHNzaGJveA=="; // Base64 encoding of 'psshbox'. my_drm.subelements.push_back(cenc_pssh); const uint32_t kSdRepresentation = 6u; const uint32_t kHdRepresentation = 7u; scoped_ptr<MockRepresentation> sd_representation( new MockRepresentation(kSdRepresentation)); scoped_ptr<MockRepresentation> hd_representation( new MockRepresentation(kHdRepresentation)); // No reason to set @group if there is only one AdaptationSet. EXPECT_CALL(*default_mock_adaptation_set_, SetGroup(_)).Times(0); InSequence in_sequence; EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(default_mock_adaptation_set_.get())); EXPECT_CALL( *default_mock_adaptation_set_, AddContentProtectionElement(ContentProtectionElementEq(mp4_protection))); EXPECT_CALL(*default_mock_adaptation_set_, AddContentProtectionElement(ContentProtectionElementEq(my_drm))); EXPECT_CALL(*default_mock_adaptation_set_, AddRole(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(sd_representation.get())); // For second representation, no new AddAdaptationSet(). // And make sure that AddContentProtection() is not called. EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddContentProtectionElement(_)) .Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddRole(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(hd_representation.get())); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kSdProtectedContent), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kHdProtectedContent), &unused_container_id)); } // AddContentProtection() should not work and should always return false. TEST_P(DashIopMpdNotifierTest, AddContentProtection) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(default_mock_adaptation_set_.get())); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(default_mock_representation_.get())); uint32_t container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer(ConvertToMediaInfo(kValidMediaInfo), &container_id)); ContentProtectionElement empty_content_protection_element; EXPECT_FALSE(notifier.AddContentProtectionElement( container_id, empty_content_protection_element)); } // Default Key IDs are different but if the content protection UUIDs match, then // they can be in the same group. // This is a long test. // Basically this // 1. Add an SD protected content. This should make an AdaptationSet. // 2. Add an HD protected content. This should make another AdaptationSet that // is different from the SD version. Both SD and HD should have the same // group ID assigned. // 3. Add a 4k protected content. This should also make a new AdaptationSet. // The group ID should also match the SD and HD (but this takes a slightly // different path). TEST_P(DashIopMpdNotifierTest, SetGroup) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); // These have the same default key ID and PSSH. const char kSdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 640\n" " height: 360\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh_sd'\n" " }\n" " default_key_id: '_default_key_id_'\n" "}\n" "container_type: 1\n"; const char kHdProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 1280\n" " height: 720\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh_hd'\n" " }\n" " default_key_id: '.DEFAULT.KEY.ID.'\n" "}\n" "container_type: 1\n"; const uint32_t kSdAdaptationSetId = 6u; const uint32_t kHdAdaptationSetId = 7u; scoped_ptr<MockAdaptationSet> sd_adaptation_set( new MockAdaptationSet(kSdAdaptationSetId)); scoped_ptr<MockAdaptationSet> hd_adaptation_set( new MockAdaptationSet(kHdAdaptationSetId)); ON_CALL(*sd_adaptation_set, Group()).WillByDefault(Return(kDefaultGroupId)); ON_CALL(*hd_adaptation_set, Group()).WillByDefault(Return(kDefaultGroupId)); const uint32_t kSdRepresentation = 4u; const uint32_t kHdRepresentation = 5u; scoped_ptr<MockRepresentation> sd_representation( new MockRepresentation(kSdRepresentation)); scoped_ptr<MockRepresentation> hd_representation( new MockRepresentation(kHdRepresentation)); InSequence in_sequence; EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(sd_adaptation_set.get())); EXPECT_CALL(*sd_adaptation_set, AddContentProtectionElement(_)).Times(2); EXPECT_CALL(*sd_adaptation_set, AddRepresentation(_)) .WillOnce(Return(sd_representation.get())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(hd_adaptation_set.get())); EXPECT_CALL(*hd_adaptation_set, AddContentProtectionElement(_)).Times(2); EXPECT_CALL(*hd_adaptation_set, AddRepresentation(_)) .WillOnce(Return(hd_representation.get())); // Both AdaptationSets' groups should be set to the same value. const int kExpectedGroupId = 1; EXPECT_CALL(*sd_adaptation_set, SetGroup(kExpectedGroupId)); EXPECT_CALL(*hd_adaptation_set, SetGroup(kExpectedGroupId)); // This is not very nice but we need it for settings expectations later. MockMpdBuilder* mock_mpd_builder_raw = mock_mpd_builder.get(); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kSdProtectedContent), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kHdProtectedContent), &unused_container_id)); // Now that the group IDs are set Group() returns kExpectedGroupId. ON_CALL(*sd_adaptation_set, Group()).WillByDefault(Return(kExpectedGroupId)); ON_CALL(*hd_adaptation_set, Group()).WillByDefault(Return(kExpectedGroupId)); // Add another content that has the same protected content and make sure that // it gets added to the existing group. const char k4kProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 4096\n" " height: 2160\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh_4k'\n" " }\n" " default_key_id: 'some16bytestring'\n" "}\n" "container_type: 1\n"; const uint32_t k4kAdaptationSetId = 4000u; scoped_ptr<MockAdaptationSet> fourk_adaptation_set( new MockAdaptationSet(k4kAdaptationSetId)); ON_CALL(*fourk_adaptation_set, Group()) .WillByDefault(Return(kDefaultGroupId)); const uint32_t k4kRepresentationId = 4001u; scoped_ptr<MockRepresentation> fourk_representation( new MockRepresentation(k4kRepresentationId)); EXPECT_CALL(*mock_mpd_builder_raw, AddAdaptationSet(_)) .WillOnce(Return(fourk_adaptation_set.get())); EXPECT_CALL(*fourk_adaptation_set, AddContentProtectionElement(_)).Times(2); EXPECT_CALL(*fourk_adaptation_set, AddRepresentation(_)) .WillOnce(Return(fourk_representation.get())); // Same group ID should be set. EXPECT_CALL(*fourk_adaptation_set, SetGroup(kExpectedGroupId)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(k4kProtectedContent), &unused_container_id)); } // Even if the UUIDs match, video and audio AdaptationSets should not be grouped // together. TEST_P(DashIopMpdNotifierTest, DoNotSetGroupIfContentTypesDifferent) { DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); // These have the same default key ID and PSSH. const char kVideoContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 640\n" " height: 360\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh_video'\n" " }\n" " default_key_id: '_default_key_id_'\n" "}\n" "container_type: 1\n"; const char kAudioContent[] = "audio_info {\n" " codec: 'mp4a.40.2'\n" " sampling_frequency: 44100\n" " time_scale: 1200\n" " num_channels: 2\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh_audio'\n" " }\n" " default_key_id: '_default_key_id_'\n" "}\n" "reference_time_scale: 50\n" "container_type: 1\n" "media_duration_seconds: 10.5\n"; const uint32_t kVideoAdaptationSetId = 6u; const uint32_t kAudioAdaptationSetId = 7u; scoped_ptr<MockAdaptationSet> video_adaptation_set( new MockAdaptationSet(kVideoAdaptationSetId)); scoped_ptr<MockAdaptationSet> audio_adaptation_set( new MockAdaptationSet(kAudioAdaptationSetId)); ON_CALL(*video_adaptation_set, Group()) .WillByDefault(Return(kDefaultGroupId)); ON_CALL(*audio_adaptation_set, Group()) .WillByDefault(Return(kDefaultGroupId)); // Both AdaptationSets' groups should NOT be set. EXPECT_CALL(*video_adaptation_set, SetGroup(_)).Times(0); EXPECT_CALL(*audio_adaptation_set, SetGroup(_)).Times(0); const uint32_t kVideoRepresentation = 8u; const uint32_t kAudioRepresentation = 9u; scoped_ptr<MockRepresentation> video_representation( new MockRepresentation(kVideoRepresentation)); scoped_ptr<MockRepresentation> audio_representation( new MockRepresentation(kAudioRepresentation)); InSequence in_sequence; EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(video_adaptation_set.get())); EXPECT_CALL(*video_adaptation_set, AddContentProtectionElement(_)).Times(2); EXPECT_CALL(*video_adaptation_set, AddRole(_)).Times(0); EXPECT_CALL(*video_adaptation_set, AddRepresentation(_)) .WillOnce(Return(video_representation.get())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(audio_adaptation_set.get())); EXPECT_CALL(*audio_adaptation_set, AddContentProtectionElement(_)).Times(2); EXPECT_CALL(*audio_adaptation_set, AddRole(_)).Times(0); EXPECT_CALL(*audio_adaptation_set, AddRepresentation(_)) .WillOnce(Return(audio_representation.get())); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kVideoContent), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kAudioContent), &unused_container_id)); } TEST_P(DashIopMpdNotifierTest, UpdateEncryption) { const char kProtectedContent[] = "video_info {\n" " codec: 'avc1'\n" " width: 640\n" " height: 360\n" " time_scale: 10\n" " frame_duration: 10\n" " pixel_width: 1\n" " pixel_height: 1\n" "}\n" "protected_content {\n" " content_protection_entry {\n" " uuid: 'myuuid'\n" " name_version: 'MyContentProtection version 1'\n" " pssh: 'pssh1'\n" " }\n" " default_key_id: '_default_key_id_'\n" "}\n" "container_type: 1\n"; DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(default_mock_adaptation_set_.get())); EXPECT_CALL(*default_mock_adaptation_set_, AddRole(_)).Times(0); EXPECT_CALL(*default_mock_adaptation_set_, AddRepresentation(_)) .WillOnce(Return(default_mock_representation_.get())); uint32_t container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer(ConvertToMediaInfo(kProtectedContent), &container_id)); ::testing::Mock::VerifyAndClearExpectations( default_mock_adaptation_set_.get()); const uint8_t kBogusNewPssh[] = {// "psshsomethingelse" as uint8 array. 0x70, 0x73, 0x73, 0x68, 0x73, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x65, 0x6c, 0x73, 0x65}; const std::vector<uint8_t> kBogusNewPsshVector( kBogusNewPssh, kBogusNewPssh + arraysize(kBogusNewPssh)); const char kBogusNewPsshInBase64[] = "cHNzaHNvbWV0aGluZ2Vsc2U="; EXPECT_CALL(*default_mock_adaptation_set_, UpdateContentProtectionPssh(StrEq("myuuid"), StrEq(kBogusNewPsshInBase64))); EXPECT_TRUE(notifier.NotifyEncryptionUpdate( container_id, "myuuid", std::vector<uint8_t>(), kBogusNewPsshVector)); } // This test is mainly for tsan. Using both the notifier and the MpdBuilder. // Although locks in MpdBuilder have been removed, // https://github.com/google/edash-packager/issues/45 // This issue identified a bug where using SimpleMpdNotifier with multiple // threads causes a deadlock. This tests with DashIopMpdNotifier. TEST_F(DashIopMpdNotifierTest, NotifyNewContainerAndSampleDurationNoMock) { DashIopMpdNotifier notifier(kOnDemandProfile, empty_mpd_option_, empty_base_urls_, output_path_); uint32_t container_id; EXPECT_TRUE(notifier.NotifyNewContainer(ConvertToMediaInfo(kValidMediaInfo), &container_id)); const uint32_t kAnySampleDuration = 1000; EXPECT_TRUE(notifier.NotifySampleDuration(container_id, kAnySampleDuration)); EXPECT_TRUE(notifier.Flush()); } // Don't put different audio languages or codecs in the same AdaptationSet. TEST_P(DashIopMpdNotifierTest, SplitAdaptationSetsByLanguageAndCodec) { // MP4, English const char kAudioContent1[] = "audio_info {\n" " codec: 'mp4a.40.2'\n" " sampling_frequency: 44100\n" " time_scale: 1200\n" " num_channels: 2\n" " language: 'eng'\n" "}\n" "reference_time_scale: 50\n" "container_type: CONTAINER_MP4\n" "media_duration_seconds: 10.5\n"; // MP4, German const char kAudioContent2[] = "audio_info {\n" " codec: 'mp4a.40.2'\n" " sampling_frequency: 44100\n" " time_scale: 1200\n" " num_channels: 2\n" " language: 'ger'\n" "}\n" "reference_time_scale: 50\n" "container_type: CONTAINER_MP4\n" "media_duration_seconds: 10.5\n"; // WebM, German const char kAudioContent3[] = "audio_info {\n" " codec: 'vorbis'\n" " sampling_frequency: 44100\n" " time_scale: 1200\n" " num_channels: 2\n" " language: 'ger'\n" "}\n" "reference_time_scale: 50\n" "container_type: CONTAINER_WEBM\n" "media_duration_seconds: 10.5\n"; // WebM, German again const char kAudioContent4[] = "audio_info {\n" " codec: 'vorbis'\n" " sampling_frequency: 44100\n" " time_scale: 1200\n" " num_channels: 2\n" " language: 'ger'\n" "}\n" "reference_time_scale: 50\n" "container_type: CONTAINER_WEBM\n" "media_duration_seconds: 10.5\n"; DashIopMpdNotifier notifier(dash_profile(), empty_mpd_option_, empty_base_urls_, output_path_); scoped_ptr<MockMpdBuilder> mock_mpd_builder(new MockMpdBuilder(mpd_type())); scoped_ptr<MockAdaptationSet> adaptation_set1(new MockAdaptationSet(1)); scoped_ptr<MockAdaptationSet> adaptation_set2(new MockAdaptationSet(2)); scoped_ptr<MockAdaptationSet> adaptation_set3(new MockAdaptationSet(3)); scoped_ptr<MockRepresentation> representation1(new MockRepresentation(1)); scoped_ptr<MockRepresentation> representation2(new MockRepresentation(2)); scoped_ptr<MockRepresentation> representation3(new MockRepresentation(3)); scoped_ptr<MockRepresentation> representation4(new MockRepresentation(4)); // We expect three AdaptationSets. EXPECT_CALL(*mock_mpd_builder, AddAdaptationSet(_)) .WillOnce(Return(adaptation_set1.get())) .WillOnce(Return(adaptation_set2.get())) .WillOnce(Return(adaptation_set3.get())); // The first AdaptationSet should have Eng MP4, one Representation. EXPECT_CALL(*adaptation_set1, AddRepresentation(_)) .WillOnce(Return(representation1.get())); // The second AdaptationSet should have Ger MP4, one Representation. EXPECT_CALL(*adaptation_set2, AddRepresentation(_)) .WillOnce(Return(representation2.get())); // The third AdaptationSet should have Ger WebM, two Representations. EXPECT_CALL(*adaptation_set3, AddRepresentation(_)) .WillOnce(Return(representation3.get())) .WillOnce(Return(representation4.get())); uint32_t unused_container_id; SetMpdBuilder(&notifier, mock_mpd_builder.Pass()); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kAudioContent1), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kAudioContent2), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kAudioContent3), &unused_container_id)); EXPECT_TRUE(notifier.NotifyNewContainer( ConvertToMediaInfo(kAudioContent4), &unused_container_id)); } INSTANTIATE_TEST_CASE_P(StaticAndDynamic, DashIopMpdNotifierTest, ::testing::Values(MpdBuilder::kStatic, MpdBuilder::kDynamic)); } // namespace edash_packager
38.574347
80
0.702125
[ "vector" ]
823854262c43f23064932a0c86093f9b1f108ca9
8,822
cpp
C++
Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/ethernet/vlan_network_interface.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/ethernet/vlan_network_interface.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/ethernet/vlan_network_interface.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2015-2019 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "psme/core/agent/agent_manager.hpp" #include "psme/rest/constants/constants.hpp" #include "psme/rest/endpoints/ethernet/vlan_network_interface.hpp" #include "psme/rest/model/handlers/handler_manager.hpp" #include "psme/rest/model/handlers/generic_handler_deps.hpp" #include "psme/rest/model/handlers/generic_handler.hpp" #include "psme/rest/server/error/error_factory.hpp" #include "psme/rest/utils/status_helpers.hpp" #include "psme/rest/validators/json_validator.hpp" #include "psme/rest/validators/schemas/vlan_network_interface.hpp" #include "agent-framework/module/requests/network.hpp" #include "agent-framework/module/responses/network.hpp" #include "agent-framework/module/responses/common.hpp" #include "agent-framework/module/network_components.hpp" #include "json-wrapper/json-wrapper.hpp" using namespace psme::rest; using namespace psme::rest::constants; using namespace psme::rest::error; using namespace psme::rest::validators; using namespace agent_framework::model::attribute; namespace { json::Json make_prototype() { json::Json r(json::Json::value_t::object); r[Common::ODATA_CONTEXT] = "/redfish/v1/$metadata#VLanNetworkInterface.VLanNetworkInterface"; r[Common::ODATA_ID] = json::Json::value_t::null; r[Common::ODATA_TYPE] = "#VLanNetworkInterface.v1_0_1.VLanNetworkInterface"; r[Common::ID] = json::Json::value_t::null; r[Common::NAME] = "VLAN Network Interface"; r[Common::DESCRIPTION] = "VLAN Network Interface description"; r[Vlan::VLAN_ENABLE] = json::Json::value_t::null; r[Vlan::VLAN_ID] = json::Json::value_t::null; json::Json rs = json::Json(); rs[Common::ODATA_TYPE] = "#Intel.Oem.VLanNetworkInterface"; rs[::Vlan::TAGGED] = json::Json::value_t::null; rs[Common::STATUS][Common::STATE] = json::Json::value_t::null; rs[Common::STATUS][Common::HEALTH] = json::Json::value_t::null; rs[Common::STATUS][Common::HEALTH_ROLLUP] = json::Json::value_t::null; r[Common::OEM][Common::RACKSCALE] = std::move(rs); return r; } Attributes fill_attributes(json::Json& json) { Attributes attributes{}; if (json.count(constants::Vlan::VLAN_ID)) { attributes.set_value(agent_framework::model::literals::Vlan::VLAN_ID, json[constants::Vlan::VLAN_ID].get<std::int64_t>()); } return attributes; } static const std::map<std::string, std::string> gami_to_rest_attributes = { {agent_framework::model::literals::Vlan::VLAN_ID, constants::Vlan::VLAN_ID} }; } endpoint::VlanNetworkInterface::VlanNetworkInterface(const std::string& path) : EndpointBase(path) {} endpoint::VlanNetworkInterface::~VlanNetworkInterface() {} void endpoint::VlanNetworkInterface::get(const server::Request& request, server::Response& response) { auto r = make_prototype(); r[Common::ODATA_ID] = PathBuilder(request).build(); r[Common::ID] = request.params[PathParam::VLAN_ID]; r[Common::NAME] = Vlan::VLAN + request.params[PathParam::VLAN_ID]; auto vlan = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort, agent_framework::model::EthernetSwitchPortVlan>( request.params).get(); endpoint::status_to_json(vlan, r[Common::OEM][Common::RACKSCALE]); r[Vlan::VLAN_ENABLE] = vlan.get_vlan_enable(); r[Vlan::VLAN_ID] = vlan.get_vlan_id(); r[Common::OEM][Common::RACKSCALE][Vlan::TAGGED] = vlan.get_tagged(); set_response(response, r); } void endpoint::VlanNetworkInterface::del(const server::Request& request, server::Response& response) { static const constexpr char TRANSACTION_NAME[] = "DeleteVlanNetworkInterface"; using AgentManager = psme::core::agent::AgentManager; using HandlerManager = psme::rest::model::handler::HandlerManager; auto vlan_interface = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort, agent_framework::model::EthernetSwitchPortVlan>( request.params).get(); auto gami_agent = AgentManager::get_instance()->get_agent(vlan_interface.get_agent_id()); auto delete_vlan = [&, gami_agent] { // Those resources are needed to properly lock the resource tree and avoid deadlocks auto parent_switch = psme::rest::model::find<agent_framework::model::EthernetSwitch>(request.params).get_one(); auto parent_switch_port = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort>( request.params).get_one(); auto vlan = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort, agent_framework::model::EthernetSwitchPortVlan>( request.params).get_one(); auto port_uuid = vlan->get_parent_uuid(); auto switch_uuid = parent_switch->get_uuid(); auto gami_request = agent_framework::model::requests::DeletePortVlan{vlan->get_uuid()}; gami_agent->execute<agent_framework::model::responses::DeletePortVlan>(gami_request); // remove the resource HandlerManager::get_instance()-> get_handler(agent_framework::model::enums::Component::EthernetSwitchPortVlan)->remove(vlan->get_uuid()); psme::rest::model::handler::HandlerManager::get_instance()->get_handler( agent_framework::model::enums::Component::EthernetSwitchPort)-> load(gami_agent, switch_uuid, agent_framework::model::enums::Component::EthernetSwitch, port_uuid, false); response.set_status(server::status_2XX::NO_CONTENT); }; gami_agent->execute_in_transaction(TRANSACTION_NAME, delete_vlan); } void endpoint::VlanNetworkInterface::patch(const server::Request& request, server::Response& response) { using HandlerManager = psme::rest::model::handler::HandlerManager; static const constexpr char TRANSACTION_NAME[] = "PatchVlanNetworkInterface"; auto json = JsonValidator::validate_request_body<schema::VlanNetworkInterfacePatchSchema>(request); auto attributes = fill_attributes(json); // Holding reference to parent object ensures that locks are acquired in the same order in each thread auto parent_switch = psme::rest::model::find<agent_framework::model::EthernetSwitch>(request.params).get(); auto port = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort>( request.params).get(); auto vlan = psme::rest::model::find<agent_framework::model::EthernetSwitch, agent_framework::model::EthernetSwitchPort, agent_framework::model::EthernetSwitchPortVlan>( request.params).get(); auto gami_agent = psme::core::agent::AgentManager::get_instance()->get_agent(port.get_agent_id()); auto patch_vlan = [&, gami_agent] { bool updated{false}; if (!attributes.empty()) { const auto& set_component_attributes_request = agent_framework::model::requests::SetComponentAttributes{vlan.get_uuid(), attributes}; const auto& set_component_attributes_response = gami_agent->execute<agent_framework::model::responses::SetComponentAttributes> (set_component_attributes_request); const auto& result_statuses = set_component_attributes_response.get_statuses(); if (!result_statuses.empty()) { const auto& error = ErrorFactory::create_error_from_set_component_attributes_results( result_statuses, gami_to_rest_attributes); throw ServerException(error); } updated = true; } if (updated) { HandlerManager::get_instance()-> get_handler(agent_framework::model::enums::Component::EthernetSwitchPortVlan)-> load(gami_agent, port.get_uuid(), agent_framework::model::enums::Component::EthernetSwitchPort, vlan.get_uuid(), true); } }; gami_agent->execute_in_transaction(TRANSACTION_NAME, patch_vlan); get(request, response); }
43.245098
168
0.708343
[ "object", "model" ]
82434ef2b4cd8e51ed187be454d7b054ce118998
16,766
cpp
C++
src/C/Security-57031.40.6/Security/libsecurity_utilities/lib/machserver.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/Security/libsecurity_utilities/lib/machserver.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/Security/libsecurity_utilities/lib/machserver.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* * Copyright (c) 2000-2007,2011-2013 Apple Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ // // machserver - C++ shell for writing Mach 3 servers // #include "machserver.h" #include <servers/bootstrap.h> #include <mach/kern_return.h> #include <mach/message.h> #include <mach/mig_errors.h> #include "mach_notify.h" #include <security_utilities/debugging.h> #include <malloc/malloc.h> #if defined(USECFCURRENTTIME) # include <CoreFoundation/CFDate.h> #else # include <sys/time.h> #endif namespace Security { namespace MachPlusPlus { // // Global per-thread information // ModuleNexus< ThreadNexus<MachServer::PerThread> > MachServer::thread; // // Create a server object. // The resulting object is not "active", and any number of server objects // can be in this "prepared" state at the same time. // MachServer::MachServer() { setup("(anonymous)"); } MachServer::MachServer(const char *name) : mServerPort(name, bootstrap) { setup(name); } MachServer::MachServer(const char *name, const Bootstrap &boot) : bootstrap(boot), mServerPort(name, bootstrap) { setup(name); } void MachServer::setup(const char *name) { workerTimeout = 60 * 2; // 2 minutes default timeout maxWorkerCount = 100; // sanity check limit useFloatingThread = false; // tight thread management mPortSet += mServerPort; } MachServer::~MachServer() { // The ReceivePort members will clean themselves up. // The bootstrap server will clear us from its map when our receive port dies. } // // Add and remove extra listening ports. // Messages directed to those ports are dispatched through the main handler. // To get automatic call-out to another handler, use the Handler class. // void MachServer::add(Port receiver) { SECURITY_MACHSERVER_PORT_ADD(receiver); mPortSet += receiver; } void MachServer::remove(Port receiver) { SECURITY_MACHSERVER_PORT_REMOVE(receiver); mPortSet -= receiver; } // // Register for mach port notifications // void MachServer::notifyIfDead(Port port, bool doNotify) const { if (doNotify) port.requestNotify(mServerPort); else port.cancelNotify(); } void MachServer::notifyIfUnused(Port port, bool doNotify) const { if (doNotify) port.requestNotify(port, MACH_NOTIFY_NO_SENDERS, true); else port.cancelNotify(MACH_NOTIFY_NO_SENDERS); } // // Initiate service. // This call will take control of the current thread and use it to service // incoming requests. The thread will not be released until an error happens, which // will cause an exception to be thrown. In other words, this never returns normally. // We may also be creating additional threads to service concurrent requests // as appropriate. // @@@ Msg-errors in additional threads are not acted upon. // void MachServer::run(mach_msg_size_t maxSize, mach_msg_options_t options) { // establish server-global (thread-shared) parameters mMaxSize = maxSize; mMsgOptions = options; // establish the thread pool state // (don't need managerLock since we're the only thread as of yet) idleCount = workerCount = 1; nextCheckTime = Time::now() + workerTimeout; leastIdleWorkers = 1; highestWorkerCount = 1; // run server loop in initial (immortal) thread SECURITY_MACHSERVER_START_THREAD(false); runServerThread(false); SECURITY_MACHSERVER_END_THREAD(false); // primary server thread exited somehow (not currently possible) assert(false); } // // This is the core of a server thread at work. It takes over the thread until // (a) an error occurs, throwing an exception // (b) low-load timeout happens, causing a normal return (doTimeout only) // This code was once based on mach_msg_server.c, but it is getting harder to notice // the lingering resemblance. // extern "C" boolean_t cdsa_notify_server(mach_msg_header_t *in, mach_msg_header_t *out); void MachServer::runServerThread(bool doTimeout) { // allocate request/reply buffers Message bufRequest(mMaxSize); Message bufReply(mMaxSize); // all exits from runServerThread are through exceptions try { // register as a worker thread perThread().server = this; for (;;) { // progress hook eventDone(); // process all pending timers while (processTimer()) {} // check for worker idle timeout { StLock<Mutex> _(managerLock); // record idle thread low-water mark in scan interval if (idleCount < leastIdleWorkers) leastIdleWorkers = idleCount; // perform self-timeout processing if (doTimeout) { if (workerCount > maxWorkerCount) // someone reduced maxWorkerCount recently... break; // ... so release this thread immediately Time::Absolute rightNow = Time::now(); if (rightNow >= nextCheckTime) { // reaping period complete; process UInt32 idlers = leastIdleWorkers; SECURITY_MACHSERVER_REAP(workerCount, idlers); nextCheckTime = rightNow + workerTimeout; leastIdleWorkers = INT_MAX; if (idlers > 1) // multiple idle threads throughout measuring interval... break; // ... so release this thread now } } } // determine next timeout (if any) bool indefinite = false; Time::Interval timeout = workerTimeout; { StLock<Mutex> _(managerLock); if (timers.empty()) { indefinite = !doTimeout; } else { timeout = max(Time::Interval(0), timers.next() - Time::now()); if (doTimeout && workerTimeout < timeout) timeout = workerTimeout; } } if (SECURITY_MACHSERVER_RECEIVE_ENABLED()) SECURITY_MACHSERVER_RECEIVE(indefinite ? 0 : timeout.seconds()); // receive next IPC request (or wait for timeout) mach_msg_return_t mr = indefinite ? mach_msg_overwrite(bufRequest, MACH_RCV_MSG | mMsgOptions, 0, mMaxSize, mPortSet, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL, (mach_msg_header_t *) 0, 0) : mach_msg_overwrite(bufRequest, MACH_RCV_MSG | MACH_RCV_TIMEOUT | MACH_RCV_INTERRUPT | mMsgOptions, 0, mMaxSize, mPortSet, mach_msg_timeout_t(timeout.mSeconds()), MACH_PORT_NULL, (mach_msg_header_t *) 0, 0); switch (mr) { case MACH_MSG_SUCCESS: // process received request message below break; default: SECURITY_MACHSERVER_RECEIVE_ERROR(mr); continue; } // process received message if (bufRequest.msgId() >= MACH_NOTIFY_FIRST && bufRequest.msgId() <= MACH_NOTIFY_LAST) { // mach kernel notification message // we assume this is quick, so no thread arbitration here cdsa_notify_server(bufRequest, bufReply); } else { // normal request message StLock<MachServer, &MachServer::busy, &MachServer::idle> _(*this); SECURITY_MACHSERVER_BEGIN(bufRequest.localPort(), bufRequest.msgId()); // try subsidiary handlers first bool handled = false; for (HandlerSet::const_iterator it = mHandlers.begin(); it != mHandlers.end(); it++) if (bufRequest.localPort() == (*it)->port()) { (*it)->handle(bufRequest, bufReply); handled = true; } if (!handled) { // unclaimed, send to main handler handle(bufRequest, bufReply); } SECURITY_MACHSERVER_END(); } // process reply generated by handler if (!(bufReply.bits() & MACH_MSGH_BITS_COMPLEX) && bufReply.returnCode() != KERN_SUCCESS) { if (bufReply.returnCode() == MIG_NO_REPLY) continue; // don't destroy the reply port right, so we can send an error message bufRequest.remotePort(MACH_PORT_NULL); mach_msg_destroy(bufRequest); } if (bufReply.remotePort() == MACH_PORT_NULL) { // no reply port, so destroy the reply if (bufReply.bits() & MACH_MSGH_BITS_COMPLEX) bufReply.destroy(); continue; } /* * We don't want to block indefinitely because the client * isn't receiving messages from the reply port. * If we have a send-once right for the reply port, then * this isn't a concern because the send won't block. * If we have a send right, we need to use MACH_SEND_TIMEOUT. * To avoid falling off the kernel's fast RPC path unnecessarily, * we only supply MACH_SEND_TIMEOUT when absolutely necessary. */ mr = mach_msg_overwrite(bufReply, (MACH_MSGH_BITS_REMOTE(bufReply.bits()) == MACH_MSG_TYPE_MOVE_SEND_ONCE) ? MACH_SEND_MSG | mMsgOptions : MACH_SEND_MSG | MACH_SEND_TIMEOUT | mMsgOptions, bufReply.length(), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL, NULL, 0); switch (mr) { case MACH_MSG_SUCCESS: break; default: SECURITY_MACHSERVER_SEND_ERROR(mr, bufReply.remotePort()); bufReply.destroy(); break; } // clean up after the transaction releaseDeferredAllocations(); } perThread().server = NULL; } catch (...) { perThread().server = NULL; throw; } } // // Manage subsidiary port handlers // void MachServer::add(Handler &handler) { assert(mHandlers.find(&handler) == mHandlers.end()); assert(handler.port() != MACH_PORT_NULL); mHandlers.insert(&handler); mPortSet += handler.port(); } void MachServer::remove(Handler &handler) { assert(mHandlers.find(&handler) != mHandlers.end()); mHandlers.erase(&handler); mPortSet -= handler.port(); } // // Abstract auxiliary message handlers // MachServer::Handler::~Handler() { /* virtual */ } // // Implement a Handler that sends no reply // boolean_t MachServer::NoReplyHandler::handle(mach_msg_header_t *in, mach_msg_header_t *out) { // set up reply message to be valid (enough) and read "do not send reply" out->msgh_bits = 0; out->msgh_remote_port = MACH_PORT_NULL; out->msgh_size = sizeof(mig_reply_error_t); ((mig_reply_error_t *)out)->RetCode = MIG_NO_REPLY; // call input-only handler return handle(in); } // // Register a memory block for deferred release. // void MachServer::releaseWhenDone(Allocator &alloc, void *memory) { if (memory) { set<Allocation> &releaseSet = perThread().deferredAllocations; assert(releaseSet.find(Allocation(memory, alloc)) == releaseSet.end()); SECURITY_MACHSERVER_ALLOC_REGISTER(memory, &alloc); releaseSet.insert(Allocation(memory, alloc)); } } // // Run through the accumulated deferred allocations and release them. // This is done automatically on every pass through the server loop; // it must be called by subclasses that implement their loop in some // other way. // @@@X Needs to be thread local // void MachServer::releaseDeferredAllocations() { set<Allocation> &releaseSet = perThread().deferredAllocations; for (set<Allocation>::iterator it = releaseSet.begin(); it != releaseSet.end(); it++) { SECURITY_MACHSERVER_ALLOC_RELEASE(it->addr, it->allocator); // before we release the deferred allocation, zap it so that secrets aren't left in memory size_t memSize = malloc_size(it->addr); bzero(it->addr, memSize); it->allocator->free(it->addr); } releaseSet.erase(releaseSet.begin(), releaseSet.end()); } // // The handler function calls this if it realizes that it might be blocked // (or doing something that takes a long time). We respond by ensuring that // at least one more thread is ready to serve requests. // Calls the threadLimitReached callback in the server object if the thread // limit has been exceeded and a needed new thread was not created. // void MachServer::longTermActivity() { if (!useFloatingThread) { StLock<Mutex> _(managerLock); ensureReadyThread(); } } void MachServer::busy() { StLock<Mutex> _(managerLock); idleCount--; if (useFloatingThread) ensureReadyThread(); } void MachServer::idle() { StLock<Mutex> _(managerLock); idleCount++; } void MachServer::ensureReadyThread() { if (idleCount == 0) { if (workerCount >= maxWorkerCount) { this->threadLimitReached(workerCount); // call remedial handler } if (workerCount < maxWorkerCount) { // threadLimit() may have raised maxWorkerCount (new LoadThread(*this))->run(); } } } // // The callback hook for our subclasses. // The default does nothing, thereby denying further thread creation. // You could do something like maxThreads(limit+1) here to grant an variance; // or throw an exception to avoid possible deadlocks (this would abort the current // request but not otherwise impact the server's operation). // void MachServer::threadLimitReached(UInt32 limit) { } // // What our (non-primary) load threads do // void MachServer::LoadThread::action() { //@@@ race condition?! can server exit before helpers thread gets here? // register the worker thread and go server.addThread(this); try { SECURITY_MACHSERVER_START_THREAD(true); server.runServerThread(true); SECURITY_MACHSERVER_END_THREAD(false); } catch (...) { // fell out of server loop by error. Let the thread go quietly SECURITY_MACHSERVER_END_THREAD(true); } server.removeThread(this); } // // Thread accounting // void MachServer::addThread(Thread *thread) { StLock<Mutex> _(managerLock); workerCount++; idleCount++; workers.insert(thread); } void MachServer::removeThread(Thread *thread) { StLock<Mutex> _(managerLock); workerCount--; idleCount--; workers.erase(thread); } // // Timer management // MachServer::Timer::~Timer() { } void MachServer::Timer::select() { } void MachServer::Timer::unselect() { } bool MachServer::processTimer() { Timer *top; { StLock<Mutex> _(managerLock); // could have multiple threads trying this if (!(top = static_cast<Timer *>(timers.pop(Time::now())))) return false; // nothing (more) to be done now } // drop lock; work has been retrieved try { SECURITY_MACHSERVER_TIMER_START(top, top->longTerm(), Time::now().internalForm()); StLock<MachServer::Timer, &MachServer::Timer::select, &MachServer::Timer::unselect> _t(*top); if (top->longTerm()) { StLock<MachServer, &MachServer::busy, &MachServer::idle> _(*this); top->action(); } else { top->action(); } SECURITY_MACHSERVER_TIMER_END(false); } catch (...) { SECURITY_MACHSERVER_TIMER_END(true); } return true; } void MachServer::setTimer(Timer *timer, Time::Absolute when) { StLock<Mutex> _(managerLock); timers.schedule(timer, when); } void MachServer::clearTimer(Timer *timer) { StLock<Mutex> _(managerLock); if (timer->scheduled()) timers.unschedule(timer); } // // Notification hooks and shims. Defaults do nothing. // void cdsa_mach_notify_dead_name(mach_port_t, mach_port_name_t port) { try { MachServer::active().notifyDeadName(port); } catch (...) { } } void MachServer::notifyDeadName(Port) { } void cdsa_mach_notify_port_deleted(mach_port_t, mach_port_name_t port) { try { MachServer::active().notifyPortDeleted(port); } catch (...) { } } void MachServer::notifyPortDeleted(Port) { } void cdsa_mach_notify_port_destroyed(mach_port_t, mach_port_name_t port) { try { MachServer::active().notifyPortDestroyed(port); } catch (...) { } } void MachServer::notifyPortDestroyed(Port) { } void cdsa_mach_notify_send_once(mach_port_t port) { try { MachServer::active().notifySendOnce(port); } catch (...) { } } void MachServer::notifySendOnce(Port) { } void cdsa_mach_notify_no_senders(mach_port_t port, mach_port_mscount_t count) { try { MachServer::active().notifyNoSenders(port, count); } catch (...) { } } void MachServer::notifyNoSenders(Port, mach_port_mscount_t) { } void MachServer::eventDone() { } } // end namespace MachPlusPlus } // end namespace Security
27.621087
98
0.685614
[ "object" ]
8246e6d920e76a15b26344723eedd979583fe68d
9,437
cpp
C++
src/renderer/vt/tracing.cpp
utgwkk/terminal
4608fd0b94af2f4cf6ceec7b324ba36462e9c06b
[ "MIT" ]
2
2020-06-03T13:07:23.000Z
2020-06-04T16:39:36.000Z
src/renderer/vt/tracing.cpp
utgwkk/terminal
4608fd0b94af2f4cf6ceec7b324ba36462e9c06b
[ "MIT" ]
null
null
null
src/renderer/vt/tracing.cpp
utgwkk/terminal
4608fd0b94af2f4cf6ceec7b324ba36462e9c06b
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "tracing.hpp" #include <sstream> TRACELOGGING_DEFINE_PROVIDER(g_hConsoleVtRendererTraceProvider, "Microsoft.Windows.Console.Render.VtEngine", // tl:{c9ba2a95-d3ca-5e19-2bd6-776a0910cb9d} (0xc9ba2a95, 0xd3ca, 0x5e19, 0x2b, 0xd6, 0x77, 0x6a, 0x09, 0x10, 0xcb, 0x9d), TraceLoggingOptionMicrosoftTelemetry()); using namespace Microsoft::Console::VirtualTerminal; using namespace Microsoft::Console::Types; RenderTracing::RenderTracing() { #ifndef UNIT_TESTING TraceLoggingRegister(g_hConsoleVtRendererTraceProvider); #endif UNIT_TESTING } RenderTracing::~RenderTracing() { #ifndef UNIT_TESTING TraceLoggingUnregister(g_hConsoleVtRendererTraceProvider); #endif UNIT_TESTING } // Function Description: // - Convert the string to only have printable characters in it. Control // characters are converted to hat notation, spaces are converted to "SPC" // (to be able to see them at the end of a string), and DEL is written as // "\x7f". // Arguments: // - inString: The string to convert // Return Value: // - a string with only printable characters in it. std::string toPrintableString(const std::string_view& inString) { std::string retval = ""; for (size_t i = 0; i < inString.length(); i++) { unsigned char c = inString[i]; if (c < '\x20') { retval += "^"; char actual = (c + 0x40); retval += std::string(1, actual); } else if (c == '\x7f') { retval += "\\x7f"; } else if (c == '\x20') { retval += "SPC"; } else { retval += std::string(1, c); } } return retval; } void RenderTracing::TraceString(const std::string_view& instr) const { #ifndef UNIT_TESTING if (TraceLoggingProviderEnabled(g_hConsoleVtRendererTraceProvider, WINEVENT_LEVEL_VERBOSE, 0)) { const std::string _seq = toPrintableString(instr); const char* const seq = _seq.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceString", TraceLoggingUtf8String(seq), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } #else UNREFERENCED_PARAMETER(instr); #endif UNIT_TESTING } std::string _ViewportToString(const Viewport& view) { std::stringstream ss; ss << "{LT:("; ss << view.Left(); ss << ","; ss << view.Top(); ss << ") RB:("; ss << view.RightInclusive(); ss << ","; ss << view.BottomInclusive(); ss << ") ["; ss << view.Width(); ss << "x"; ss << view.Height(); ss << "]}"; std::string myString = ""; const auto s = ss.str(); myString += s; return myString; } std::string _CoordToString(const COORD& c) { std::stringstream ss; ss << "{"; ss << c.X; ss << ","; ss << c.Y; ss << "}"; const auto s = ss.str(); // Make sure you actually place this value in a local after calling, don't // just inline it to _CoordToString().c_str() return s; } void RenderTracing::TraceInvalidate(const Viewport invalidRect) const { #ifndef UNIT_TESTING if (TraceLoggingProviderEnabled(g_hConsoleVtRendererTraceProvider, WINEVENT_LEVEL_VERBOSE, 0)) { const auto invalidatedStr = _ViewportToString(invalidRect); const auto invalidated = invalidatedStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceInvalidate", TraceLoggingString(invalidated), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } #else UNREFERENCED_PARAMETER(invalidRect); #endif UNIT_TESTING } void RenderTracing::TraceInvalidateAll(const Viewport viewport) const { #ifndef UNIT_TESTING if (TraceLoggingProviderEnabled(g_hConsoleVtRendererTraceProvider, WINEVENT_LEVEL_VERBOSE, 0)) { const auto invalidatedStr = _ViewportToString(viewport); const auto invalidatedAll = invalidatedStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceInvalidateAll", TraceLoggingString(invalidatedAll), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } #else UNREFERENCED_PARAMETER(viewport); #endif UNIT_TESTING } void RenderTracing::TraceTriggerCircling(const bool newFrame) const { #ifndef UNIT_TESTING TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceTriggerCircling", TraceLoggingBool(newFrame), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); #else UNREFERENCED_PARAMETER(newFrame); #endif UNIT_TESTING } void RenderTracing::TraceStartPaint(const bool quickReturn, const bool invalidRectUsed, const Microsoft::Console::Types::Viewport invalidRect, const Microsoft::Console::Types::Viewport lastViewport, const COORD scrollDelt, const bool cursorMoved) const { #ifndef UNIT_TESTING if (TraceLoggingProviderEnabled(g_hConsoleVtRendererTraceProvider, WINEVENT_LEVEL_VERBOSE, 0)) { const auto invalidatedStr = _ViewportToString(invalidRect); const auto invalidated = invalidatedStr.c_str(); const auto lastViewStr = _ViewportToString(lastViewport); const auto lastView = lastViewStr.c_str(); const auto scrollDeltaStr = _CoordToString(scrollDelt); const auto scrollDelta = scrollDeltaStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceStartPaint", TraceLoggingBool(quickReturn), TraceLoggingBool(invalidRectUsed), TraceLoggingString(invalidated), TraceLoggingString(lastView), TraceLoggingString(scrollDelta), TraceLoggingBool(cursorMoved), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } #else UNREFERENCED_PARAMETER(quickReturn); UNREFERENCED_PARAMETER(invalidRectUsed); UNREFERENCED_PARAMETER(invalidRect); UNREFERENCED_PARAMETER(lastViewport); UNREFERENCED_PARAMETER(scrollDelt); UNREFERENCED_PARAMETER(cursorMoved); #endif UNIT_TESTING } void RenderTracing::TraceEndPaint() const { #ifndef UNIT_TESTING TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceEndPaint", TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); #else #endif UNIT_TESTING } void RenderTracing::TraceLastText(const COORD lastTextPos) const { #ifndef UNIT_TESTING if (TraceLoggingProviderEnabled(g_hConsoleVtRendererTraceProvider, WINEVENT_LEVEL_VERBOSE, 0)) { const auto lastTextStr = _CoordToString(lastTextPos); const auto lastText = lastTextStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceLastText", TraceLoggingString(lastText), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); } #else UNREFERENCED_PARAMETER(lastTextPos); #endif UNIT_TESTING } void RenderTracing::TraceMoveCursor(const COORD lastTextPos, const COORD cursor) const { #ifndef UNIT_TESTING const auto lastTextStr = _CoordToString(lastTextPos); const auto lastText = lastTextStr.c_str(); const auto cursorStr = _CoordToString(cursor); const auto cursorPos = cursorStr.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceMoveCursor", TraceLoggingString(lastText), TraceLoggingString(cursorPos), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); #else UNREFERENCED_PARAMETER(lastTextPos); UNREFERENCED_PARAMETER(cursor); #endif UNIT_TESTING } void RenderTracing::TraceWrapped() const { #ifndef UNIT_TESTING const auto* const msg = "Wrapped instead of \\r\\n"; TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TraceWrapped", TraceLoggingString(msg), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); #else #endif UNIT_TESTING } void RenderTracing::TracePaintCursor(const COORD coordCursor) const { #ifndef UNIT_TESTING const auto cursorPosString = _CoordToString(coordCursor); const auto cursorPos = cursorPosString.c_str(); TraceLoggingWrite(g_hConsoleVtRendererTraceProvider, "VtEngine_TracePaintCursor", TraceLoggingString(cursorPos), TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE)); #else UNREFERENCED_PARAMETER(coordCursor); #endif UNIT_TESTING }
34.567766
107
0.624563
[ "render" ]
8248610a9a02f04aa70d507a7806d1fb252cc7ab
45,327
cc
C++
wrappers/8.1.1/vtkMultiBlockPLOT3DReaderWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkMultiBlockPLOT3DReaderWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkMultiBlockPLOT3DReaderWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkMultiBlockDataSetAlgorithmWrap.h" #include "vtkMultiBlockPLOT3DReaderWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkMultiProcessControllerWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkMultiBlockPLOT3DReaderWrap::ptpl; VtkMultiBlockPLOT3DReaderWrap::VtkMultiBlockPLOT3DReaderWrap() { } VtkMultiBlockPLOT3DReaderWrap::VtkMultiBlockPLOT3DReaderWrap(vtkSmartPointer<vtkMultiBlockPLOT3DReader> _native) { native = _native; } VtkMultiBlockPLOT3DReaderWrap::~VtkMultiBlockPLOT3DReaderWrap() { } void VtkMultiBlockPLOT3DReaderWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkMultiBlockPLOT3DReader").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("MultiBlockPLOT3DReader").ToLocalChecked(), ConstructorGetter); } void VtkMultiBlockPLOT3DReaderWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkMultiBlockPLOT3DReaderWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkMultiBlockDataSetAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkMultiBlockDataSetAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkMultiBlockPLOT3DReaderWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "AddFunction", AddFunction); Nan::SetPrototypeMethod(tpl, "addFunction", AddFunction); Nan::SetPrototypeMethod(tpl, "AutoDetectFormatOff", AutoDetectFormatOff); Nan::SetPrototypeMethod(tpl, "autoDetectFormatOff", AutoDetectFormatOff); Nan::SetPrototypeMethod(tpl, "AutoDetectFormatOn", AutoDetectFormatOn); Nan::SetPrototypeMethod(tpl, "autoDetectFormatOn", AutoDetectFormatOn); Nan::SetPrototypeMethod(tpl, "BinaryFileOff", BinaryFileOff); Nan::SetPrototypeMethod(tpl, "binaryFileOff", BinaryFileOff); Nan::SetPrototypeMethod(tpl, "BinaryFileOn", BinaryFileOn); Nan::SetPrototypeMethod(tpl, "binaryFileOn", BinaryFileOn); Nan::SetPrototypeMethod(tpl, "CanReadBinaryFile", CanReadBinaryFile); Nan::SetPrototypeMethod(tpl, "canReadBinaryFile", CanReadBinaryFile); Nan::SetPrototypeMethod(tpl, "DoublePrecisionOff", DoublePrecisionOff); Nan::SetPrototypeMethod(tpl, "doublePrecisionOff", DoublePrecisionOff); Nan::SetPrototypeMethod(tpl, "DoublePrecisionOn", DoublePrecisionOn); Nan::SetPrototypeMethod(tpl, "doublePrecisionOn", DoublePrecisionOn); Nan::SetPrototypeMethod(tpl, "ForceReadOff", ForceReadOff); Nan::SetPrototypeMethod(tpl, "forceReadOff", ForceReadOff); Nan::SetPrototypeMethod(tpl, "ForceReadOn", ForceReadOn); Nan::SetPrototypeMethod(tpl, "forceReadOn", ForceReadOn); Nan::SetPrototypeMethod(tpl, "GetAutoDetectFormat", GetAutoDetectFormat); Nan::SetPrototypeMethod(tpl, "getAutoDetectFormat", GetAutoDetectFormat); Nan::SetPrototypeMethod(tpl, "GetBinaryFile", GetBinaryFile); Nan::SetPrototypeMethod(tpl, "getBinaryFile", GetBinaryFile); Nan::SetPrototypeMethod(tpl, "GetByteOrder", GetByteOrder); Nan::SetPrototypeMethod(tpl, "getByteOrder", GetByteOrder); Nan::SetPrototypeMethod(tpl, "GetByteOrderAsString", GetByteOrderAsString); Nan::SetPrototypeMethod(tpl, "getByteOrderAsString", GetByteOrderAsString); Nan::SetPrototypeMethod(tpl, "GetController", GetController); Nan::SetPrototypeMethod(tpl, "getController", GetController); Nan::SetPrototypeMethod(tpl, "GetDoublePrecision", GetDoublePrecision); Nan::SetPrototypeMethod(tpl, "getDoublePrecision", GetDoublePrecision); Nan::SetPrototypeMethod(tpl, "GetFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "getFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "GetForceRead", GetForceRead); Nan::SetPrototypeMethod(tpl, "getForceRead", GetForceRead); Nan::SetPrototypeMethod(tpl, "GetFunctionFileName", GetFunctionFileName); Nan::SetPrototypeMethod(tpl, "getFunctionFileName", GetFunctionFileName); Nan::SetPrototypeMethod(tpl, "GetGamma", GetGamma); Nan::SetPrototypeMethod(tpl, "getGamma", GetGamma); Nan::SetPrototypeMethod(tpl, "GetHasByteCount", GetHasByteCount); Nan::SetPrototypeMethod(tpl, "getHasByteCount", GetHasByteCount); Nan::SetPrototypeMethod(tpl, "GetIBlanking", GetIBlanking); Nan::SetPrototypeMethod(tpl, "getIBlanking", GetIBlanking); Nan::SetPrototypeMethod(tpl, "GetMultiGrid", GetMultiGrid); Nan::SetPrototypeMethod(tpl, "getMultiGrid", GetMultiGrid); Nan::SetPrototypeMethod(tpl, "GetPreserveIntermediateFunctions", GetPreserveIntermediateFunctions); Nan::SetPrototypeMethod(tpl, "getPreserveIntermediateFunctions", GetPreserveIntermediateFunctions); Nan::SetPrototypeMethod(tpl, "GetQFileName", GetQFileName); Nan::SetPrototypeMethod(tpl, "getQFileName", GetQFileName); Nan::SetPrototypeMethod(tpl, "GetR", GetR); Nan::SetPrototypeMethod(tpl, "getR", GetR); Nan::SetPrototypeMethod(tpl, "GetScalarFunctionNumber", GetScalarFunctionNumber); Nan::SetPrototypeMethod(tpl, "getScalarFunctionNumber", GetScalarFunctionNumber); Nan::SetPrototypeMethod(tpl, "GetTwoDimensionalGeometry", GetTwoDimensionalGeometry); Nan::SetPrototypeMethod(tpl, "getTwoDimensionalGeometry", GetTwoDimensionalGeometry); Nan::SetPrototypeMethod(tpl, "GetVectorFunctionNumber", GetVectorFunctionNumber); Nan::SetPrototypeMethod(tpl, "getVectorFunctionNumber", GetVectorFunctionNumber); Nan::SetPrototypeMethod(tpl, "GetXYZFileName", GetXYZFileName); Nan::SetPrototypeMethod(tpl, "getXYZFileName", GetXYZFileName); Nan::SetPrototypeMethod(tpl, "HasByteCountOff", HasByteCountOff); Nan::SetPrototypeMethod(tpl, "hasByteCountOff", HasByteCountOff); Nan::SetPrototypeMethod(tpl, "HasByteCountOn", HasByteCountOn); Nan::SetPrototypeMethod(tpl, "hasByteCountOn", HasByteCountOn); Nan::SetPrototypeMethod(tpl, "IBlankingOff", IBlankingOff); Nan::SetPrototypeMethod(tpl, "iBlankingOff", IBlankingOff); Nan::SetPrototypeMethod(tpl, "IBlankingOn", IBlankingOn); Nan::SetPrototypeMethod(tpl, "iBlankingOn", IBlankingOn); Nan::SetPrototypeMethod(tpl, "MultiGridOff", MultiGridOff); Nan::SetPrototypeMethod(tpl, "multiGridOff", MultiGridOff); Nan::SetPrototypeMethod(tpl, "MultiGridOn", MultiGridOn); Nan::SetPrototypeMethod(tpl, "multiGridOn", MultiGridOn); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "PreserveIntermediateFunctionsOff", PreserveIntermediateFunctionsOff); Nan::SetPrototypeMethod(tpl, "preserveIntermediateFunctionsOff", PreserveIntermediateFunctionsOff); Nan::SetPrototypeMethod(tpl, "PreserveIntermediateFunctionsOn", PreserveIntermediateFunctionsOn); Nan::SetPrototypeMethod(tpl, "preserveIntermediateFunctionsOn", PreserveIntermediateFunctionsOn); Nan::SetPrototypeMethod(tpl, "RemoveAllFunctions", RemoveAllFunctions); Nan::SetPrototypeMethod(tpl, "removeAllFunctions", RemoveAllFunctions); Nan::SetPrototypeMethod(tpl, "RemoveFunction", RemoveFunction); Nan::SetPrototypeMethod(tpl, "removeFunction", RemoveFunction); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetAutoDetectFormat", SetAutoDetectFormat); Nan::SetPrototypeMethod(tpl, "setAutoDetectFormat", SetAutoDetectFormat); Nan::SetPrototypeMethod(tpl, "SetBinaryFile", SetBinaryFile); Nan::SetPrototypeMethod(tpl, "setBinaryFile", SetBinaryFile); Nan::SetPrototypeMethod(tpl, "SetByteOrder", SetByteOrder); Nan::SetPrototypeMethod(tpl, "setByteOrder", SetByteOrder); Nan::SetPrototypeMethod(tpl, "SetByteOrderToBigEndian", SetByteOrderToBigEndian); Nan::SetPrototypeMethod(tpl, "setByteOrderToBigEndian", SetByteOrderToBigEndian); Nan::SetPrototypeMethod(tpl, "SetByteOrderToLittleEndian", SetByteOrderToLittleEndian); Nan::SetPrototypeMethod(tpl, "setByteOrderToLittleEndian", SetByteOrderToLittleEndian); Nan::SetPrototypeMethod(tpl, "SetController", SetController); Nan::SetPrototypeMethod(tpl, "setController", SetController); Nan::SetPrototypeMethod(tpl, "SetDoublePrecision", SetDoublePrecision); Nan::SetPrototypeMethod(tpl, "setDoublePrecision", SetDoublePrecision); Nan::SetPrototypeMethod(tpl, "SetFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "setFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "SetForceRead", SetForceRead); Nan::SetPrototypeMethod(tpl, "setForceRead", SetForceRead); Nan::SetPrototypeMethod(tpl, "SetFunctionFileName", SetFunctionFileName); Nan::SetPrototypeMethod(tpl, "setFunctionFileName", SetFunctionFileName); Nan::SetPrototypeMethod(tpl, "SetGamma", SetGamma); Nan::SetPrototypeMethod(tpl, "setGamma", SetGamma); Nan::SetPrototypeMethod(tpl, "SetHasByteCount", SetHasByteCount); Nan::SetPrototypeMethod(tpl, "setHasByteCount", SetHasByteCount); Nan::SetPrototypeMethod(tpl, "SetIBlanking", SetIBlanking); Nan::SetPrototypeMethod(tpl, "setIBlanking", SetIBlanking); Nan::SetPrototypeMethod(tpl, "SetMultiGrid", SetMultiGrid); Nan::SetPrototypeMethod(tpl, "setMultiGrid", SetMultiGrid); Nan::SetPrototypeMethod(tpl, "SetPreserveIntermediateFunctions", SetPreserveIntermediateFunctions); Nan::SetPrototypeMethod(tpl, "setPreserveIntermediateFunctions", SetPreserveIntermediateFunctions); Nan::SetPrototypeMethod(tpl, "SetQFileName", SetQFileName); Nan::SetPrototypeMethod(tpl, "setQFileName", SetQFileName); Nan::SetPrototypeMethod(tpl, "SetR", SetR); Nan::SetPrototypeMethod(tpl, "setR", SetR); Nan::SetPrototypeMethod(tpl, "SetScalarFunctionNumber", SetScalarFunctionNumber); Nan::SetPrototypeMethod(tpl, "setScalarFunctionNumber", SetScalarFunctionNumber); Nan::SetPrototypeMethod(tpl, "SetTwoDimensionalGeometry", SetTwoDimensionalGeometry); Nan::SetPrototypeMethod(tpl, "setTwoDimensionalGeometry", SetTwoDimensionalGeometry); Nan::SetPrototypeMethod(tpl, "SetVectorFunctionNumber", SetVectorFunctionNumber); Nan::SetPrototypeMethod(tpl, "setVectorFunctionNumber", SetVectorFunctionNumber); Nan::SetPrototypeMethod(tpl, "SetXYZFileName", SetXYZFileName); Nan::SetPrototypeMethod(tpl, "setXYZFileName", SetXYZFileName); Nan::SetPrototypeMethod(tpl, "TwoDimensionalGeometryOff", TwoDimensionalGeometryOff); Nan::SetPrototypeMethod(tpl, "twoDimensionalGeometryOff", TwoDimensionalGeometryOff); Nan::SetPrototypeMethod(tpl, "TwoDimensionalGeometryOn", TwoDimensionalGeometryOn); Nan::SetPrototypeMethod(tpl, "twoDimensionalGeometryOn", TwoDimensionalGeometryOn); #ifdef VTK_NODE_PLUS_VTKMULTIBLOCKPLOT3DREADERWRAP_INITPTPL VTK_NODE_PLUS_VTKMULTIBLOCKPLOT3DREADERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkMultiBlockPLOT3DReaderWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkMultiBlockPLOT3DReader> native = vtkSmartPointer<vtkMultiBlockPLOT3DReader>::New(); VtkMultiBlockPLOT3DReaderWrap* obj = new VtkMultiBlockPLOT3DReaderWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkMultiBlockPLOT3DReaderWrap::AddFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->AddFunction( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::AutoDetectFormatOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->AutoDetectFormatOff(); } void VtkMultiBlockPLOT3DReaderWrap::AutoDetectFormatOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->AutoDetectFormatOn(); } void VtkMultiBlockPLOT3DReaderWrap::BinaryFileOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BinaryFileOff(); } void VtkMultiBlockPLOT3DReaderWrap::BinaryFileOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BinaryFileOn(); } void VtkMultiBlockPLOT3DReaderWrap::CanReadBinaryFile(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->CanReadBinaryFile( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::DoublePrecisionOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DoublePrecisionOff(); } void VtkMultiBlockPLOT3DReaderWrap::DoublePrecisionOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->DoublePrecisionOn(); } void VtkMultiBlockPLOT3DReaderWrap::ForceReadOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ForceReadOff(); } void VtkMultiBlockPLOT3DReaderWrap::ForceReadOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ForceReadOn(); } void VtkMultiBlockPLOT3DReaderWrap::GetAutoDetectFormat(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetAutoDetectFormat(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetBinaryFile(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetBinaryFile(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetByteOrder(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetByteOrder(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetByteOrderAsString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetByteOrderAsString(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkMultiBlockPLOT3DReaderWrap::GetController(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); vtkMultiProcessController * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetController(); VtkMultiProcessControllerWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkMultiProcessControllerWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkMultiProcessControllerWrap *w = new VtkMultiProcessControllerWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkMultiBlockPLOT3DReaderWrap::GetDoublePrecision(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDoublePrecision(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkMultiBlockPLOT3DReaderWrap::GetForceRead(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetForceRead(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetFunctionFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFunctionFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkMultiBlockPLOT3DReaderWrap::GetGamma(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetGamma(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetHasByteCount(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetHasByteCount(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetIBlanking(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetIBlanking(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetMultiGrid(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMultiGrid(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetPreserveIntermediateFunctions(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPreserveIntermediateFunctions(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetQFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetQFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkMultiBlockPLOT3DReaderWrap::GetR(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetR(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetScalarFunctionNumber(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetScalarFunctionNumber(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetTwoDimensionalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTwoDimensionalGeometry(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetVectorFunctionNumber(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVectorFunctionNumber(); info.GetReturnValue().Set(Nan::New(r)); } void VtkMultiBlockPLOT3DReaderWrap::GetXYZFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetXYZFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkMultiBlockPLOT3DReaderWrap::HasByteCountOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->HasByteCountOff(); } void VtkMultiBlockPLOT3DReaderWrap::HasByteCountOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->HasByteCountOn(); } void VtkMultiBlockPLOT3DReaderWrap::IBlankingOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->IBlankingOff(); } void VtkMultiBlockPLOT3DReaderWrap::IBlankingOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->IBlankingOn(); } void VtkMultiBlockPLOT3DReaderWrap::MultiGridOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MultiGridOff(); } void VtkMultiBlockPLOT3DReaderWrap::MultiGridOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MultiGridOn(); } void VtkMultiBlockPLOT3DReaderWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); vtkMultiBlockPLOT3DReader * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkMultiBlockPLOT3DReaderWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkMultiBlockPLOT3DReaderWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkMultiBlockPLOT3DReaderWrap *w = new VtkMultiBlockPLOT3DReaderWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkMultiBlockPLOT3DReaderWrap::PreserveIntermediateFunctionsOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->PreserveIntermediateFunctionsOff(); } void VtkMultiBlockPLOT3DReaderWrap::PreserveIntermediateFunctionsOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->PreserveIntermediateFunctionsOn(); } void VtkMultiBlockPLOT3DReaderWrap::RemoveAllFunctions(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->RemoveAllFunctions(); } void VtkMultiBlockPLOT3DReaderWrap::RemoveFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->RemoveFunction( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkMultiBlockPLOT3DReader * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkMultiBlockPLOT3DReaderWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkMultiBlockPLOT3DReaderWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkMultiBlockPLOT3DReaderWrap *w = new VtkMultiBlockPLOT3DReaderWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetAutoDetectFormat(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetAutoDetectFormat( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetBinaryFile(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetBinaryFile( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetByteOrder(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrder( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetByteOrderToBigEndian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrderToBigEndian(); } void VtkMultiBlockPLOT3DReaderWrap::SetByteOrderToLittleEndian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrderToLittleEndian(); } void VtkMultiBlockPLOT3DReaderWrap::SetController(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkMultiProcessControllerWrap::ptpl))->HasInstance(info[0])) { VtkMultiProcessControllerWrap *a0 = ObjectWrap::Unwrap<VtkMultiProcessControllerWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetController( (vtkMultiProcessController *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetDoublePrecision(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetDoublePrecision( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetForceRead(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetForceRead( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetFunctionFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFunctionFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetGamma(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetGamma( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetHasByteCount(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetHasByteCount( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetIBlanking(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetIBlanking( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetMultiGrid(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMultiGrid( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetPreserveIntermediateFunctions(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPreserveIntermediateFunctions( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetQFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetQFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetR(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetR( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetScalarFunctionNumber(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetScalarFunctionNumber( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetTwoDimensionalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTwoDimensionalGeometry( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetVectorFunctionNumber(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetVectorFunctionNumber( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::SetXYZFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetXYZFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkMultiBlockPLOT3DReaderWrap::TwoDimensionalGeometryOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->TwoDimensionalGeometryOff(); } void VtkMultiBlockPLOT3DReaderWrap::TwoDimensionalGeometryOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkMultiBlockPLOT3DReaderWrap *wrapper = ObjectWrap::Unwrap<VtkMultiBlockPLOT3DReaderWrap>(info.Holder()); vtkMultiBlockPLOT3DReader *native = (vtkMultiBlockPLOT3DReader *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->TwoDimensionalGeometryOn(); }
34.893764
118
0.761334
[ "object" ]
824b020295fba2d058778acb45c302920e56ddd3
23,138
cpp
C++
pytorch-frontend/test/cpp/api/nn_utils.cpp
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
206
2020-11-28T22:56:38.000Z
2022-03-27T02:33:04.000Z
pytorch-frontend/test/cpp/api/nn_utils.cpp
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
19
2020-12-09T23:13:14.000Z
2022-01-24T23:24:08.000Z
pytorch-frontend/test/cpp/api/nn_utils.cpp
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
28
2020-11-29T15:25:12.000Z
2022-01-20T02:16:27.000Z
#include <gtest/gtest.h> #include <torch/torch.h> #include <test/cpp/api/support.h> #include <algorithm> #include <random> using namespace torch::nn; namespace rnn_utils = torch::nn::utils::rnn; struct NNUtilsTest : torch::test::SeedingFixture {}; struct PackedSequenceTest : torch::test::SeedingFixture {}; TEST_F(NNUtilsTest, ClipGradNorm) { auto l = Linear(10, 10); float max_norm = 2; auto compute_norm = [&](float norm_type) -> float { float total_norm = 0.0; if (norm_type != std::numeric_limits<float>::infinity()) { for (const auto& p : l->parameters()) { total_norm += p.grad().data().abs().pow(norm_type).sum().item().toFloat(); } return std::pow(total_norm, 1.0 / norm_type); } else { for (const auto& p : l->parameters()) { auto param_max = p.grad().data().abs().max().item().toFloat(); if (param_max > total_norm) { total_norm = param_max; } } return total_norm; } }; auto compare_scaling = [&](const std::vector<torch::Tensor>& grads) -> torch::Tensor { std::vector<torch::Tensor> p_scale; for (int i = 0; i < grads.size(); i++) { auto param = l->parameters()[i]; auto grad = grads[i]; p_scale.push_back(param.grad().data().div(grad).view(-1)); } auto scale = torch::cat(p_scale); return scale; // need to assert std is 0. }; std::vector<torch::Tensor> grads = { torch::arange(1.0, 101).view({10, 10}), torch::ones({10}).div(1000), }; std::vector<float> norm_types = { 0.5, 1.5, 2.0, 4.0, std::numeric_limits<float>::infinity(), }; for (auto norm_type : norm_types) { for (int i = 0; i < grads.size(); i++) { l->parameters()[i].mutable_grad() = grads[i].clone().view_as(l->parameters()[i].data()); } auto norm_before = compute_norm(norm_type); auto norm = utils::clip_grad_norm_(l->parameters(), max_norm, norm_type); auto norm_after = compute_norm(norm_type); ASSERT_FLOAT_EQ(norm, norm_before); ASSERT_NEAR(norm_after, max_norm, 1e-6); ASSERT_LE(norm_after, max_norm); auto scaled = compare_scaling(grads); ASSERT_NEAR(0, scaled.std().item().toFloat(), 1e-7); } // Small gradients should be left unchanged grads = { torch::rand({10, 10}).div(10000), torch::ones(10).div(500), }; for (auto norm_type : norm_types) { for (int i = 0; i < grads.size(); i++) { l->parameters()[i].grad().data().copy_(grads[i]); } auto norm_before = compute_norm(norm_type); auto norm = utils::clip_grad_norm_(l->parameters(), max_norm, norm_type); auto norm_after = compute_norm(norm_type); ASSERT_FLOAT_EQ(norm, norm_before); ASSERT_FLOAT_EQ(norm_before, norm_after); ASSERT_LE(norm_after, max_norm); auto scaled = compare_scaling(grads); ASSERT_NEAR(0, scaled.std().item().toFloat(), 1e-7); ASSERT_EQ(scaled[0].item().toFloat(), 1); } // should accept a single tensor as input auto p1 = torch::randn({10, 10}); auto p2 = torch::randn({10, 10}); auto g = torch::arange(1., 101).view({10, 10}); p1.mutable_grad() = g.clone(); p2.mutable_grad() = g.clone(); for (const auto norm_type : norm_types) { utils::clip_grad_norm_(p1, max_norm, norm_type); utils::clip_grad_norm_({p2}, max_norm, norm_type); ASSERT_TRUE(torch::allclose(p1.grad(), p2.grad())); } } TEST_F(NNUtilsTest, ClipGradValue) { auto l = Linear(10, 10); float clip_value = 2.5; torch::Tensor grad_w = torch::arange(-50., 50).view({10, 10}).div_(5); torch::Tensor grad_b = torch::ones({10}).mul_(2); std::vector<std::vector<torch::Tensor>> grad_lists = { {grad_w, grad_b}, {grad_w, torch::Tensor()}}; for (auto grad_list : grad_lists) { for (int i = 0; i < grad_list.size(); i++) { auto p = l->parameters()[i]; auto g = grad_list[i]; p.mutable_grad() = g.defined() ? g.clone().view_as(p.data()) : g; } utils::clip_grad_value_(l->parameters(), clip_value); for (const auto& p : l->parameters()) { if (p.grad().defined()) { ASSERT_LE( p.grad().data().max().item().toFloat(), clip_value); ASSERT_GE( p.grad().data().min().item().toFloat(), -clip_value); } } } // Should accept a single Tensor as input auto p1 = torch::randn({10, 10}); auto p2 = torch::randn({10, 10}); auto g = torch::arange(-50., 50).view({10, 10}).div_(5); p1.mutable_grad() = g.clone(); p2.mutable_grad() = g.clone(); utils::clip_grad_value_(p1, clip_value); utils::clip_grad_value_({p2}, clip_value); ASSERT_TRUE(torch::allclose(p1.grad(), p2.grad())); } TEST_F(NNUtilsTest, ConvertParameters) { std::vector<torch::Tensor> parameters{ torch::arange(9, torch::kFloat32), torch::arange(9, torch::kFloat32).view({3, 3}), torch::arange(8, torch::kFloat32).view({2, 2, 2}) }; auto expected = torch::cat({ torch::arange(9, torch::kFloat32), torch::arange(9, torch::kFloat32).view(-1), torch::arange(8, torch::kFloat32).view(-1) }); auto vector = utils::parameters_to_vector(parameters); ASSERT_TRUE(vector.allclose(expected)); std::vector<torch::Tensor> zero_parameters{ torch::zeros({9}, torch::kFloat32), torch::zeros({9}, torch::kFloat32).view({3, 3}), torch::zeros({8}, torch::kFloat32).view({2, 2, 2}) }; utils::vector_to_parameters(vector, zero_parameters); for (int i = 0; i < zero_parameters.size(); ++i) { ASSERT_TRUE(zero_parameters[i].allclose(parameters[i])); } { auto conv1 = Conv2d(3, 10, 5); auto fc1 = Linear(10, 20); auto model = Sequential(conv1, fc1); auto vec = utils::parameters_to_vector(model->parameters()); ASSERT_EQ(vec.size(0), 980); } { auto conv1 = Conv2d(3, 10, 5); auto fc1 = Linear(10, 20); auto model = Sequential(conv1, fc1); auto vec = torch::arange(0., 980); utils::vector_to_parameters(vec, model->parameters()); auto sample = model->parameters()[0][0][0][0]; ASSERT_TRUE(torch::equal(sample.data(), vec.data().slice(0, 0, 5))); } } int64_t PackedSequenceTest_batch_size = 5; int64_t PackedSequenceTest_max_length = 6; std::vector<torch::Tensor> PackedSequenceTest_ordered_sequence(torch::ScalarType tensor_type) { std::vector<torch::Tensor> seqs; seqs.reserve(PackedSequenceTest_batch_size); for (int64_t i = 0; i < PackedSequenceTest_batch_size; i++) { seqs.emplace_back(torch::empty({ torch::randint(1, PackedSequenceTest_max_length, {1}).item<int64_t>() }, tensor_type)); } for (auto& s : seqs) { s.random_(-128, 128); } sort( seqs.begin(), seqs.end(), [&](const torch::Tensor& t1, const torch::Tensor& t2) { return t1.size(0) > t2.size(0); } ); return seqs; } std::tuple<torch::Tensor, torch::Tensor> PackedSequenceTest_padded_sequence(torch::ScalarType tensor_type) { // Create Tensor of random padded sequences auto ordered = PackedSequenceTest_ordered_sequence(tensor_type); auto lengths = torch::empty({(int64_t)ordered.size()}, torch::kInt64); for (int64_t i = 0; i < ordered.size(); i++) { lengths[i] = ordered[i].size(0); } auto padded_tensor = rnn_utils::pad_sequence(ordered); return std::make_tuple(padded_tensor, lengths); } void assert_is_equal_packed_sequence(const rnn_utils::PackedSequence& a, const rnn_utils::PackedSequence& b) { ASSERT_TRUE(torch::allclose(a.data(), b.data())); ASSERT_TRUE(torch::allclose(a.batch_sizes(), b.batch_sizes())); ASSERT_TRUE( (!a.sorted_indices().defined() && !b.sorted_indices().defined()) || torch::allclose(a.sorted_indices(), b.sorted_indices())); ASSERT_TRUE( (!a.unsorted_indices().defined() && !b.unsorted_indices().defined()) || torch::allclose(a.unsorted_indices(), b.unsorted_indices())); } void assert_is_same_packed_sequence(const rnn_utils::PackedSequence& a, const rnn_utils::PackedSequence& b) { ASSERT_TRUE(a.data().is_same(b.data())); ASSERT_TRUE(a.batch_sizes().is_same(b.batch_sizes())); ASSERT_TRUE(a.sorted_indices().is_same(b.sorted_indices())); ASSERT_TRUE(a.unsorted_indices().is_same(b.unsorted_indices())); } TEST_F(PackedSequenceTest, WrongOrder) { auto a = torch::ones({25, 300}); auto b = torch::ones({22, 300}); auto b_a = rnn_utils::pad_sequence({b, a}); ASSERT_THROW( rnn_utils::pack_padded_sequence( b_a, torch::tensor({22, 25}), /*batch_first=*/false, /*enforce_sorted=*/true), c10::Error); } TEST_F(PackedSequenceTest, TotalLength) { torch::Tensor padded, lengths; std::tie(padded, lengths) = PackedSequenceTest_padded_sequence(torch::kFloat); int64_t max_length = torch::max(lengths).item<int64_t>(); rnn_utils::PackedSequence packed = rnn_utils::pack_padded_sequence(padded, lengths); // test ValueError if total_length < max_length for (int64_t total_length : std::vector<int64_t>{-1, 0, max_length - 1}) { for (bool batch_first : std::vector<bool>{true, false}) { auto err_fn = [&]() { rnn_utils::pad_packed_sequence( packed, /*batch_first=*/batch_first, /*padding_value=*/0.0, /*total_length=*/total_length); }; ASSERT_THROWS_WITH(err_fn(), "Expected total_length to be at least the length of the longest sequence in input"); } } // test that pad_packed_sequence returns results of correct length for (bool batch_first : std::vector<bool>{true, false}) { torch::Tensor no_extra_pad, ignored; std::tie(no_extra_pad, ignored) = rnn_utils::pad_packed_sequence( packed, /*batch_first=*/batch_first); for (int64_t total_length_delta : std::vector<int64_t>{0, 1, 8}) { int64_t total_length = max_length + total_length_delta; torch::Tensor unpacked, lengths_out; std::tie(unpacked, lengths_out) = rnn_utils::pad_packed_sequence( packed, /*batch_first=*/batch_first, /*padding_value=*/0.0, /*total_length=*/total_length); ASSERT_TRUE(torch::allclose(lengths, lengths_out)); ASSERT_EQ(unpacked.size(batch_first ? 1 : 0), total_length); torch::Tensor ref_output, extra_pad; if (total_length_delta == 0) { ref_output = no_extra_pad; } else if (batch_first) { extra_pad = torch::zeros({PackedSequenceTest_batch_size, total_length_delta}, no_extra_pad.options()); ref_output = torch::cat({no_extra_pad, extra_pad}, 1); } else { extra_pad = torch::zeros({total_length_delta, PackedSequenceTest_batch_size}, no_extra_pad.options()); ref_output = torch::cat({no_extra_pad, extra_pad}, 0); } ASSERT_TRUE(torch::allclose(unpacked, ref_output)); } } } TEST_F(PackedSequenceTest, To) { for (bool enforce_sorted : std::vector<bool>{true, false}) { torch::Tensor padded, lengths; std::tie(padded, lengths) = PackedSequenceTest_padded_sequence(torch::kInt); rnn_utils::PackedSequence a = rnn_utils::pack_padded_sequence( padded, lengths, /*batch_first=*/false, /*enforce_sorted=*/enforce_sorted).cpu(); assert_is_same_packed_sequence(a, a.to(torch::kCPU)); assert_is_same_packed_sequence(a, a.cpu()); assert_is_same_packed_sequence(a, a.to(torch::device(torch::kCPU).dtype(torch::kInt32))); if (torch::cuda::is_available()) { auto b = a.cuda(); assert_is_same_packed_sequence(b, b.to(torch::kCUDA)); assert_is_same_packed_sequence(b, b.cuda()); assert_is_equal_packed_sequence(a, b.to(torch::kCPU)); assert_is_equal_packed_sequence(b, a.to(torch::kCUDA)); assert_is_equal_packed_sequence(a, b.to(torch::device(torch::kCPU).dtype(torch::kInt32))); assert_is_same_packed_sequence(b, b.to(torch::kInt32)); } } } TEST_F(NNUtilsTest, PackSequence) { auto _compatibility_test = [&]( torch::ArrayRef<torch::Tensor> sequences, torch::Tensor lengths, bool batch_first, bool enforce_sorted = false) { torch::Tensor padded = rnn_utils::pad_sequence(sequences, batch_first); rnn_utils::PackedSequence packed = rnn_utils::pack_sequence(sequences, enforce_sorted); std::tuple<torch::Tensor, torch::Tensor> unpacked = rnn_utils::pad_packed_sequence(packed, batch_first); ASSERT_TRUE(torch::allclose(padded, std::get<0>(unpacked))); rnn_utils::PackedSequence pack_padded = rnn_utils::pack_padded_sequence( padded, lengths, batch_first, enforce_sorted); assert_is_equal_packed_sequence(packed, pack_padded); }; // single dimensional auto a = torch::tensor({1, 2, 3}); auto b = torch::tensor({4, 5}); auto c = torch::tensor({6}); rnn_utils::PackedSequence packed = rnn_utils::pack_sequence({a, b, c}, /*enforce_sorted=*/false); auto expected = torch::tensor({1, 4, 6, 2, 5, 3}); ASSERT_TRUE(torch::allclose(packed.batch_sizes(), torch::tensor({3, 2, 1}))); ASSERT_TRUE(torch::allclose(packed.data(), expected)); ASSERT_TRUE(torch::allclose(packed.sorted_indices(), torch::tensor({0, 1, 2}))); ASSERT_TRUE(torch::allclose(packed.unsorted_indices(), torch::tensor({0, 1, 2}))); rnn_utils::PackedSequence packed_unsorted = rnn_utils::pack_sequence({b, c, a}, /*enforce_sorted=*/false); ASSERT_TRUE(torch::allclose(packed_unsorted.batch_sizes(), torch::tensor({3, 2, 1}))); ASSERT_TRUE(torch::allclose(packed_unsorted.data(), expected)); ASSERT_TRUE(torch::allclose(packed_unsorted.sorted_indices(), torch::tensor({2, 0, 1}))); ASSERT_TRUE(torch::allclose(packed_unsorted.unsorted_indices(), torch::tensor({1, 2, 0}))); // single dimensional, enforce_sorted = True rnn_utils::PackedSequence packed_enforce_sorted = rnn_utils::pack_sequence({a, b, c}, /*enforce_sorted=*/true); ASSERT_TRUE(torch::allclose(packed_enforce_sorted.batch_sizes(), torch::tensor({3, 2, 1}))); ASSERT_TRUE(torch::allclose(packed_enforce_sorted.data(), expected)); ASSERT_FALSE(packed_enforce_sorted.sorted_indices().defined()); ASSERT_FALSE(packed_enforce_sorted.unsorted_indices().defined()); ASSERT_THROWS_WITH( rnn_utils::pack_sequence({b, c, a}, /*enforce_sorted=*/true), "must be sorted in decreasing order"); ASSERT_THROWS_WITH( rnn_utils::pack_sequence({b, c, a}, /*enforce_sorted=*/true), "You can pass `enforce_sorted=False`"); // more dimensions int64_t maxlen = 9; for (int64_t num_dim : std::vector<int64_t>{0, 1, 2, 3}) { std::vector<torch::Tensor> sequences; std::vector<int64_t> lengths_vec; std::vector<int64_t> trailing_dims(num_dim, 4); for (int64_t i = maxlen; i > 0; i--) { int64_t seq_len = i * i; lengths_vec.emplace_back(seq_len); std::vector<int64_t> tensor_sizes{seq_len, 5}; tensor_sizes.insert( tensor_sizes.end(), trailing_dims.begin(), trailing_dims.end()); sequences.emplace_back(torch::rand(tensor_sizes)); } std::vector<torch::Tensor> unsorted_sequences; for (const auto& s : sequences) { unsorted_sequences.emplace_back(s.clone()); } std::shuffle( std::begin(unsorted_sequences), std::end(unsorted_sequences), std::default_random_engine{}); std::vector<int64_t> unsorted_sequences_lengths_vec; for (const auto& t : unsorted_sequences) { unsorted_sequences_lengths_vec.emplace_back(t.size(0)); } // compatibility with other utilities for (bool batch_first : std::vector<bool>{true, false}) { for (bool enforce_sorted : std::vector<bool>{true, false}) { _compatibility_test( sequences, torch::tensor(lengths_vec), batch_first, enforce_sorted); } _compatibility_test( unsorted_sequences, torch::tensor(unsorted_sequences_lengths_vec), batch_first); } } } TEST_F(NNUtilsTest, PackPaddedSequence) { auto generate_test_case = [&]( torch::ArrayRef<int64_t> sorted_lengths, bool should_shuffle) { auto pad = [&](torch::Tensor tensor, int64_t length) { std::vector<int64_t> tensor_sizes{length - tensor.size(0)}; tensor_sizes.insert( tensor_sizes.end(), tensor.sizes().slice(1).begin(), tensor.sizes().slice(1).end()); return torch::cat({tensor, torch::zeros(tensor_sizes, tensor.options())}); }; int64_t max_length = sorted_lengths[0]; torch::Tensor batch_sizes = torch::empty({max_length}, torch::kInt64); for (int64_t i = 1; i < max_length + 1; i++) { int64_t total = 0; for (const auto& x : sorted_lengths) { if (x >= i) { total++; } } batch_sizes[i-1] = total; } int64_t offset = 0; std::vector<torch::Tensor> tensors_to_be_cat; for (int64_t i = 1; i < sorted_lengths.size() + 1; i++) { int64_t l = sorted_lengths.at(i-1); tensors_to_be_cat.emplace_back(pad(i * 100 + torch::arange(1., 5 * l + 1).view({l, 1, 5}), max_length)); } auto padded = torch::cat(tensors_to_be_cat, 1); std::vector<torch::Tensor> expected_data_vec; for (int64_t n = 0; n < batch_sizes.size(0); n++) { int64_t batch_size = batch_sizes[n].item<int64_t>(); for (int64_t i = 0; i < batch_size; i++) { expected_data_vec.emplace_back(torch::arange(1., 6) + (i + 1) * 100 + 5 * n); } } auto expected_data = torch::stack(expected_data_vec, /*dim=*/0); torch::Tensor unsorted_indices, lengths; if (should_shuffle) { // Shuffle the padded sequence to create an unsorted sequence std::vector<int64_t> permutation; for (int64_t i = 0; i < sorted_lengths.size(); i++) { permutation.emplace_back(i); } std::shuffle( std::begin(permutation), std::end(permutation), std::default_random_engine{}); unsorted_indices = torch::tensor(permutation); padded = padded.index_select(1, unsorted_indices); lengths = torch::tensor(sorted_lengths).index_select(0, unsorted_indices); } else { unsorted_indices = torch::Tensor(); lengths = torch::tensor(sorted_lengths); } return std::make_tuple( padded.requires_grad_(), lengths, expected_data, batch_sizes, unsorted_indices); }; std::vector<std::pair<std::vector<int64_t>, bool>> test_cases = { // sorted_lengths, should_shuffle {{10, 8, 4, 2, 2, 2, 1}, false}, {{11, 10, 8, 6, 4, 3, 1}, false}, {{11, 10, 8, 6, 4, 3, 1}, true} }; for (const auto& test_case : test_cases) { for (bool batch_first : std::vector<bool>{true, false}) { std::vector<int64_t> sorted_lengths = std::get<0>(test_case); bool should_shuffle = std::get<1>(test_case); torch::Tensor padded, lengths, expected_data, batch_sizes, unsorted_indices; std::tie(padded, lengths, expected_data, batch_sizes, unsorted_indices) = generate_test_case( sorted_lengths, should_shuffle); auto src = padded; if (batch_first) { src = src.transpose(0, 1); } // check output rnn_utils::PackedSequence packed = rnn_utils::pack_padded_sequence( src, lengths, /*batch_first=*/batch_first, /*enforce_sorted=*/!should_shuffle); ASSERT_TRUE(torch::allclose(packed.data(), expected_data)); ASSERT_TRUE(torch::allclose(packed.batch_sizes(), batch_sizes)); ASSERT_TRUE( (!packed.unsorted_indices().defined() && !unsorted_indices.defined()) || torch::allclose(packed.unsorted_indices(), unsorted_indices)); // test inverse torch::Tensor unpacked, unpacked_len; std::tie(unpacked, unpacked_len) = rnn_utils::pad_packed_sequence(packed, /*batch_first=*/batch_first); ASSERT_TRUE(torch::allclose(unpacked, src)); ASSERT_TRUE(torch::allclose(unpacked_len, lengths)); // check grad if (padded.grad().defined()) { torch::NoGradGuard no_grad; padded.grad().zero_(); } torch::Tensor grad_output; { torch::NoGradGuard no_grad; grad_output = unpacked.clone().normal_(); } unpacked.backward(grad_output); if (batch_first) { grad_output.transpose_(0, 1); } for (int64_t i = 0; i < lengths.size(0); i++) { int64_t l = lengths[i].item<int64_t>(); ASSERT_TRUE(torch::allclose( padded.grad().narrow(0, 0, l).select(1, i), grad_output.narrow(0, 0, l).select(1, i))); if (l < 10) { ASSERT_EQ( padded.grad().narrow(0, l, padded.grad().size(0) - l).select(1, i).abs().sum().item<double>(), 0); } } } } // test error messages ASSERT_THROWS_WITH(rnn_utils::pack_padded_sequence(torch::randn({3, 3}), torch::tensor({1, 3, 2})), "You can pass `enforce_sorted=False`"); ASSERT_THROWS_WITH(rnn_utils::pack_padded_sequence(torch::randn({0, 0}), torch::tensor({})), "empty tensor"); } TEST_F(NNUtilsTest, PadSequence) { auto pad = [&](const torch::Tensor& tensor, int64_t length) { torch::NoGradGuard no_grad; std::vector<int64_t> tensor_sizes{length - tensor.size(0)}; tensor_sizes.insert( tensor_sizes.end(), tensor.sizes().slice(1).begin(), tensor.sizes().slice(1).end()); return torch::cat({tensor, torch::zeros(tensor_sizes, tensor.options())}); }; // single dimensional auto a = torch::tensor({1, 2, 3}); auto b = torch::tensor({4, 5}); auto c = torch::tensor({6}); torch::Tensor expected, padded; // batch_first = true expected = torch::tensor({{4, 5, 0}, {1, 2, 3}, {6, 0, 0}}); padded = rnn_utils::pad_sequence({b, a, c}, true); ASSERT_TRUE(padded.allclose(expected)); // batch_first = false padded = rnn_utils::pad_sequence({b, a, c}); ASSERT_TRUE(padded.allclose(expected.transpose(0, 1))); // pad with non-zero value expected = torch::tensor({{4, 5, 1}, {1, 2, 3}, {6, 1, 1}}); padded = rnn_utils::pad_sequence({b, a, c}, true, 1); ASSERT_TRUE(padded.allclose(expected)); // Test pad sorted sequence expected = torch::tensor({{1, 2, 3}, {4, 5, 0}, {6, 0, 0}}); padded = rnn_utils::pad_sequence({a, b, c}, true); ASSERT_TRUE(padded.allclose(expected)); // more dimensions int64_t maxlen = 9; for (int64_t num_dim : std::vector<int64_t>{0, 1, 2, 3}) { std::vector<torch::Tensor> sequences; std::vector<int64_t> trailing_dims(num_dim, 4); for (int64_t i = 1; i < maxlen + 1; i++) { int64_t seq_len = i * i; std::vector<int64_t> tensor_sizes{seq_len, 5}; tensor_sizes.insert( tensor_sizes.end(), trailing_dims.begin(), trailing_dims.end()); sequences.emplace_back(torch::rand(tensor_sizes)); } std::shuffle( std::begin(sequences), std::end(sequences), std::default_random_engine{}); std::vector<torch::Tensor> expected_tensors; for (const torch::Tensor& seq : sequences) { expected_tensors.emplace_back(pad(seq, maxlen * maxlen)); } // batch first = true auto expected = torch::stack(expected_tensors); auto padded = rnn_utils::pad_sequence(sequences, true); ASSERT_TRUE(padded.allclose(expected)); // batch first = false padded = rnn_utils::pad_sequence(sequences); ASSERT_TRUE(padded.allclose(expected.transpose(0, 1))); } }
37.440129
113
0.649883
[ "vector", "model" ]
824dd956a7b790e25eb3b184187f5dba014b2c99
1,048
hpp
C++
src/percept/mesh/geometry/kernel/GeometryFactory.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
3
2017-08-08T21:06:02.000Z
2020-01-08T13:23:36.000Z
src/percept/mesh/geometry/kernel/GeometryFactory.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2016-12-17T00:18:56.000Z
2019-08-09T15:29:25.000Z
src/percept/mesh/geometry/kernel/GeometryFactory.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2017-11-30T07:02:41.000Z
2019-08-05T17:07:04.000Z
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering // Solutions of Sandia, LLC (NTESS). Under the terms of Contract // DE-NA0003525 with NTESS, the U.S. Government retains certain rights // in this software. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef GEOMETRYFACTORY_HPP #define GEOMETRYFACTORY_HPP #include <string> #include <percept/mesh/geometry/kernel/GeometryKernel.hpp> #include <percept/mesh/geometry/kernel/MeshGeometry.hpp> #include <percept/PerceptMesh.hpp> namespace percept { class GeometryFactory { public: GeometryFactory(GeometryKernel* kernel, MeshGeometry* geometry); virtual ~GeometryFactory(); bool read_file(const std::string& filename, stk::mesh::MetaData* meta_data); bool read_file(const std::string& filename, PerceptMesh *mesh) { return read_file(filename, mesh->get_fem_meta_data()); } protected: GeometryKernel* geomKernel; MeshGeometry* geomDatabase; }; } #endif // GEOMETRYFACTORY_HPP
28.324324
80
0.751908
[ "mesh", "geometry" ]
824e5af30d604da872cf52996942353c422b6363
5,583
cpp
C++
MMVII/src/TestLibsExtern/TestEigen.cpp
rumenmitrev/micmac
065de918bb963a1c0f472504862c3060e180d48b
[ "CECILL-B" ]
null
null
null
MMVII/src/TestLibsExtern/TestEigen.cpp
rumenmitrev/micmac
065de918bb963a1c0f472504862c3060e180d48b
[ "CECILL-B" ]
null
null
null
MMVII/src/TestLibsExtern/TestEigen.cpp
rumenmitrev/micmac
065de918bb963a1c0f472504862c3060e180d48b
[ "CECILL-B" ]
null
null
null
#include "include/MMVII_all.h" #define GPP11 (__GNUC__>=11) // G++11 /** \file TestEigen.cpp \brief File to test eigen library class Eigen::SimplicialLDLT< _MatrixType, _UpLo, _Ordering > A direct sparse LDLT Cholesky factorizations without square root. More... class Eigen::SimplicialLLT< _Matri */ #include "ExternalInclude/Eigen/Dense" #include "ExternalInclude/Eigen/Core" #include "ExternalInclude/Eigen/Eigenvalues" #include "ExternalInclude/Eigen/SparseCholesky" // #include "External/eigen-git-mirror-master/unsupported/Eigen/src/SparseExtra/MarketIO.h" #include "ExternalInclude/MarketIO.h" #include "ExternalInclude/Eigen/LU" using Eigen::MatrixXd; using Eigen::Map; using namespace Eigen; namespace MMVII { /// MMVII Appli for Testing boost serialization service /** Probably obsolete */ class cAppli_MMVII_TestEigen : public cMMVII_Appli { public : cAppli_MMVII_TestEigen(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) ; int Exe() override ; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override {return anArgObl;} cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override;// override {return anArgOpt;} void T1(); ///< Un test de la doc void TestRawData(); ///< Test sur l'import des raw data void TCho(); void BenchCho(); void TestInv(); private : bool mTestRawD; int mNbCho; std::string mNameMatMark; }; cCollecSpecArg2007 & cAppli_MMVII_TestEigen::ArgOpt(cCollecSpecArg2007 & anArgOpt) { return anArgOpt << AOpt2007(mNbCho,"NbCho","Size Mat in choleski",{}) << AOpt2007(mNameMatMark,"NMM","Name of Matrix Market for Bench",{}) << AOpt2007(mTestRawD,"TIRD","Test Import Raw Data",{}) ; } cAppli_MMVII_TestEigen::cAppli_MMVII_TestEigen (const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec), mTestRawD (false), mNbCho (-1) { } int cAppli_MMVII_TestEigen::Exe() { if (mTestRawD) { TestRawData(); } while (mNbCho>0) { TCho(); getchar(); } if (IsInit(&mNameMatMark)) BenchCho(); return EXIT_SUCCESS; } void cAppli_MMVII_TestEigen::T1() { MatrixXd m(2,2); m(0,0) = 3; m(1,0) = 2.5; m(0,1) = -1; m(1,1) = m(1,0) + m(0,1); StdOut() << m << "\n";; } void cAppli_MMVII_TestEigen::TestInv() { // for (int aK=0 ; aK } void cAppli_MMVII_TestEigen::TestRawData() { cPt2di aSz(3,2); cIm2D<double> aIm(aSz); cDataIm2D<double> & aDIM=aIm.DIm(); for (const auto & aP : aDIM) aDIM.SetV(aP,10*aP.x() + aP.y()); { StdOut() << "RowMajor SzY SzX \n"; Map<Matrix<double,Dynamic,Dynamic,RowMajor> > aMap(aDIM.RawDataLin(),aSz.y(),aSz.x()); StdOut() << aMap << "\n"; } { StdOut() << "ColumnMajor SzX SzY \n"; Map<Matrix<double,Dynamic,Dynamic> > aMap(aDIM.RawDataLin(),aSz.x(),aSz.y()); StdOut() << aMap << "\n"; } } void cAppli_MMVII_TestEigen::BenchCho() { SparseMatrix<double> aS2; loadMarket(aS2,mNameMatMark); StdOut() << " NB " << aS2.rows() << " " << aS2.cols() << "\n"; double aT1 = SecFromT0(); SimplicialLDLT<SparseMatrix<double> > aDLT(aS2); double aT2 = SecFromT0(); StdOut() << "DONE " << aT2 - aT1 << "\n"; } void cAppli_MMVII_TestEigen::TCho() { #if (GPP1) int aSzBrd = 3; Matrix<double,Dynamic,Dynamic> m(mNbCho,mNbCho); VectorXd aSol(mNbCho); for (int aX=0 ; aX<mNbCho ; aX++) { aSol(aX) = RandUnif_0_1(); for (int aY=aX ; aY<mNbCho ; aY++) { if (aX==aY) { m(aX,aY) = 2* mNbCho + RandUnif_0_1(); } else if ((std::abs(aX-aY) <aSzBrd) && ( RandUnif_0_1() < 0.5)) { m(aX,aY) = m(aY,aX) = RandUnif_0_1(); } else { m(aX,aY) = m(aY,aX) = 0.0; } } } VectorXd aB = m * aSol; StdOut() << m << "\n"; SelfAdjointEigenSolver<MatrixXd> aSAES(m); StdOut() << "The eigenvalues of A are: " << aSAES.eigenvalues().transpose() << "\n"; StdOut() << aSAES.eigenvectors() << "\n"; double aDetEV = aSAES.eigenvalues().prod(); std::vector<Triplet<double> > aVT; for (int aX=0 ; aX<mNbCho ; aX++) { // for (int aY=aX ; aY<mNbCho ; aY++) // for (int aY=0 ; aY<mNbCho ; aY++) for (int aY=0 ; aY<=aX ; aY++) // !!! => les algo sur les sparse matrix doivent faire des supoistion triang sup ou inf { if (m(aX,aY) != 0.0) aVT.push_back(Triplet<double>(aX,aY,m(aX,aY))); } } SparseMatrix<double> aSM(mNbCho,mNbCho); aSM.setFromTriplets(aVT.begin(), aVT.end()); SimplicialLDLT<SparseMatrix<double> > aDLT(aSM); // aDLT.compute(m); StdOut() << "Det= " << aDLT.determinant() << " " << aDetEV << "\n"; VectorXd aSolCho = aDLT.solve(aB); StdOut() << "Check Sol " << (aSolCho - aSol).norm() << "\n"; #endif } tMMVII_UnikPApli Alloc_MMVII_TestEigen(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MMVII_TestEigen(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpec_TestEigen ( "TestEigen", Alloc_MMVII_TestEigen, "This command execute some experiments eigen (matrix manipulation) library", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); /* */ };
24.064655
128
0.592871
[ "vector" ]
825697827bc79287664204ce5c9b0f1e642c620f
4,142
cpp
C++
plugins/microservices/src/atomic_apply_acl_operations.cpp
aghsmith/irods
31d48a47a4942df688da94b30aa8a5b5210261bb
[ "BSD-3-Clause" ]
1
2022-03-08T13:00:56.000Z
2022-03-08T13:00:56.000Z
plugins/microservices/src/atomic_apply_acl_operations.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
plugins/microservices/src/atomic_apply_acl_operations.cpp
selroc/irods
d232c7f3e0154cacc3a115aa50e366a98617b126
[ "BSD-3-Clause" ]
null
null
null
/// \file #include "irods/irods_ms_plugin.hpp" #include "irods/irods_re_structs.hpp" #include "irods/msParam.h" #include "irods/rodsErrorTable.h" #include "irods/rs_atomic_apply_acl_operations.hpp" #include "irods/irods_error.hpp" #include "irods/irods_logger.hpp" #include <functional> #include <string> #include <exception> namespace { using log = irods::experimental::log; auto to_string(msParam_t& _p) -> const char* { const auto* s = parseMspForStr(&_p); if (!s) { THROW(SYS_INVALID_INPUT_PARAM, "Failed to convert microservice argument to string."); } return s; } auto msi_impl(msParam_t* _json_input, msParam_t* _json_output, ruleExecInfo_t* _rei) -> int { if (!_json_input || !_json_output) { log::microservice::error("Invalid input argument."); return SYS_INVALID_INPUT_PARAM; } try { const auto* json_input = to_string(*_json_input); char* json_output{}; if (const auto ec = rs_atomic_apply_acl_operations(_rei->rsComm, json_input, &json_output); ec != 0) { log::microservice::error("Failed to update ACLs [error_code={}]", ec); return ec; } fillStrInMsParam(_json_output, json_output); return 0; } catch (const irods::exception& e) { log::microservice::error("{} [error_code={}]", e.what(), e.code()); return e.code(); } catch (const std::exception& e) { log::microservice::error(e.what()); return SYS_INTERNAL_ERR; } catch (...) { log::microservice::error("An unknown error occurred while processing the request."); return SYS_UNKNOWN_ERROR; } } template <typename... Args, typename Function> auto make_msi(const std::string& _name, Function _func) -> irods::ms_table_entry* { auto* msi = new irods::ms_table_entry{sizeof...(Args)}; msi->add_operation(_name, std::function<int(Args..., ruleExecInfo_t*)>(_func)); return msi; } } // anonymous namespace extern "C" auto plugin_factory() -> irods::ms_table_entry* { return make_msi<msParam_t*, msParam_t*>("msi_atomic_apply_acl_operations", msi_impl); } #ifdef IRODS_FOR_DOXYGEN /// \brief Executes a list of ACL operations on a single data object or collection atomically. /// /// Sequentially executes all \p operations on \p logical_path as a single transaction. If an /// error occurs, all updates are rolled back and an error is returned. \p _json_output will /// contain specific information about the error. /// /// \p _json_input must have the following JSON structure: /// \code{.js} /// { /// "logical_path": string, /// "operations": [ /// { /// "entity_name": string, /// "acl": string /// } /// ] /// } /// \endcode /// /// \p logical_path must be an absolute path to a data object or collection. /// /// \p operations is the list of ACL operations to execute atomically. They will be executed in order. /// /// \p entity_name is the name of the user or group for which the ACL is being set. /// /// \p acl must be one of the following: /// - read /// - write /// - own /// - null (removes the ACL) /// /// On error, \p _json_output will have the following JSON structure: /// \code{.js} /// { /// "operation": string, /// "operation_index": integer, /// "error_message": string /// } /// \endcode /// /// \param[in] _json_input A JSON string containing the batch of ACL operations. /// \param[in,out] _json_output A JSON string containing the error information on failure. /// \param[in,out] _rei A ::RuleExecInfo object that is automatically handled by the /// rule engine plugin framework. Users must ignore this parameter. /// /// \return An integer. /// \retval 0 On success. /// \retval non-zero On failure. /// /// \since 4.2.9 auto msi_atomic_apply_acl_operations(msParam_t* _json_input, msParam_t* _json_output, ruleExecInfo_t* _rei) -> int; #endif // IRODS_FOR_DOXYGEN
31.142857
115
0.631338
[ "object" ]
8257ca85bfd29cb10429996740c1fcb06e21937f
9,429
cpp
C++
tem/src/v20210701/model/CreateApplicationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
tem/src/v20210701/model/CreateApplicationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
tem/src/v20210701/model/CreateApplicationRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tem/v20210701/model/CreateApplicationRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tem::V20210701::Model; using namespace std; CreateApplicationRequest::CreateApplicationRequest() : m_applicationNameHasBeenSet(false), m_descriptionHasBeenSet(false), m_useDefaultImageServiceHasBeenSet(false), m_repoTypeHasBeenSet(false), m_instanceIdHasBeenSet(false), m_repoServerHasBeenSet(false), m_repoNameHasBeenSet(false), m_sourceChannelHasBeenSet(false), m_subnetListHasBeenSet(false), m_codingLanguageHasBeenSet(false), m_deployModeHasBeenSet(false), m_enableTracingHasBeenSet(false) { } string CreateApplicationRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_applicationNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ApplicationName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_applicationName.c_str(), allocator).Move(), allocator); } if (m_descriptionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Description"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator); } if (m_useDefaultImageServiceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UseDefaultImageService"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_useDefaultImageService, allocator); } if (m_repoTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RepoType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_repoType, allocator); } if (m_instanceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator); } if (m_repoServerHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RepoServer"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_repoServer.c_str(), allocator).Move(), allocator); } if (m_repoNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RepoName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_repoName.c_str(), allocator).Move(), allocator); } if (m_sourceChannelHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SourceChannel"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_sourceChannel, allocator); } if (m_subnetListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SubnetList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_subnetList.begin(); itr != m_subnetList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_codingLanguageHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CodingLanguage"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_codingLanguage.c_str(), allocator).Move(), allocator); } if (m_deployModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeployMode"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_deployMode.c_str(), allocator).Move(), allocator); } if (m_enableTracingHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EnableTracing"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_enableTracing, allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateApplicationRequest::GetApplicationName() const { return m_applicationName; } void CreateApplicationRequest::SetApplicationName(const string& _applicationName) { m_applicationName = _applicationName; m_applicationNameHasBeenSet = true; } bool CreateApplicationRequest::ApplicationNameHasBeenSet() const { return m_applicationNameHasBeenSet; } string CreateApplicationRequest::GetDescription() const { return m_description; } void CreateApplicationRequest::SetDescription(const string& _description) { m_description = _description; m_descriptionHasBeenSet = true; } bool CreateApplicationRequest::DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } int64_t CreateApplicationRequest::GetUseDefaultImageService() const { return m_useDefaultImageService; } void CreateApplicationRequest::SetUseDefaultImageService(const int64_t& _useDefaultImageService) { m_useDefaultImageService = _useDefaultImageService; m_useDefaultImageServiceHasBeenSet = true; } bool CreateApplicationRequest::UseDefaultImageServiceHasBeenSet() const { return m_useDefaultImageServiceHasBeenSet; } int64_t CreateApplicationRequest::GetRepoType() const { return m_repoType; } void CreateApplicationRequest::SetRepoType(const int64_t& _repoType) { m_repoType = _repoType; m_repoTypeHasBeenSet = true; } bool CreateApplicationRequest::RepoTypeHasBeenSet() const { return m_repoTypeHasBeenSet; } string CreateApplicationRequest::GetInstanceId() const { return m_instanceId; } void CreateApplicationRequest::SetInstanceId(const string& _instanceId) { m_instanceId = _instanceId; m_instanceIdHasBeenSet = true; } bool CreateApplicationRequest::InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; } string CreateApplicationRequest::GetRepoServer() const { return m_repoServer; } void CreateApplicationRequest::SetRepoServer(const string& _repoServer) { m_repoServer = _repoServer; m_repoServerHasBeenSet = true; } bool CreateApplicationRequest::RepoServerHasBeenSet() const { return m_repoServerHasBeenSet; } string CreateApplicationRequest::GetRepoName() const { return m_repoName; } void CreateApplicationRequest::SetRepoName(const string& _repoName) { m_repoName = _repoName; m_repoNameHasBeenSet = true; } bool CreateApplicationRequest::RepoNameHasBeenSet() const { return m_repoNameHasBeenSet; } int64_t CreateApplicationRequest::GetSourceChannel() const { return m_sourceChannel; } void CreateApplicationRequest::SetSourceChannel(const int64_t& _sourceChannel) { m_sourceChannel = _sourceChannel; m_sourceChannelHasBeenSet = true; } bool CreateApplicationRequest::SourceChannelHasBeenSet() const { return m_sourceChannelHasBeenSet; } vector<string> CreateApplicationRequest::GetSubnetList() const { return m_subnetList; } void CreateApplicationRequest::SetSubnetList(const vector<string>& _subnetList) { m_subnetList = _subnetList; m_subnetListHasBeenSet = true; } bool CreateApplicationRequest::SubnetListHasBeenSet() const { return m_subnetListHasBeenSet; } string CreateApplicationRequest::GetCodingLanguage() const { return m_codingLanguage; } void CreateApplicationRequest::SetCodingLanguage(const string& _codingLanguage) { m_codingLanguage = _codingLanguage; m_codingLanguageHasBeenSet = true; } bool CreateApplicationRequest::CodingLanguageHasBeenSet() const { return m_codingLanguageHasBeenSet; } string CreateApplicationRequest::GetDeployMode() const { return m_deployMode; } void CreateApplicationRequest::SetDeployMode(const string& _deployMode) { m_deployMode = _deployMode; m_deployModeHasBeenSet = true; } bool CreateApplicationRequest::DeployModeHasBeenSet() const { return m_deployModeHasBeenSet; } int64_t CreateApplicationRequest::GetEnableTracing() const { return m_enableTracing; } void CreateApplicationRequest::SetEnableTracing(const int64_t& _enableTracing) { m_enableTracing = _enableTracing; m_enableTracingHasBeenSet = true; } bool CreateApplicationRequest::EnableTracingHasBeenSet() const { return m_enableTracingHasBeenSet; }
26.94
104
0.732103
[ "vector", "model" ]
8267ab44494cd158a1654855a28f71217e5452c1
24,589
cpp
C++
dbms/src/Dictionaries/CacheDictionary.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2017-01-17T17:29:05.000Z
2017-01-17T17:29:05.000Z
dbms/src/Dictionaries/CacheDictionary.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
dbms/src/Dictionaries/CacheDictionary.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
null
null
null
#include <DB/Columns/ColumnsNumber.h> #include <DB/Dictionaries/CacheDictionary.h> #include <DB/Common/BitHelpers.h> #include <DB/Common/randomSeed.h> #include <DB/Common/HashTable/Hash.h> namespace DB { namespace ErrorCodes { extern const int TYPE_MISMATCH; extern const int BAD_ARGUMENTS; extern const int UNSUPPORTED_METHOD; } inline UInt64 CacheDictionary::getCellIdx(const Key id) const { const auto hash = intHash64(id); const auto idx = hash & (size - 1); return idx; } CacheDictionary::CacheDictionary(const std::string & name, const DictionaryStructure & dict_struct, DictionarySourcePtr source_ptr, const DictionaryLifetime dict_lifetime, const std::size_t size) : name{name}, dict_struct(dict_struct), source_ptr{std::move(source_ptr)}, dict_lifetime(dict_lifetime), size{roundUpToPowerOfTwoOrZero(size)}, cells{this->size}, rnd_engine{randomSeed()} { if (!this->source_ptr->supportsSelectiveLoad()) throw Exception{ name + ": source cannot be used with CacheDictionary", ErrorCodes::UNSUPPORTED_METHOD}; createAttributes(); } CacheDictionary::CacheDictionary(const CacheDictionary & other) : CacheDictionary{other.name, other.dict_struct, other.source_ptr->clone(), other.dict_lifetime, other.size} {} void CacheDictionary::toParent(const PaddedPODArray<Key> & ids, PaddedPODArray<Key> & out) const { const auto null_value = std::get<UInt64>(hierarchical_attribute->null_values); getItemsNumber<UInt64>(*hierarchical_attribute, ids, out, [&] (const std::size_t) { return null_value; }); } #define DECLARE(TYPE)\ void CacheDictionary::get##TYPE(const std::string & attribute_name, const PaddedPODArray<Key> & ids, PaddedPODArray<TYPE> & out) const\ {\ auto & attribute = getAttribute(attribute_name);\ if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::TYPE))\ throw Exception{\ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type),\ ErrorCodes::TYPE_MISMATCH};\ \ const auto null_value = std::get<TYPE>(attribute.null_values);\ \ getItemsNumber<TYPE>(attribute, ids, out, [&] (const std::size_t) { return null_value; });\ } DECLARE(UInt8) DECLARE(UInt16) DECLARE(UInt32) DECLARE(UInt64) DECLARE(Int8) DECLARE(Int16) DECLARE(Int32) DECLARE(Int64) DECLARE(Float32) DECLARE(Float64) #undef DECLARE void CacheDictionary::getString(const std::string & attribute_name, const PaddedPODArray<Key> & ids, ColumnString * out) const { auto & attribute = getAttribute(attribute_name); if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::String)) throw Exception{ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type), ErrorCodes::TYPE_MISMATCH}; const auto null_value = StringRef{std::get<String>(attribute.null_values)}; getItemsString(attribute, ids, out, [&] (const std::size_t) { return null_value; }); } #define DECLARE(TYPE)\ void CacheDictionary::get##TYPE(\ const std::string & attribute_name, const PaddedPODArray<Key> & ids, const PaddedPODArray<TYPE> & def,\ PaddedPODArray<TYPE> & out) const\ {\ auto & attribute = getAttribute(attribute_name);\ if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::TYPE))\ throw Exception{\ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type),\ ErrorCodes::TYPE_MISMATCH};\ \ getItemsNumber<TYPE>(attribute, ids, out, [&] (const std::size_t row) { return def[row]; });\ } DECLARE(UInt8) DECLARE(UInt16) DECLARE(UInt32) DECLARE(UInt64) DECLARE(Int8) DECLARE(Int16) DECLARE(Int32) DECLARE(Int64) DECLARE(Float32) DECLARE(Float64) #undef DECLARE void CacheDictionary::getString( const std::string & attribute_name, const PaddedPODArray<Key> & ids, const ColumnString * const def, ColumnString * const out) const { auto & attribute = getAttribute(attribute_name); if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::String)) throw Exception{ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type), ErrorCodes::TYPE_MISMATCH}; getItemsString(attribute, ids, out, [&] (const std::size_t row) { return def->getDataAt(row); }); } #define DECLARE(TYPE)\ void CacheDictionary::get##TYPE(\ const std::string & attribute_name, const PaddedPODArray<Key> & ids, const TYPE def, PaddedPODArray<TYPE> & out) const\ {\ auto & attribute = getAttribute(attribute_name);\ if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::TYPE))\ throw Exception{\ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type),\ ErrorCodes::TYPE_MISMATCH};\ \ getItemsNumber<TYPE>(attribute, ids, out, [&] (const std::size_t) { return def; });\ } DECLARE(UInt8) DECLARE(UInt16) DECLARE(UInt32) DECLARE(UInt64) DECLARE(Int8) DECLARE(Int16) DECLARE(Int32) DECLARE(Int64) DECLARE(Float32) DECLARE(Float64) #undef DECLARE void CacheDictionary::getString( const std::string & attribute_name, const PaddedPODArray<Key> & ids, const String & def, ColumnString * const out) const { auto & attribute = getAttribute(attribute_name); if (!isAttributeTypeConvertibleTo(attribute.type, AttributeUnderlyingType::String)) throw Exception{ name + ": type mismatch: attribute " + attribute_name + " has type " + toString(attribute.type), ErrorCodes::TYPE_MISMATCH}; getItemsString(attribute, ids, out, [&] (const std::size_t) { return StringRef{def}; }); } void CacheDictionary::has(const PaddedPODArray<Key> & ids, PaddedPODArray<UInt8> & out) const { /// Mapping: <id> -> { all indices `i` of `ids` such that `ids[i]` = <id> } std::unordered_map<Key, std::vector<std::size_t>> outdated_ids; const auto rows = ext::size(ids); { const Poco::ScopedReadRWLock read_lock{rw_lock}; const auto now = std::chrono::system_clock::now(); /// fetch up-to-date values, decide which ones require update for (const auto row : ext::range(0, rows)) { const auto id = ids[row]; const auto cell_idx = getCellIdx(id); const auto & cell = cells[cell_idx]; /** cell should be updated if either: * 1. ids do not match, * 2. cell has expired, * 3. explicit defaults were specified and cell was set default. */ if (cell.id != id || cell.expiresAt() < now) outdated_ids[id].push_back(row); else out[row] = !cell.isDefault(); } } query_count.fetch_add(rows, std::memory_order_relaxed); hit_count.fetch_add(rows - outdated_ids.size(), std::memory_order_release); if (outdated_ids.empty()) return; std::vector<Key> required_ids(outdated_ids.size()); std::transform(std::begin(outdated_ids), std::end(outdated_ids), std::begin(required_ids), [] (auto & pair) { return pair.first; }); /// request new values update(required_ids, [&] (const auto id, const auto) { for (const auto row : outdated_ids[id]) out[row] = true; }, [&] (const auto id, const auto) { for (const auto row : outdated_ids[id]) out[row] = false; }); } void CacheDictionary::createAttributes() { const auto size = dict_struct.attributes.size(); attributes.reserve(size); bytes_allocated += size * sizeof(CellMetadata); bytes_allocated += size * sizeof(attributes.front()); for (const auto & attribute : dict_struct.attributes) { attribute_index_by_name.emplace(attribute.name, attributes.size()); attributes.push_back(createAttributeWithType(attribute.underlying_type, attribute.null_value)); if (attribute.hierarchical) { hierarchical_attribute = &attributes.back(); if (hierarchical_attribute->type != AttributeUnderlyingType::UInt64) throw Exception{ name + ": hierarchical attribute must be UInt64.", ErrorCodes::TYPE_MISMATCH}; } } } CacheDictionary::Attribute CacheDictionary::createAttributeWithType(const AttributeUnderlyingType type, const Field & null_value) { Attribute attr{type}; switch (type) { case AttributeUnderlyingType::UInt8: std::get<UInt8>(attr.null_values) = null_value.get<UInt64>(); std::get<ContainerPtrType<UInt8>>(attr.arrays) = std::make_unique<ContainerType<UInt8>>(size); bytes_allocated += size * sizeof(UInt8); break; case AttributeUnderlyingType::UInt16: std::get<UInt16>(attr.null_values) = null_value.get<UInt64>(); std::get<ContainerPtrType<UInt16>>(attr.arrays) = std::make_unique<ContainerType<UInt16>>(size); bytes_allocated += size * sizeof(UInt16); break; case AttributeUnderlyingType::UInt32: std::get<UInt32>(attr.null_values) = null_value.get<UInt64>(); std::get<ContainerPtrType<UInt32>>(attr.arrays) = std::make_unique<ContainerType<UInt32>>(size); bytes_allocated += size * sizeof(UInt32); break; case AttributeUnderlyingType::UInt64: std::get<UInt64>(attr.null_values) = null_value.get<UInt64>(); std::get<ContainerPtrType<UInt64>>(attr.arrays) = std::make_unique<ContainerType<UInt64>>(size); bytes_allocated += size * sizeof(UInt64); break; case AttributeUnderlyingType::Int8: std::get<Int8>(attr.null_values) = null_value.get<Int64>(); std::get<ContainerPtrType<Int8>>(attr.arrays) = std::make_unique<ContainerType<Int8>>(size); bytes_allocated += size * sizeof(Int8); break; case AttributeUnderlyingType::Int16: std::get<Int16>(attr.null_values) = null_value.get<Int64>(); std::get<ContainerPtrType<Int16>>(attr.arrays) = std::make_unique<ContainerType<Int16>>(size); bytes_allocated += size * sizeof(Int16); break; case AttributeUnderlyingType::Int32: std::get<Int32>(attr.null_values) = null_value.get<Int64>(); std::get<ContainerPtrType<Int32>>(attr.arrays) = std::make_unique<ContainerType<Int32>>(size); bytes_allocated += size * sizeof(Int32); break; case AttributeUnderlyingType::Int64: std::get<Int64>(attr.null_values) = null_value.get<Int64>(); std::get<ContainerPtrType<Int64>>(attr.arrays) = std::make_unique<ContainerType<Int64>>(size); bytes_allocated += size * sizeof(Int64); break; case AttributeUnderlyingType::Float32: std::get<Float32>(attr.null_values) = null_value.get<Float64>(); std::get<ContainerPtrType<Float32>>(attr.arrays) = std::make_unique<ContainerType<Float32>>(size); bytes_allocated += size * sizeof(Float32); break; case AttributeUnderlyingType::Float64: std::get<Float64>(attr.null_values) = null_value.get<Float64>(); std::get<ContainerPtrType<Float64>>(attr.arrays) = std::make_unique<ContainerType<Float64>>(size); bytes_allocated += size * sizeof(Float64); break; case AttributeUnderlyingType::String: std::get<String>(attr.null_values) = null_value.get<String>(); std::get<ContainerPtrType<StringRef>>(attr.arrays) = std::make_unique<ContainerType<StringRef>>(size); bytes_allocated += size * sizeof(StringRef); if (!string_arena) string_arena = std::make_unique<ArenaWithFreeLists>(); break; } return attr; } template <typename OutputType, typename DefaultGetter> void CacheDictionary::getItemsNumber( Attribute & attribute, const PaddedPODArray<Key> & ids, PaddedPODArray<OutputType> & out, DefaultGetter && get_default) const { if (false) {} #define DISPATCH(TYPE) \ else if (attribute.type == AttributeUnderlyingType::TYPE) \ getItemsNumberImpl<TYPE, OutputType>(attribute, ids, out, std::forward<DefaultGetter>(get_default)); DISPATCH(UInt8) DISPATCH(UInt16) DISPATCH(UInt32) DISPATCH(UInt64) DISPATCH(Int8) DISPATCH(Int16) DISPATCH(Int32) DISPATCH(Int64) DISPATCH(Float32) DISPATCH(Float64) #undef DISPATCH else throw Exception("Unexpected type of attribute: " + toString(attribute.type), ErrorCodes::LOGICAL_ERROR); } template <typename AttributeType, typename OutputType, typename DefaultGetter> void CacheDictionary::getItemsNumberImpl( Attribute & attribute, const PaddedPODArray<Key> & ids, PaddedPODArray<OutputType> & out, DefaultGetter && get_default) const { /// Mapping: <id> -> { all indices `i` of `ids` such that `ids[i]` = <id> } std::unordered_map<Key, std::vector<std::size_t>> outdated_ids; auto & attribute_array = std::get<ContainerPtrType<AttributeType>>(attribute.arrays); const auto rows = ext::size(ids); { const Poco::ScopedReadRWLock read_lock{rw_lock}; const auto now = std::chrono::system_clock::now(); /// fetch up-to-date values, decide which ones require update for (const auto row : ext::range(0, rows)) { const auto id = ids[row]; const auto cell_idx = getCellIdx(id); const auto & cell = cells[cell_idx]; /** cell should be updated if either: * 1. ids do not match, * 2. cell has expired, * 3. explicit defaults were specified and cell was set default. */ if (cell.id != id || cell.expiresAt() < now) outdated_ids[id].push_back(row); else out[row] = cell.isDefault() ? get_default(row) : attribute_array[cell_idx]; } } query_count.fetch_add(rows, std::memory_order_relaxed); hit_count.fetch_add(rows - outdated_ids.size(), std::memory_order_release); if (outdated_ids.empty()) return; std::vector<Key> required_ids(outdated_ids.size()); std::transform(std::begin(outdated_ids), std::end(outdated_ids), std::begin(required_ids), [] (auto & pair) { return pair.first; }); /// request new values update(required_ids, [&] (const auto id, const auto cell_idx) { const auto attribute_value = attribute_array[cell_idx]; for (const auto row : outdated_ids[id]) out[row] = attribute_value; }, [&] (const auto id, const auto cell_idx) { for (const auto row : outdated_ids[id]) out[row] = get_default(row); }); } template <typename DefaultGetter> void CacheDictionary::getItemsString( Attribute & attribute, const PaddedPODArray<Key> & ids, ColumnString * out, DefaultGetter && get_default) const { const auto rows = ext::size(ids); /// save on some allocations out->getOffsets().reserve(rows); auto & attribute_array = std::get<ContainerPtrType<StringRef>>(attribute.arrays); auto found_outdated_values = false; /// perform optimistic version, fallback to pessimistic if failed { const Poco::ScopedReadRWLock read_lock{rw_lock}; const auto now = std::chrono::system_clock::now(); /// fetch up-to-date values, discard on fail for (const auto row : ext::range(0, rows)) { const auto id = ids[row]; const auto cell_idx = getCellIdx(id); const auto & cell = cells[cell_idx]; if (cell.id != id || cell.expiresAt() < now) { found_outdated_values = true; break; } else { const auto string_ref = cell.isDefault() ? get_default(row) : attribute_array[cell_idx]; out->insertData(string_ref.data, string_ref.size); } } } /// optimistic code completed successfully if (!found_outdated_values) { query_count.fetch_add(rows, std::memory_order_relaxed); hit_count.fetch_add(rows, std::memory_order_release); return; } /// now onto the pessimistic one, discard possible partial results from the optimistic path out->getChars().resize_assume_reserved(0); out->getOffsets().resize_assume_reserved(0); /// Mapping: <id> -> { all indices `i` of `ids` such that `ids[i]` = <id> } std::unordered_map<Key, std::vector<std::size_t>> outdated_ids; /// we are going to store every string separately std::unordered_map<Key, String> map; std::size_t total_length = 0; { const Poco::ScopedReadRWLock read_lock{rw_lock}; const auto now = std::chrono::system_clock::now(); for (const auto row : ext::range(0, ids.size())) { const auto id = ids[row]; const auto cell_idx = getCellIdx(id); const auto & cell = cells[cell_idx]; if (cell.id != id || cell.expiresAt() < now) outdated_ids[id].push_back(row); else { const auto string_ref = cell.isDefault() ? get_default(row) : attribute_array[cell_idx]; if (!cell.isDefault()) map[id] = String{string_ref}; total_length += string_ref.size + 1; } } } query_count.fetch_add(rows, std::memory_order_relaxed); hit_count.fetch_add(rows - outdated_ids.size(), std::memory_order_release); /// request new values if (!outdated_ids.empty()) { std::vector<Key> required_ids(outdated_ids.size()); std::transform(std::begin(outdated_ids), std::end(outdated_ids), std::begin(required_ids), [] (auto & pair) { return pair.first; }); update(required_ids, [&] (const auto id, const auto cell_idx) { const auto attribute_value = attribute_array[cell_idx]; map[id] = String{attribute_value}; total_length += (attribute_value.size + 1) * outdated_ids[id].size(); }, [&] (const auto id, const auto cell_idx) { for (const auto row : outdated_ids[id]) total_length += get_default(row).size + 1; }); } out->getChars().reserve(total_length); for (const auto row : ext::range(0, ext::size(ids))) { const auto id = ids[row]; const auto it = map.find(id); const auto string_ref = it != std::end(map) ? StringRef{it->second} : get_default(row); out->insertData(string_ref.data, string_ref.size); } } template <typename PresentIdHandler, typename AbsentIdHandler> void CacheDictionary::update( const std::vector<Key> & requested_ids, PresentIdHandler && on_cell_updated, AbsentIdHandler && on_id_not_found) const { std::unordered_map<Key, UInt8> remaining_ids{requested_ids.size()}; for (const auto id : requested_ids) remaining_ids.insert({ id, 0 }); std::uniform_int_distribution<UInt64> distribution{ dict_lifetime.min_sec, dict_lifetime.max_sec }; const Poco::ScopedWriteRWLock write_lock{rw_lock}; auto stream = source_ptr->loadIds(requested_ids); stream->readPrefix(); while (const auto block = stream->read()) { const auto id_column = typeid_cast<const ColumnUInt64 *>(block.safeGetByPosition(0).column.get()); if (!id_column) throw Exception{ name + ": id column has type different from UInt64.", ErrorCodes::TYPE_MISMATCH}; const auto & ids = id_column->getData(); /// cache column pointers const auto column_ptrs = ext::map<std::vector>(ext::range(0, attributes.size()), [&block] (const auto & i) { return block.safeGetByPosition(i + 1).column.get(); }); for (const auto i : ext::range(0, ids.size())) { const auto id = ids[i]; const auto cell_idx = getCellIdx(id); auto & cell = cells[cell_idx]; for (const auto attribute_idx : ext::range(0, attributes.size())) { const auto & attribute_column = *column_ptrs[attribute_idx]; auto & attribute = attributes[attribute_idx]; setAttributeValue(attribute, cell_idx, attribute_column[i]); } /// if cell id is zero and zero does not map to this cell, then the cell is unused if (cell.id == 0 && cell_idx != zero_cell_idx) element_count.fetch_add(1, std::memory_order_relaxed); cell.id = id; if (dict_lifetime.min_sec != 0 && dict_lifetime.max_sec != 0) cell.setExpiresAt(std::chrono::system_clock::now() + std::chrono::seconds{distribution(rnd_engine)}); else cell.setExpiresAt(std::chrono::time_point<std::chrono::system_clock>::max()); /// inform caller on_cell_updated(id, cell_idx); /// mark corresponding id as found remaining_ids[id] = 1; } } stream->readSuffix(); /// Check which ids have not been found and require setting null_value for (const auto id_found_pair : remaining_ids) { if (id_found_pair.second) continue; const auto id = id_found_pair.first; const auto cell_idx = getCellIdx(id); auto & cell = cells[cell_idx]; /// Set null_value for each attribute for (auto & attribute : attributes) setDefaultAttributeValue(attribute, cell_idx); /// Check if cell had not been occupied before and increment element counter if it hadn't if (cell.id == 0 && cell_idx != zero_cell_idx) element_count.fetch_add(1, std::memory_order_relaxed); cell.id = id; if (dict_lifetime.min_sec != 0 && dict_lifetime.max_sec != 0) cell.setExpiresAt(std::chrono::system_clock::now() + std::chrono::seconds{distribution(rnd_engine)}); else cell.setExpiresAt(std::chrono::time_point<std::chrono::system_clock>::max()); cell.setDefault(); /// inform caller that the cell has not been found on_id_not_found(id, cell_idx); } } void CacheDictionary::setDefaultAttributeValue(Attribute & attribute, const Key idx) const { switch (attribute.type) { case AttributeUnderlyingType::UInt8: std::get<ContainerPtrType<UInt8>>(attribute.arrays)[idx] = std::get<UInt8>(attribute.null_values); break; case AttributeUnderlyingType::UInt16: std::get<ContainerPtrType<UInt16>>(attribute.arrays)[idx] = std::get<UInt16>(attribute.null_values); break; case AttributeUnderlyingType::UInt32: std::get<ContainerPtrType<UInt32>>(attribute.arrays)[idx] = std::get<UInt32>(attribute.null_values); break; case AttributeUnderlyingType::UInt64: std::get<ContainerPtrType<UInt64>>(attribute.arrays)[idx] = std::get<UInt64>(attribute.null_values); break; case AttributeUnderlyingType::Int8: std::get<ContainerPtrType<Int8>>(attribute.arrays)[idx] = std::get<Int8>(attribute.null_values); break; case AttributeUnderlyingType::Int16: std::get<ContainerPtrType<Int16>>(attribute.arrays)[idx] = std::get<Int16>(attribute.null_values); break; case AttributeUnderlyingType::Int32: std::get<ContainerPtrType<Int32>>(attribute.arrays)[idx] = std::get<Int32>(attribute.null_values); break; case AttributeUnderlyingType::Int64: std::get<ContainerPtrType<Int64>>(attribute.arrays)[idx] = std::get<Int64>(attribute.null_values); break; case AttributeUnderlyingType::Float32: std::get<ContainerPtrType<Float32>>(attribute.arrays)[idx] = std::get<Float32>(attribute.null_values); break; case AttributeUnderlyingType::Float64: std::get<ContainerPtrType<Float64>>(attribute.arrays)[idx] = std::get<Float64>(attribute.null_values); break; case AttributeUnderlyingType::String: { const auto & null_value_ref = std::get<String>(attribute.null_values); auto & string_ref = std::get<ContainerPtrType<StringRef>>(attribute.arrays)[idx]; if (string_ref.data != null_value_ref.data()) { if (string_ref.data) string_arena->free(const_cast<char *>(string_ref.data), string_ref.size); string_ref = StringRef{null_value_ref}; } break; } } } void CacheDictionary::setAttributeValue(Attribute & attribute, const Key idx, const Field & value) const { switch (attribute.type) { case AttributeUnderlyingType::UInt8: std::get<ContainerPtrType<UInt8>>(attribute.arrays)[idx] = value.get<UInt64>(); break; case AttributeUnderlyingType::UInt16: std::get<ContainerPtrType<UInt16>>(attribute.arrays)[idx] = value.get<UInt64>(); break; case AttributeUnderlyingType::UInt32: std::get<ContainerPtrType<UInt32>>(attribute.arrays)[idx] = value.get<UInt64>(); break; case AttributeUnderlyingType::UInt64: std::get<ContainerPtrType<UInt64>>(attribute.arrays)[idx] = value.get<UInt64>(); break; case AttributeUnderlyingType::Int8: std::get<ContainerPtrType<Int8>>(attribute.arrays)[idx] = value.get<Int64>(); break; case AttributeUnderlyingType::Int16: std::get<ContainerPtrType<Int16>>(attribute.arrays)[idx] = value.get<Int64>(); break; case AttributeUnderlyingType::Int32: std::get<ContainerPtrType<Int32>>(attribute.arrays)[idx] = value.get<Int64>(); break; case AttributeUnderlyingType::Int64: std::get<ContainerPtrType<Int64>>(attribute.arrays)[idx] = value.get<Int64>(); break; case AttributeUnderlyingType::Float32: std::get<ContainerPtrType<Float32>>(attribute.arrays)[idx] = value.get<Float64>(); break; case AttributeUnderlyingType::Float64: std::get<ContainerPtrType<Float64>>(attribute.arrays)[idx] = value.get<Float64>(); break; case AttributeUnderlyingType::String: { const auto & string = value.get<String>(); auto & string_ref = std::get<ContainerPtrType<StringRef>>(attribute.arrays)[idx]; const auto & null_value_ref = std::get<String>(attribute.null_values); /// free memory unless it points to a null_value if (string_ref.data && string_ref.data != null_value_ref.data()) string_arena->free(const_cast<char *>(string_ref.data), string_ref.size); const auto size = string.size(); if (size != 0) { auto string_ptr = string_arena->alloc(size + 1); std::copy(string.data(), string.data() + size + 1, string_ptr); string_ref = StringRef{string_ptr, size}; } else string_ref = {}; break; } } } CacheDictionary::Attribute & CacheDictionary::getAttribute(const std::string & attribute_name) const { const auto it = attribute_index_by_name.find(attribute_name); if (it == std::end(attribute_index_by_name)) throw Exception{ name + ": no such attribute '" + attribute_name + "'", ErrorCodes::BAD_ARGUMENTS }; return attributes[it->second]; } }
35.379856
150
0.722437
[ "vector", "transform" ]
826b4f7622e817bdda88a39b0a6c06aa4213d44c
7,992
cpp
C++
GVRf/Extensions/gvrf-physics/src/main/jni/engine/bullet/bullet_world.cpp
sidia-dev-team/GearVRf
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
[ "Apache-2.0" ]
474
2015-03-27T17:14:43.000Z
2022-03-30T23:10:38.000Z
GVRf/Extensions/gvrf-physics/src/main/jni/engine/bullet/bullet_world.cpp
sidia-dev-team/GearVRf
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
[ "Apache-2.0" ]
1,677
2015-03-28T02:00:21.000Z
2019-10-21T13:28:44.000Z
GVRf/Extensions/gvrf-physics/src/main/jni/engine/bullet/bullet_world.cpp
sidia-dev-team/GearVRf
d93d62d49e5fc5b55dc00a485db92ec8fe004db1
[ "Apache-2.0" ]
260
2015-03-27T23:55:12.000Z
2022-03-18T03:46:41.000Z
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "bullet_world.h" #include "bullet_rigidbody.h" #include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h> #include <BulletCollision/BroadphaseCollision/btDbvtBroadphase.h> #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h> #include <BulletDynamics/Dynamics/btDynamicsWorld.h> #include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h> #include <android/log.h> namespace gvr { BulletWorld::BulletWorld() { initialize(); } BulletWorld::~BulletWorld() { finalize(); } void BulletWorld::initialize() { // Default setup for memory, collision setup. mCollisionConfiguration = new btDefaultCollisionConfiguration(); /// Default collision dispatcher. mDispatcher = new btCollisionDispatcher(mCollisionConfiguration); ///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep. mOverlappingPairCache = new btDbvtBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) mSolver = new btSequentialImpulseConstraintSolver; mPhysicsWorld = new btDiscreteDynamicsWorld(mDispatcher, mOverlappingPairCache, mSolver, mCollisionConfiguration); mPhysicsWorld->setGravity(btVector3(0, -10, 0)); mDraggingConstraint = nullptr; } void BulletWorld::finalize() { for (int i = mPhysicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject *obj = mPhysicsWorld->getCollisionObjectArray()[i]; if (obj) { mPhysicsWorld->removeCollisionObject(obj); delete obj; } } if (nullptr != mDraggingConstraint) { delete mDraggingConstraint; } //delete dynamics world delete mPhysicsWorld; //delete solver delete mSolver; //delete broadphase delete mOverlappingPairCache; //delete dispatcher delete mDispatcher; delete mCollisionConfiguration; } void BulletWorld::addConstraint(PhysicsConstraint *constraint) { constraint->updateConstructionInfo(); btTypedConstraint *_constr = reinterpret_cast<btTypedConstraint*>(constraint->getUnderlying()); mPhysicsWorld->addConstraint(_constr); } void BulletWorld::removeConstraint(PhysicsConstraint *constraint) { mPhysicsWorld->removeConstraint(reinterpret_cast<btTypedConstraint*>(constraint->getUnderlying())); } void BulletWorld::startDrag(SceneObject *pivot_obj, PhysicsRigidBody *target, float relx, float rely, float relz) { btRigidBody *rb = reinterpret_cast<BulletRigidBody*>(target)->getRigidBody(); mActivationState = rb->getActivationState(); rb->setActivationState(DISABLE_DEACTIVATION); mDraggingConstraint = new btPoint2PointConstraint(*rb, btVector3(relx, rely, relz)); mPhysicsWorld->addConstraint(mDraggingConstraint, true); mDraggingConstraint->m_setting.m_impulseClamp = 30.f; mDraggingConstraint->m_setting.m_tau = 0.001f; mPivotObject = pivot_obj; } void BulletWorld::stopDrag() { btRigidBody *rb = &mDraggingConstraint->getRigidBodyA(); rb->forceActivationState(mActivationState); rb->activate(); mPhysicsWorld->removeConstraint(mDraggingConstraint); delete mDraggingConstraint; mDraggingConstraint = nullptr; } void BulletWorld::addRigidBody(PhysicsRigidBody *body) { btRigidBody *b = (static_cast<BulletRigidBody *>(body))->getRigidBody(); body->updateConstructionInfo(); mPhysicsWorld->addRigidBody(b); } void BulletWorld::addRigidBody(PhysicsRigidBody *body, int collisiontype, int collidesWith) { body->updateConstructionInfo(); mPhysicsWorld->addRigidBody((static_cast<BulletRigidBody *>(body))->getRigidBody(), collidesWith, collisiontype); } void BulletWorld::removeRigidBody(PhysicsRigidBody *body) { mPhysicsWorld->removeRigidBody((static_cast<BulletRigidBody *>(body))->getRigidBody()); } void BulletWorld::step(float timeStep, int maxSubSteps) { if (mDraggingConstraint != nullptr) { auto matrixB = mPivotObject->transform()->getModelMatrix(true); mDraggingConstraint->setPivotB(btVector3(matrixB[3][0], matrixB[3][1], matrixB[3][2])); } mPhysicsWorld->stepSimulation(timeStep, maxSubSteps); } /** * Returns by reference the list of new and ceased collisions * that will be the objects of ONENTER and ONEXIT events. */ void BulletWorld::listCollisions(std::list <ContactPoint> &contactPoints) { /* * Creates a list of all the current collisions on the World * */ std::map<std::pair<long,long>, ContactPoint> currCollisions; int numManifolds = mPhysicsWorld->getDispatcher()->getNumManifolds(); btPersistentManifold *contactManifold; for (int i = 0; i < numManifolds; i++) { ContactPoint contactPt; contactManifold = mPhysicsWorld->getDispatcher()-> getManifoldByIndexInternal(i); contactPt.body0 = (BulletRigidBody *) (contactManifold->getBody0()->getUserPointer()); contactPt.body1 = (BulletRigidBody *) (contactManifold->getBody1()->getUserPointer()); contactPt.normal[0] = contactManifold->getContactPoint(0).m_normalWorldOnB.getX(); contactPt.normal[1] = contactManifold->getContactPoint(0).m_normalWorldOnB.getY(); contactPt.normal[2] = contactManifold->getContactPoint(0).m_normalWorldOnB.getZ(); contactPt.distance = contactManifold->getContactPoint(0).getDistance(); contactPt.isHit = true; std::pair<long, long> collisionPair((long)contactPt.body0, (long)contactPt.body1); std::pair<std::pair<long, long>, ContactPoint> newPair(collisionPair, contactPt); currCollisions.insert(newPair); /* * If one of these current collisions is not on the list with all the previous * collision, then it should be on the return list, because it is an onEnter event * */ auto it = prevCollisions.find(collisionPair); if ( it == prevCollisions.end()) { contactPoints.push_front(contactPt); } contactManifold = 0; } /* * After going through all the current list, go through all the previous collisions list, * if one of its collisions is not on the current collision list, then it should be * on the return list, because it is an onExit event * */ for (auto it = prevCollisions.begin(); it != prevCollisions.end(); ++it) { if (currCollisions.find(it->first) == currCollisions.end()) { ContactPoint cp = it->second; cp.isHit = false; contactPoints.push_front(cp); } } /* * Save all the current collisions on the previous collisions list for the next iteration * */ prevCollisions.clear(); prevCollisions.swap(currCollisions); } void BulletWorld::setGravity(float x, float y, float z) { mPhysicsWorld->setGravity(btVector3(x, y, z)); } void BulletWorld::setGravity(glm::vec3 gravity) { mPhysicsWorld->setGravity(btVector3(gravity.x, gravity.y, gravity.z)); } PhysicsVec3 BulletWorld::getGravity() const { btVector3 g = mPhysicsWorld->getGravity(); PhysicsVec3 gravity; gravity.x = g.getX(); gravity.y = g.getY(); gravity.z = g.getZ(); return gravity; } }
34.153846
125
0.706456
[ "transform" ]
826f469dd8dbe039e64af0cc41650f3a87350cf0
12,421
cc
C++
test/test_script.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
test/test_script.cc
pekdon/plux
74d7dd1e4bd57dda0b2a3754e77af068205dabe1
[ "MIT" ]
null
null
null
#include <iostream> #include "test.hh" #include "script.hh" #include "script_run.hh" /** * ShellCtx user for testing. */ class ShellCtxTest : public plux::ShellCtx { public: ShellCtxTest() : _name("my-shell"), _timeout_ms(-1) { } virtual ~ShellCtxTest() { } virtual const std::string& name() const override { return _name; } void set_name(const std::string& name) { _name = name; } unsigned int timeout() const override { return _timeout_ms; } virtual void set_timeout(unsigned int timeout_ms) override { _timeout_ms = timeout_ms; } virtual void set_error_pattern(const std::string& pattern) override { _error_pattern = pattern; } std::vector<std::string>& input() { return _input; } virtual bool input(const std::string& data) override { _input.push_back(data); return true; } virtual void output(const char* data, ssize_t size) override { } virtual line_it line_begin() override { return _lines.begin(); } virtual line_it line_end() override { return _lines.end(); } virtual void line_consume_until(line_it it) override { } virtual const std::string& buf() const override { return plux::empty_string; } virtual void consume_buf() override { } private: std::string _name; unsigned int _timeout_ms; std::string _error_pattern; plux::ShellCtx::line_vector _lines; std::vector<std::string> _input; }; class TestLine : public plux::Line, public TestSuite { public: TestLine() : Line(":memory:", 0, ""), TestSuite("Line") { register_test("expand_var", std::bind(&TestLine::test_expand_var, this)); } virtual ~TestLine() { } virtual plux::LineRes run(plux::ShellCtx& ctx, plux::ShellEnv& env) { return plux::RES_ERROR; } void test_expand_var() { plux::env_map os_env; plux::ScriptEnv env(os_env); env.set_env("", "WHERE", plux::VAR_SCOPE_GLOBAL, "world"); env.set_env("", "with space", plux::VAR_SCOPE_GLOBAL, "planet"); env.set_env("", "glob1", plux::VAR_SCOPE_GLOBAL, "value"); ASSERT_EQUAL("expand_var, no var", "test", expand_var(env, "shell", "test")); ASSERT_EQUAL("expand_var, var", "hello world", expand_var(env, "shell", "hello $WHERE")); ASSERT_EQUAL("expand_var, curly var", "hello planet", expand_var(env, "shell", "hello ${with space}")); ASSERT_EQUAL("expand_var, ==", "==value==", expand_var(env, "shell", "==$glob1==")); try { expand_var(env, "shell", "invalid $ is empty"); ASSERT_EQUAL("expand_var, empty", false, true); } catch (plux::ScriptError& ex) { ASSERT_EQUAL("expand_var, empty", "empty variable name", ex.error()); } try { expand_var(env, "shell", "my ${} var"); ASSERT_EQUAL("expand_var, curly empty", false, true); } catch (plux::ScriptError& ex) { ASSERT_EQUAL("expand_var, curly empty", "empty variable name", ex.error()); } try { expand_var(env, "shell", "end ${end"); ASSERT_EQUAL("expand_var, curly incomplete", false, true); } catch (plux::ScriptError& ex) { ASSERT_EQUAL("expand_var, curly incomplete", "end of line while scanning for }", ex.error()); } ASSERT_EQUAL("expand_var, skip end $", "^complete$", expand_var(env, "shell", "^complete$")); ASSERT_EQUAL("expand_var, multi", "hello planet and world", expand_var(env, "shell", "hello ${with space} and $WHERE")); } virtual std::string to_string() const { return "TestLine"; } }; class TestHeaderConfigRequire : public plux::HeaderConfigRequire, public TestSuite { public: TestHeaderConfigRequire() : plux::HeaderConfigRequire(":memory:", 0, "key", ""), TestSuite("HeaderConfigRequire") { register_test("run", std::bind(&TestHeaderConfigRequire::test_run, this)); } virtual ~TestHeaderConfigRequire() { } void test_run() { ShellCtxTest ctx; plux::env_map os_env; plux::ScriptEnv env(os_env); ASSERT_EQUAL("run", plux::RES_ERROR, run(ctx, env).status()); env.set_env("", "key", plux::VAR_SCOPE_GLOBAL, "any"); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); env.set_env("", "key", plux::VAR_SCOPE_GLOBAL, "value"); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); set_val("value"); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); env.set_env("", "key", plux::VAR_SCOPE_GLOBAL, "any"); ASSERT_EQUAL("run", plux::RES_ERROR, run(ctx, env).status()); } }; class TestScriptLine : public plux::Line, public TestSuite { public: TestScriptLine() : plux::Line(":memory:", 0, ""), TestSuite("ScriptLine") { } virtual ~TestScriptLine() { } virtual std::string to_string() const override { return "TestScriptLine"; } virtual plux::LineRes run(plux::ShellCtx& ctx, plux::ShellEnv& env) override { return plux::RES_ERROR; } }; class TestLineVarAssignGlobal : public plux::LineVarAssignGlobal, public TestSuite { public: TestLineVarAssignGlobal() : plux::LineVarAssignGlobal(":memory:", 0, "", "key", "global-val"), TestSuite("LineVarAssignGlobal") { register_test("run", std::bind(&TestLineVarAssignGlobal::test_run, this)); } virtual ~TestLineVarAssignGlobal() { } void test_run() { ShellCtxTest ctx; plux::env_map os_env; plux::ScriptEnv env(os_env); std::string val; ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); ASSERT_EQUAL("run", true, env.get_env("", "key", val)); ASSERT_EQUAL("run", "global-val", val); } }; class TestLineVarAssignShell : public plux::LineVarAssignShell, public TestSuite { public: TestLineVarAssignShell() : plux::LineVarAssignShell(":memory:", 0, "shell", "key", "local-val"), TestSuite("LineVarAssignShell") { register_test("run", std::bind(&TestLineVarAssignShell::test_run, this)); } ~TestLineVarAssignShell() { } void test_run() { ShellCtxTest ctx; plux::env_map os_env; plux::ScriptEnv env(os_env); std::string val; ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); ASSERT_EQUAL("run", true, env.get_env("my-shell", "key", val)); ASSERT_EQUAL("run", "local-val", val); ASSERT_EQUAL("run", false, env.get_env("my-shell-2", "key", val)); } }; class TestLineOutput : public plux::LineOutput, public TestSuite { public: TestLineOutput() : plux::LineOutput(":memory:", 0, "shell", "not-used"), TestSuite("LineOutput") { register_test("run", std::bind(&TestLineOutput::test_run, this)); } virtual ~TestLineOutput() { } void test_run() { ShellCtxTest ctx; plux::env_map os_env; plux::ScriptEnv env(os_env); env.set_env("", "glob1", plux::VAR_SCOPE_GLOBAL, "value"); set_output("plain\n"); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); ASSERT_EQUAL("run", 1, ctx.input().size()); ASSERT_EQUAL("run", "plain\n", ctx.input()[0]); set_output("echo ==$glob1==\n"); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); ASSERT_EQUAL("run", 2, ctx.input().size()); ASSERT_EQUAL("run", "echo ==value==\n", ctx.input()[1]); } }; class TestLineVarMatch : public plux::LineVarMatch, public TestSuite { public: TestLineVarMatch() : plux::LineVarMatch(":memory:", 0, "shell", "not-used"), TestSuite("LineVarMatch") { register_test("match", std::bind(&TestLineVarMatch::test_match, this)); } virtual ~TestLineVarMatch() { } void test_match() { plux::env_map os_env; plux::ScriptEnv env(os_env); env.set_env("", "VALUE", plux::VAR_SCOPE_GLOBAL, "world"); set_pattern("SH-PROMPT:"); ASSERT_EQUAL("match", true, match(env, "shell", "SH-PROMPT:", true)); set_pattern("hello $VALUE"); ASSERT_EQUAL("match var", true, match(env, "shell", "hello world", true)); ASSERT_EQUAL("match var", false, match(env, "shell", "hello planet", true)); } }; class TestLineRegexMatch : public plux::LineRegexMatch, public TestSuite { public: TestLineRegexMatch() : plux::LineRegexMatch(":memory:", 0, "shell", "not-used"), TestSuite("LineRegexMatch") { register_test("match", std::bind(&TestLineRegexMatch::test_match, this)); } virtual ~TestLineRegexMatch() { } void test_match() { plux::env_map os_env; plux::ScriptEnv env(os_env); set_pattern("SH-PROMPT:"); ASSERT_EQUAL("match full", true, match(env, "shell", "SH-PROMPT:", true)); ASSERT_EQUAL("match full", true, match(env, "shell", "SH-PROMPT:", false)); set_pattern("partial"); ASSERT_EQUAL("match partial", true, match(env, "shell", "1partial2", true)); ASSERT_EQUAL("match partial", true, match(env, "shell", "1partial2", false)); set_pattern("^complete$"); ASSERT_EQUAL("match anchor", true, match(env, "shell", "complete", true)); ASSERT_EQUAL("match anchor", false, match(env, "shell", "complete", false)); ASSERT_EQUAL("match anchor", false, match(env, "shell", "complete and more", true)); ASSERT_EQUAL("match anchor", false, match(env, "shell", "more and complete", true)); set_pattern("[0-K"); try { match(env, "shell", "some input", true); ASSERT_EQUAL("invalid", false, true); } catch (plux::ScriptError& ex) { ASSERT_EQUAL("invalid", "regex failed: ", ex.error().substr(0, 14)); } set_pattern("hello ([a-z]+) and ([0-9]+)!"); ASSERT_EQUAL("extract group", true, match(env, "shell", "hello world and 2021!", true)); std::string val; ASSERT_EQUAL("extract group", true, env.get_env("shell", "1", val)); ASSERT_EQUAL("extract group", "world", val); ASSERT_EQUAL("extract group", true, env.get_env("shell", "2", val)); ASSERT_EQUAL("extract group", "2021", val); } }; class TestLineTimeout : public plux::LineTimeout, public TestSuite { public: TestLineTimeout() : plux::LineTimeout(":memory", 0, "shell", 1000), TestSuite("LineTimeout") { register_test("run", std::bind(&TestLineTimeout::test_run, this)); } virtual ~TestLineTimeout() { } void test_run() { ShellCtxTest ctx; plux::env_map os_env; plux::ScriptEnv env(os_env); ASSERT_EQUAL("run", plux::RES_OK, run(ctx, env).status()); ASSERT_EQUAL("run", _timeout_ms, ctx.timeout()); } }; int main(int argc, char *argv[]) { TestLine test_line; TestHeaderConfigRequire test_header_config_require; TestScriptLine test_script_line; TestLineVarAssignGlobal test_assign_global; TestLineVarAssignShell test_assign_shell; TestLineOutput test_output; TestLineVarMatch test_var_match; TestLineRegexMatch test_re_match; TestLineTimeout test_timeout; try { return TestSuite::main(argc, argv); } catch (plux::PluxException &ex) { std::cerr << ex.to_string() << std::endl; return 1; } }
31.686224
79
0.565091
[ "vector" ]
82785dc608e38be2d1116f68792218199f460734
7,581
cc
C++
gpu-simulator/gpgpu-sim/src/gpgpu-sim/icnt_wrapper.cc
tgrogers/accel-sim-framework
ea3d64183bc5d9ff41963ba89a051e0871f243ca
[ "BSD-2-Clause" ]
null
null
null
gpu-simulator/gpgpu-sim/src/gpgpu-sim/icnt_wrapper.cc
tgrogers/accel-sim-framework
ea3d64183bc5d9ff41963ba89a051e0871f243ca
[ "BSD-2-Clause" ]
null
null
null
gpu-simulator/gpgpu-sim/src/gpgpu-sim/icnt_wrapper.cc
tgrogers/accel-sim-framework
ea3d64183bc5d9ff41963ba89a051e0871f243ca
[ "BSD-2-Clause" ]
4
2021-04-24T00:08:23.000Z
2021-05-13T06:30:21.000Z
// Copyright (c) 2009-2011, Tor M. Aamodt, Wilson W.L. Fung, Ali Bakhoda // The University of British Columbia // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. Neither the name of // The University of British Columbia nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "icnt_wrapper.h" #include <assert.h> #include "../intersim2/globals.hpp" #include "../intersim2/interconnect_interface.hpp" #include "local_interconnect.h" icnt_create_p icnt_create; icnt_init_p icnt_init; icnt_has_buffer_p icnt_has_buffer; icnt_push_p icnt_push; icnt_pop_p icnt_pop; icnt_transfer_p icnt_transfer; icnt_busy_p icnt_busy; icnt_display_stats_p icnt_display_stats; icnt_display_overall_stats_p icnt_display_overall_stats; icnt_display_state_p icnt_display_state; icnt_get_flit_size_p icnt_get_flit_size; unsigned g_network_mode; char* g_network_config_filename; struct inct_config g_inct_config; LocalInterconnect* g_localicnt_interface; #include "../option_parser.h" // Wrapper to intersim2 to accompany old icnt_wrapper // TODO: use delegate/boost/c++11<funtion> instead static void intersim2_create(unsigned int n_shader, unsigned int n_mem) { g_icnt_interface->CreateInterconnect(n_shader, n_mem); } static void intersim2_init() { g_icnt_interface->Init(); } static bool intersim2_has_buffer(unsigned input, unsigned int size) { return g_icnt_interface->HasBuffer(input, size); } static void intersim2_push(unsigned input, unsigned output, void* data, unsigned int size) { g_icnt_interface->Push(input, output, data, size); } static void* intersim2_pop(unsigned output) { return g_icnt_interface->Pop(output); } static void intersim2_transfer() { g_icnt_interface->Advance(); } static bool intersim2_busy() { return g_icnt_interface->Busy(); } static void intersim2_display_stats() { g_icnt_interface->DisplayStats(); } static void intersim2_display_overall_stats() { g_icnt_interface->DisplayOverallStats(); } static void intersim2_display_state(FILE* fp) { g_icnt_interface->DisplayState(fp); } static unsigned intersim2_get_flit_size() { return g_icnt_interface->GetFlitSize(); } ////////////////////////////////////////////////////// static void LocalInterconnect_create(unsigned int n_shader, unsigned int n_mem) { g_localicnt_interface->CreateInterconnect(n_shader, n_mem); } static void LocalInterconnect_init() { g_localicnt_interface->Init(); } static bool LocalInterconnect_has_buffer(unsigned input, unsigned int size) { return g_localicnt_interface->HasBuffer(input, size); } static void LocalInterconnect_push(unsigned input, unsigned output, void* data, unsigned int size) { g_localicnt_interface->Push(input, output, data, size); } static void* LocalInterconnect_pop(unsigned output) { return g_localicnt_interface->Pop(output); } static void LocalInterconnect_transfer() { g_localicnt_interface->Advance(); } static bool LocalInterconnect_busy() { return g_localicnt_interface->Busy(); } static void LocalInterconnect_display_stats() { g_localicnt_interface->DisplayStats(); } static void LocalInterconnect_display_overall_stats() { g_localicnt_interface->DisplayOverallStats(); } static void LocalInterconnect_display_state(FILE* fp) { g_localicnt_interface->DisplayState(fp); } static unsigned LocalInterconnect_get_flit_size() { return g_localicnt_interface->GetFlitSize(); } /////////////////////////// void icnt_reg_options(class OptionParser* opp) { option_parser_register(opp, "-network_mode", OPT_INT32, &g_network_mode, "Interconnection network mode", "1"); option_parser_register(opp, "-inter_config_file", OPT_CSTR, &g_network_config_filename, "Interconnection network config file", "mesh"); // parameters for local xbar option_parser_register(opp, "-icnt_in_buffer_limit", OPT_UINT32, &g_inct_config.in_buffer_limit, "in_buffer_limit", "64"); option_parser_register(opp, "-icnt_out_buffer_limit", OPT_UINT32, &g_inct_config.out_buffer_limit, "out_buffer_limit", "64"); option_parser_register(opp, "-icnt_subnets", OPT_UINT32, &g_inct_config.subnets, "subnets", "2"); option_parser_register(opp, "-icnt_arbiter_algo", OPT_UINT32, &g_inct_config.arbiter_algo, "arbiter_algo", "1"); option_parser_register(opp, "-icnt_verbose", OPT_UINT32, &g_inct_config.verbose, "inct_verbose", "0"); option_parser_register(opp, "-icnt_grant_cycles", OPT_UINT32, &g_inct_config.grant_cycles, "grant_cycles", "1"); } void icnt_wrapper_init() { switch (g_network_mode) { case INTERSIM: // FIXME: delete the object: may add icnt_done wrapper g_icnt_interface = InterconnectInterface::New(g_network_config_filename); icnt_create = intersim2_create; icnt_init = intersim2_init; icnt_has_buffer = intersim2_has_buffer; icnt_push = intersim2_push; icnt_pop = intersim2_pop; icnt_transfer = intersim2_transfer; icnt_busy = intersim2_busy; icnt_display_stats = intersim2_display_stats; icnt_display_overall_stats = intersim2_display_overall_stats; icnt_display_state = intersim2_display_state; icnt_get_flit_size = intersim2_get_flit_size; break; case LOCAL_XBAR: g_localicnt_interface = LocalInterconnect::New(g_inct_config); icnt_create = LocalInterconnect_create; icnt_init = LocalInterconnect_init; icnt_has_buffer = LocalInterconnect_has_buffer; icnt_push = LocalInterconnect_push; icnt_pop = LocalInterconnect_pop; icnt_transfer = LocalInterconnect_transfer; icnt_busy = LocalInterconnect_busy; icnt_display_stats = LocalInterconnect_display_stats; icnt_display_overall_stats = LocalInterconnect_display_overall_stats; icnt_display_state = LocalInterconnect_display_state; icnt_get_flit_size = LocalInterconnect_get_flit_size; break; default: assert(0); break; } }
38.095477
79
0.736314
[ "mesh", "object" ]
827887499a595853c7d85253697c5ccc17d3c0a7
3,371
cc
C++
src/Core/Datatypes/Tests/ScalarTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
92
2015-02-09T22:42:11.000Z
2022-03-25T09:14:50.000Z
src/Core/Datatypes/Tests/ScalarTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
1,618
2015-01-05T19:39:13.000Z
2022-03-27T20:28:45.000Z
src/Core/Datatypes/Tests/ScalarTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
64
2015-02-20T17:51:23.000Z
2021-11-19T07:08:08.000Z
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Core/Datatypes/Color.h> #include <complex> #include <Core/GeometryPrimitives/Tensor.h> #include <Core/GeometryPrimitives/Vector.h> #include <Core/GeometryPrimitives/Point.h> using ::testing::_; using ::testing::NiceMock; using ::testing::DefaultValue; using ::testing::Return; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Geometry; TEST(ColorTests, CanParseString) { ColorRGB c(1.0,2.0,3.0); const std::string expected = "Color(1,2,3)"; EXPECT_EQ(expected, c.toString()); ColorRGB c2(expected); EXPECT_EQ(c, c2); } TEST(ColorTests, CanParseStringFloating) { ColorRGB c(1.3,2.9,3.00014); const std::string expected = "Color(1.3,2.9,3.00014)"; EXPECT_EQ(expected, c.toString()); ColorRGB c2(expected); EXPECT_EQ(c, c2); } TEST(ColorTests, EmptyStringYieldsWhite) { ColorRGB c(1.0,1.0,1.0); ColorRGB c2(""); EXPECT_EQ(c, c2); } TEST(ColorTests, CanParseHexValue) { ColorRGB c(0x27213cu); ColorRGB c2(39/255.0, 33/255.0, 60/255.0); EXPECT_EQ(c, c2); } TEST(BasicDatatypeIOTests, AssertSizesOfFieldDatatypesAreConsistent) { ASSERT_EQ(1, sizeof(char)); ASSERT_EQ(1, sizeof(unsigned char)); ASSERT_EQ(2, sizeof(short)); ASSERT_EQ(2, sizeof(unsigned short)); ASSERT_EQ(4, sizeof(int)); ASSERT_EQ(4, sizeof(unsigned int)); ASSERT_EQ(8, sizeof(long long)); ASSERT_EQ(8, sizeof(unsigned long long)); ASSERT_EQ(4, sizeof(float)); ASSERT_EQ(8, sizeof(double)); ASSERT_EQ(2 * sizeof(double), sizeof(std::complex<double>)); ASSERT_EQ(3 * sizeof(double), sizeof(Vector)); ASSERT_EQ(3 * sizeof(double), sizeof(Point)); ASSERT_EQ( 3 * 3 * sizeof(double) + // matrix data 3 * sizeof(Vector) + // eigenvectors 3 * sizeof(double) + // eigenvalues sizeof(int) + // eigens computed flag (must stay int, not bool) 4, // to get to 8-byte packing sizeof(Tensor)); } TEST(BasicDatatypeIOTests, AssertSizesOfSizeTypesAreConsistent) { ASSERT_EQ(8, sizeof(SCIRun::size_type)); ASSERT_EQ(8, sizeof(SCIRun::index_type)); }
32.104762
79
0.716701
[ "geometry", "vector" ]
827b3853580f2dbe2c1d445e5bb2f3f53a017204
1,785
cpp
C++
Src/Source/ColourView.cpp
HaikuArchives/BeTeX
6df0643ff8f16be083c11abb7ce20a7b06ee43eb
[ "MIT" ]
5
2016-11-09T21:27:22.000Z
2021-09-17T09:58:42.000Z
Src/Source/ColourView.cpp
HaikuArchives/BeTeX
6df0643ff8f16be083c11abb7ce20a7b06ee43eb
[ "MIT" ]
17
2018-10-30T15:01:55.000Z
2021-11-05T19:16:59.000Z
Src/Source/ColourView.cpp
HaikuArchives/BeTeX
6df0643ff8f16be083c11abb7ce20a7b06ee43eb
[ "MIT" ]
3
2016-11-09T21:27:37.000Z
2020-10-25T17:33:07.000Z
/***************************************************************** * Copyright (c) 2005 Tim de Jong, Brent Miszalski * * * * All rights reserved. * * Distributed under the terms of the MIT License. * *****************************************************************/ #ifndef COLOUR_VIEW_H #include "ColourView.h" #endif #include <be/interface/Point.h> ColourView::ColourView(BRect frame) : BView(frame,"colorView",B_FOLLOW_NONE,B_WILL_DRAW) { m_bitmap = new BBitmap(Bounds(),B_RGB32,true); m_bitmap->Lock(); m_bitmapView = new BView(Bounds(),"view",B_FOLLOW_NONE, B_WILL_DRAW); m_bitmap->AddChild(m_bitmapView); m_bitmap->Unlock(); } ColourView::~ColourView() { // delete bitmap; // delete bView; } void ColourView::SetColor(rgb_color colour) { m_colour = colour; } void ColourView::Draw(BRect drawRect) { Render(); } void ColourView::Render() { m_bitmap->Lock(); BRect bitmapBounds = m_bitmap->Bounds(); m_bitmapView->SetHighColor(m_colour); m_bitmapView->FillRect(bitmapBounds); m_bitmapView->SetHighColor(tint_color(m_colour,B_LIGHTEN_2_TINT)); m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.top), BPoint(bitmapBounds.left,bitmapBounds.bottom)); m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.top), BPoint(bitmapBounds.right,bitmapBounds.top)); m_bitmapView->SetHighColor(tint_color(m_colour,B_DARKEN_2_TINT)); m_bitmapView->StrokeLine(BPoint(bitmapBounds.left,bitmapBounds.bottom), BPoint(bitmapBounds.right,bitmapBounds.bottom)); m_bitmapView->StrokeLine(BPoint(bitmapBounds.right,bitmapBounds.top), BPoint(bitmapBounds.right,bitmapBounds.bottom)); m_bitmapView->Sync(); DrawBitmapAsync(m_bitmap, Bounds(), Bounds()); Flush(); Sync(); m_bitmap->Unlock(); }
29.75
121
0.684594
[ "render" ]
827caa5442d367c1904bbcc7f8d217927c2b8c4d
6,120
cpp
C++
src/EndpointUser.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/EndpointUser.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/EndpointUser.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include "EndpointUser.hpp" #include <unistd.h> #include <fstream> #include "EndpointImp.hpp" // for shmem region structs and constants #include "geopm/Helper.hpp" #include "Agent.hpp" #include "Environment.hpp" #include "geopm/SharedMemory.hpp" #include "config.h" namespace geopm { std::unique_ptr<EndpointUser> EndpointUser::make_unique(const std::string &policy_path, const std::set<std::string> &hosts) { return geopm::make_unique<EndpointUserImp>(policy_path, hosts); } EndpointUserImp::EndpointUserImp(const std::string &data_path, const std::set<std::string> &hosts) : EndpointUserImp(data_path, nullptr, nullptr, environment().agent(), Agent::num_sample(environment().agent()), environment().profile(), "", hosts) { } EndpointUserImp::EndpointUserImp(const std::string &data_path, std::unique_ptr<SharedMemory> policy_shmem, std::unique_ptr<SharedMemory> sample_shmem, const std::string &agent_name, int num_sample, const std::string &profile_name, const std::string &hostlist_path, const std::set<std::string> &hosts) : m_path(data_path) , m_policy_shmem(std::move(policy_shmem)) , m_sample_shmem(std::move(sample_shmem)) , m_num_sample(num_sample) { // Attach to shared memory here and send across agent, // profile, hostname list. Once user attaches to sample // shmem, RM knows it has attached to both policy and sample. if (m_policy_shmem == nullptr) { m_policy_shmem = SharedMemory::make_unique_user(m_path + EndpointImp::shm_policy_postfix(), environment().timeout()); } if (m_sample_shmem == nullptr) { m_sample_shmem = SharedMemory::make_unique_user(m_path + EndpointImp::shm_sample_postfix(), environment().timeout()); } auto lock = m_sample_shmem->get_scoped_lock(); auto data = (struct geopm_endpoint_sample_shmem_s *)m_sample_shmem->pointer(); if (agent_name.size() >= GEOPM_ENDPOINT_AGENT_NAME_MAX) { throw Exception("EndpointImp(): Agent name is too long for endpoint storage: " + agent_name, GEOPM_ERROR_INVALID, __FILE__, __LINE__); } if (profile_name.size() >= GEOPM_ENDPOINT_PROFILE_NAME_MAX) { throw Exception("EndpointImp(): Profile name is too long for endpoint storage: " + profile_name, GEOPM_ERROR_INVALID, __FILE__, __LINE__); } data->agent[GEOPM_ENDPOINT_AGENT_NAME_MAX - 1] = '\0'; data->profile_name[GEOPM_ENDPOINT_PROFILE_NAME_MAX - 1] = '\0'; strncpy(data->agent, agent_name.c_str(), GEOPM_ENDPOINT_AGENT_NAME_MAX - 1); strncpy(data->profile_name, profile_name.c_str(), GEOPM_ENDPOINT_PROFILE_NAME_MAX - 1); /// write hostnames to file m_hostlist_path = hostlist_path; if (m_hostlist_path == "") { char temp_path[NAME_MAX] = "/tmp/geopm_hostlist_XXXXXX"; int hostlist_fd = mkstemp(temp_path); if (hostlist_fd == -1) { throw Exception("Failed to create temporary file for endpoint hostlist.", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } close(hostlist_fd); m_hostlist_path = std::string(temp_path); } std::ofstream outfile(m_hostlist_path); for (const auto &host : hosts) { outfile << host << "\n"; } data->hostlist_path[GEOPM_ENDPOINT_HOSTLIST_PATH_MAX -1] = '\0'; strncpy(data->hostlist_path, m_hostlist_path.c_str(), GEOPM_ENDPOINT_HOSTLIST_PATH_MAX - 1); } EndpointUserImp::~EndpointUserImp() { // detach from shared memory auto lock = m_sample_shmem->get_scoped_lock(); auto data = (struct geopm_endpoint_sample_shmem_s *)m_sample_shmem->pointer(); data->agent[0] = '\0'; data->profile_name[0] = '\0'; data->hostlist_path[0] = '\0'; unlink(m_hostlist_path.c_str()); } double EndpointUserImp::read_policy(std::vector<double> &policy) { auto lock = m_policy_shmem->get_scoped_lock(); auto data = (struct geopm_endpoint_policy_shmem_s *) m_policy_shmem->pointer(); // Managed by shmem subsystem. int num_policy = data->count; if (policy.size() < (size_t)num_policy) { throw Exception("EndpointUserImp::" + std::string(__func__) + "(): Data read from shmem does not fit in policy vector.", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } // Fill in missing policy values with NAN (default) std::fill(policy.begin(), policy.end(), NAN); std::copy(data->values, data->values + data->count, policy.begin()); geopm_time_s ts = data->timestamp; return geopm_time_since(&ts); } void EndpointUserImp::write_sample(const std::vector<double> &sample) { if (sample.size() != m_num_sample) { throw Exception("ShmemEndpoint::" + std::string(__func__) + "(): size of sample does not match expected.", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } auto lock = m_sample_shmem->get_scoped_lock(); auto data = (struct geopm_endpoint_sample_shmem_s *)m_sample_shmem->pointer(); data->count = sample.size(); std::copy(sample.begin(), sample.end(), data->values); // also update timestamp geopm_time(&data->timestamp); } }
44.671533
132
0.586438
[ "vector" ]
82815363fab84eb76cb80f5386ee18516a932ab7
31,861
cpp
C++
src/ripples/main.cpp
dtorvi/usher
4725931517655db990fc576815607665ab87c1b0
[ "MIT" ]
null
null
null
src/ripples/main.cpp
dtorvi/usher
4725931517655db990fc576815607665ab87c1b0
[ "MIT" ]
null
null
null
src/ripples/main.cpp
dtorvi/usher
4725931517655db990fc576815607665ab87c1b0
[ "MIT" ]
null
null
null
#include <time.h> #include <array> #include <fstream> #include <iostream> #include <memory> #include <vector> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include "tbb/concurrent_unordered_set.h" #include "../usher_graph.hpp" namespace po = boost::program_options; Timer timer; po::variables_map check_options(int argc, char** argv) { uint32_t num_cores = tbb::task_scheduler_init::default_num_threads(); std::string num_threads_message = "Number of threads to use when possible [DEFAULT uses all available cores, " + std::to_string(num_cores) + " detected on this machine]"; po::options_description desc("optimize options"); desc.add_options() ("input-mat,i", po::value<std::string>()->required(), "Input mutation-annotated tree file to optimize [REQUIRED].") ("branch-length,l", po::value<uint32_t>()->default_value(3), \ "Minimum length of the branch to consider to recombination events") ("min-coordinate-range,r", po::value<int>()->default_value(1e3), \ "Minimum range of the genomic coordinates of the mutations on the recombinant branch") ("max-coordinate-range,R", po::value<int>()->default_value(1e7), \ "Maximum range of the genomic coordinates of the mutations on the recombinant branch") ("outdir,d", po::value<std::string>()->default_value("."), "Output directory to dump output files [DEFAULT uses current directory]") ("samples-filename,s", po::value<std::string>()->default_value(""), "Restrict the search to the ancestors of the samples specified in the input file") ("parsimony-improvement,p", po::value<int>()->default_value(3), \ "Minimum improvement in parsimony score of the recombinant sequence during the partial placement") ("num-descendants,n", po::value<uint32_t>()->default_value(10), \ "Minimum number of leaves that node should have to be considered for recombination.") ("threads,T", po::value<uint32_t>()->default_value(num_cores), num_threads_message.c_str()) ("start-index,S", po::value<int>()->default_value(-1), "start index [EXPERIMENTAL]") ("end-index,E", po::value<int>()->default_value(-1), "end index [EXPERIMENTAL]") ("help,h", "Print help messages"); po::options_description all_options; all_options.add(desc); po::positional_options_description p; po::variables_map vm; try { po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(p) .run(), vm); po::notify(vm); } catch(std::exception &e) { std::cerr << desc << std::endl; // Return with error code 1 unless // the user specifies help if (vm.count("help")) exit(0); else exit(1); } return vm; } struct Pruned_Sample { std::string sample_name; std::vector<MAT::Mutation> sample_mutations; std::unordered_set<uint32_t> positions; // Assumes mutations are added in reverse chrono order void add_mutation (MAT::Mutation mut) { // If not reversal to reference allele if ((mut.ref_nuc != mut.mut_nuc) && (positions.find(mut.position) == positions.end())) { auto iter = std::lower_bound(sample_mutations.begin(), sample_mutations.end(), mut); auto m = mut.copy(); m.par_nuc = m.ref_nuc; sample_mutations.insert(iter, m); } positions.insert(mut.position); } Pruned_Sample (std::string name) { sample_name = name; sample_mutations.clear(); positions.clear(); } }; struct Recomb_Node { std::string name; int node_parsimony; int parsimony; char is_sibling; Recomb_Node() { name = ""; node_parsimony = -1; parsimony = -1; is_sibling = false; } Recomb_Node(std::string n, int np, int p, char s) : name(n), node_parsimony(np), parsimony(p), is_sibling(s) {} inline bool operator< (const Recomb_Node& n) const { return (((*this).parsimony < n.parsimony) || (((*this).name < n.name) && ((*this).parsimony == n.parsimony))); } }; struct Recomb_Interval { Recomb_Node d;//donor Recomb_Node a;//acceptor int start_range_low; int start_range_high; int end_range_low; int end_range_high; Recomb_Interval(Recomb_Node donor, Recomb_Node acceptor, int sl, int sh, int el, int eh): d(donor), a(acceptor), start_range_low(sl), start_range_high(sh), end_range_low(el), end_range_high(eh) {} bool operator<(const Recomb_Interval& other) const { //compare second interval return end_range_low < other.end_range_low; } }; struct Comp_First_Interval { inline bool operator()(const Recomb_Interval& one, const Recomb_Interval& other) { return one.start_range_low < other.start_range_low; } }; std::vector<Recomb_Interval> combine_intervals(std::vector<Recomb_Interval> pair_list) { //combine second interval std::vector<Recomb_Interval> pairs(pair_list); std::sort(pairs.begin(), pairs.end());//sorts by beginning of second interval for(size_t i = 0; i < pairs.size(); i++) { for(size_t j = i+1; j < pairs.size(); j++) { //check everything except first interval is same and first interval of pairs[i] ends where it starts for pairs[j] if((pairs[i].d.name == pairs[j].d.name) && (pairs[i].a.name == pairs[j].a.name) && (pairs[i].start_range_low == pairs[j].start_range_low) && (pairs[i].start_range_high == pairs[j].start_range_high) && (pairs[i].end_range_high == pairs[j].end_range_low) && ((pairs[i].d.parsimony+pairs[i].a.parsimony) == (pairs[j].d.parsimony+pairs[j].a.parsimony))) { pairs[i].end_range_high = pairs[j].end_range_high; pairs.erase(pairs.begin()+j);//remove the combined element j--; } } } //combine first interval std::sort(pairs.begin(), pairs.end(), Comp_First_Interval()); for(size_t i = 0; i < pairs.size(); i++) { for(size_t j = i + 1; j < pairs.size(); j++) { //check everything except second interval is same and second interval of pairs[i] ends where it starts for pairs[j] if((pairs[i].d.name == pairs[j].d.name) && (pairs[i].a.name == pairs[j].a.name) && (pairs[i].end_range_low == pairs[j].end_range_low) && (pairs[i].end_range_high == pairs[j].end_range_high) && (pairs[i].start_range_high == pairs[j].start_range_low) && ((pairs[i].d.parsimony+pairs[i].a.parsimony) == (pairs[j].d.parsimony+pairs[j].a.parsimony))) { pairs[i].start_range_high = pairs[j].start_range_high; pairs.erase(pairs.begin()+j); j--; } } } return pairs; } int main(int argc, char** argv) { po::variables_map vm = check_options(argc, argv); std::string input_mat_filename = vm["input-mat"].as<std::string>(); std::string outdir = vm["outdir"].as<std::string>(); std::string samples_filename = vm["samples-filename"].as<std::string>(); uint32_t branch_len = vm["branch-length"].as<uint32_t>(); int parsimony_improvement = vm["parsimony-improvement"].as<int>(); int max_range = vm["max-coordinate-range"].as<int>(); int min_range = vm["min-coordinate-range"].as<int>(); uint32_t num_descendants = vm["num-descendants"].as<uint32_t>(); int start_idx = vm["start-index"].as<int>(); int end_idx = vm["end-index"].as<int>(); uint32_t num_threads = vm["threads"].as<uint32_t>(); tbb::task_scheduler_init init(num_threads); srand (time(NULL)); static tbb::affinity_partitioner ap; timer.Start(); fprintf(stderr, "Loading input MAT file %s.\n", input_mat_filename.c_str()); // Load input MAT and uncondense tree MAT::Tree T = MAT::load_mutation_annotated_tree(input_mat_filename); T.uncondense_leaves(); fprintf(stderr, "Completed in %ld msec \n\n", timer.Stop()); timer.Start(); fprintf(stderr, "Finding the branches with number of mutations equal to or exceeding %u.\n", branch_len); auto bfs = T.breadth_first_expansion(); tbb::concurrent_unordered_set<std::string> nodes_to_consider; if (samples_filename != "") { std::ifstream infile(samples_filename); if (!infile) { fprintf(stderr, "ERROR: Could not open the samples file: %s!\n", samples_filename.c_str()); exit(1); } std::string line; fprintf(stderr, "Reading samples from the file %s.\n", samples_filename.c_str()); timer.Start(); while (std::getline(infile, line)) { std::vector<std::string> words; MAT::string_split(line, words); if (words.size() != 1) { fprintf(stderr, "ERROR: Incorrect format for samples file: %s!\n", samples_filename.c_str()); exit(1); } auto n = T.get_node(words[0]); if (n == NULL) { fprintf(stderr, "ERROR: Node id %s not found!\n", words[0].c_str()); exit(1); } else { for (auto anc: T.rsearch(n->identifier, true)) { nodes_to_consider.insert(anc->identifier); } } } infile.close(); } else { tbb::parallel_for(tbb::blocked_range<size_t>(0, bfs.size()), [&](const tbb::blocked_range<size_t> r) { for (size_t i=r.begin(); i<r.end(); ++i) { auto n = bfs[i]; if (n == T.root) { continue; } if (n->mutations.size() >= branch_len) { if (T.get_num_leaves(n) >= num_descendants) { nodes_to_consider.insert(n->identifier); } } } }, ap); } std::vector<std::string> nodes_to_consider_vec; for (auto elem: nodes_to_consider) { nodes_to_consider_vec.emplace_back(elem); } std::sort(nodes_to_consider_vec.begin(), nodes_to_consider_vec.end()); fprintf(stderr, "Found %zu long branches\n", nodes_to_consider.size()); fprintf(stderr, "Completed in %ld msec \n\n", timer.Stop()); fprintf(stderr, "Creating output files.\n"); boost::filesystem::path path(outdir); if (!boost::filesystem::exists(path)) { boost::filesystem::create_directory(path); } path = boost::filesystem::canonical(outdir); outdir = path.generic_string(); auto desc_filename = outdir + "/descendants.tsv"; fprintf(stderr, "Creating file %s to write descendants of recombinant nodes\n", desc_filename.c_str()); FILE* desc_file = fopen(desc_filename.c_str(), "w"); fprintf(desc_file, "#node_id\tdescendants\n"); auto recomb_filename = outdir + "/recombination.tsv"; fprintf(stderr, "Creating file %s to write recombination events\n", recomb_filename.c_str()); FILE* recomb_file = fopen(recomb_filename.c_str(), "w"); fprintf(recomb_file, "#recomb_node_id\tbreakpoint-1_interval\tbreakpoint-2_interval\tdonor_node_id\tdonor_is_sibling\tdonor_parsimony\tacceptor_node_id\tacceptor_is_sibling\tacceptor_parsimony\toriginal_parsimony\tmin_starting_parsimony\trecomb_parsimony\n"); fprintf(stderr, "Completed in %ld msec \n\n", timer.Stop()); timer.Start(); std::unordered_map<MAT::Node*, size_t> tree_num_leaves; for (int i=int(bfs.size())-1; i>=0; i--) { auto n = bfs[i]; size_t desc = 1; for (auto child: n->children) { desc += tree_num_leaves[child]; } tree_num_leaves[n] = desc; } size_t s = 0, e = nodes_to_consider.size(); if ((start_idx >= 0) && (end_idx >= 0)) { s = start_idx; if (end_idx <= (int) e) { e = end_idx; } } fprintf(stderr, "Running placement individually for %zu branches to identify potential recombination events.\n", e-s); size_t num_done = 0; for (size_t idx = s; idx < e; idx++) { auto nid_to_consider = nodes_to_consider_vec[idx]; fprintf(stderr, "At node id: %s\n", nid_to_consider.c_str()); int orig_parsimony = (int) T.get_node(nid_to_consider)->mutations.size(); Pruned_Sample pruned_sample(nid_to_consider); // Find mutations on the node to prune auto node_to_root = T.rsearch(nid_to_consider, true); for (auto curr: node_to_root) { for (auto m: curr->mutations) { pruned_sample.add_mutation(m); } } size_t num_mutations = pruned_sample.sample_mutations.size(); size_t total_nodes = bfs.size(); std::vector<std::vector<MAT::Mutation>> node_excess_mutations(total_nodes); std::vector<std::vector<MAT::Mutation>> imputed_mutations(total_nodes); std::vector<int> node_set_difference(total_nodes); size_t best_node_num_leaves = 0; int best_set_difference = 1e9; std::vector<bool> node_has_unique(total_nodes); size_t best_j = 0; bool best_node_has_unique = false; size_t best_distance = 1e9; std::vector<size_t> best_j_vec; size_t num_best = 1; MAT::Node* best_node = T.root; best_j_vec.emplace_back(0); std::vector<size_t> node_distance(total_nodes, 0); tbb::parallel_for( tbb::blocked_range<size_t>(0, total_nodes), [&](tbb::blocked_range<size_t> r) { for (size_t k=r.begin(); k<r.end(); ++k) { if (tree_num_leaves[bfs[k]] < num_descendants) { continue; } node_has_unique[k] = false; mapper2_input inp; inp.T = &T; inp.node = bfs[k]; inp.missing_sample_mutations = &pruned_sample.sample_mutations; inp.excess_mutations = &node_excess_mutations[k]; inp.imputed_mutations = &imputed_mutations[k]; inp.best_node_num_leaves = &best_node_num_leaves; inp.best_set_difference = &best_set_difference; inp.best_node = &best_node; inp.best_j = &best_j; inp.num_best = &num_best; inp.j = k; inp.has_unique = &best_node_has_unique; inp.set_difference = &node_set_difference[k]; inp.distance = node_distance[k]; inp.best_distance = &best_distance; inp.best_j_vec = &best_j_vec; inp.node_has_unique = &(node_has_unique); mapper2_body(inp, true); } }, ap); std::vector<Recomb_Interval> valid_pairs; bool has_recomb = false; size_t at = 0; for (size_t i = 0; i<num_mutations; i++) { for (size_t j=i; j<num_mutations; j++) { fprintf(stderr, "\rTrying %zu of %zu breakpoint pairs.", ++at, num_mutations*(1+num_mutations)/2); Pruned_Sample donor("donor"); Pruned_Sample acceptor("acceptor"); donor.sample_mutations.clear(); acceptor.sample_mutations.clear(); for (size_t k=0; k<num_mutations; k++) { if ((k>=i) && (k<j)) { donor.add_mutation(pruned_sample.sample_mutations[k]); } else { acceptor.add_mutation(pruned_sample.sample_mutations[k]); } } int start_range_high = pruned_sample.sample_mutations[i].position; int start_range_low = (i>=1) ? pruned_sample.sample_mutations[i-1].position : 0; //int end_range_high = pruned_sample.sample_mutations[j].position; int end_range_high = 1e9; int end_range_low = (j>=1) ? pruned_sample.sample_mutations[j-1].position : 0; //int end_range_low = pruned_sample.sample_mutations[j].position; //int end_range_high = (j+1<num_mutations) ? pruned_sample.sample_mutations[j+1].position : 1e9; if ((donor.sample_mutations.size() < branch_len) || (acceptor.sample_mutations.size() < branch_len) || (end_range_low-start_range_high < min_range) || (end_range_low-start_range_high > max_range)) { continue; } tbb::concurrent_vector<Recomb_Node> donor_nodes; tbb::concurrent_vector<Recomb_Node> acceptor_nodes; donor_nodes.clear(); acceptor_nodes.clear(); // find acceptor(s) { tbb::parallel_for( tbb::blocked_range<size_t>(0, total_nodes), [&](tbb::blocked_range<size_t> r) { for (size_t k=r.begin(); k<r.end(); ++k) { size_t num_mut = 0; if ((tree_num_leaves[bfs[k]] < num_descendants) || (T.is_ancestor(nid_to_consider,bfs[k]->identifier))) { continue; } // Is placement as sibling if (bfs[k]->is_leaf() || node_has_unique[k]) { std::vector<MAT::Mutation> l2_mut; // Compute l2_mut for (auto m1: node_excess_mutations[k]) { bool found = false; for (auto m2: bfs[k]->mutations) { if (m1.is_masked()) { break; } if (m1.position == m2.position) { if (m1.mut_nuc == m2.mut_nuc) { found = true; break; } } } if (!found) { if ((m1.position < start_range_high) || (m1.position > end_range_low)) { num_mut++; } } if (num_mut + parsimony_improvement > (size_t) orig_parsimony) { break; } } if (num_mut + parsimony_improvement <= (size_t) orig_parsimony) { acceptor_nodes.emplace_back(Recomb_Node(bfs[k]->identifier, node_set_difference[k], num_mut, 'y')); } } // Else placement as child else { for (auto m1: node_excess_mutations[k]) { bool found = false; for (auto m2: bfs[k]->mutations) { if (m1.is_masked()) { break; } if (m1.position == m2.position) { if (m1.mut_nuc == m2.mut_nuc) { found = true; break; } } } if (!found) { if ((m1.position < start_range_high) || (m1.position > end_range_low)) { num_mut++; } } if (num_mut + parsimony_improvement > (size_t) orig_parsimony) { break; } } if (num_mut + parsimony_improvement <= (size_t) orig_parsimony) { acceptor_nodes.emplace_back(Recomb_Node(bfs[k]->identifier, node_set_difference[k], num_mut, 'n')); } } } }, ap); } if (acceptor_nodes.size() == 0) { continue; } // find donor(s) { tbb::parallel_for( tbb::blocked_range<size_t>(0, total_nodes), [&](tbb::blocked_range<size_t> r) { for (size_t k=r.begin(); k<r.end(); ++k) { if ((tree_num_leaves[bfs[k]] < num_descendants) || (T.is_ancestor(nid_to_consider,bfs[k]->identifier))) { continue; } size_t num_mut = 0; // Is placement as sibling if (bfs[k]->is_leaf() || node_has_unique[k]) { std::vector<MAT::Mutation> l2_mut; // Compute l2_mut for (auto m1: node_excess_mutations[k]) { bool found = false; for (auto m2: bfs[k]->mutations) { if (m1.is_masked()) { break; } if (m1.position == m2.position) { if (m1.mut_nuc == m2.mut_nuc) { found = true; break; } } } if (!found) { if ((m1.position >= start_range_high) && (m1.position <= end_range_low)) { num_mut++; } } if (num_mut + parsimony_improvement > (size_t) orig_parsimony) { break; } } if (num_mut + parsimony_improvement <= (size_t) orig_parsimony) { donor_nodes.emplace_back(Recomb_Node(bfs[k]->identifier, node_set_difference[k], num_mut, 'y')); } } // Else placement as child else { for (auto m1: node_excess_mutations[k]) { bool found = false; for (auto m2: bfs[k]->mutations) { if (m1.is_masked()) { break; } if (m1.position == m2.position) { if (m1.mut_nuc == m2.mut_nuc) { found = true; break; } } } if (!found) { if ((m1.position >= start_range_high) && (m1.position <= end_range_low)) { num_mut++; } } if (num_mut + parsimony_improvement > (size_t) orig_parsimony) { break; } } if (num_mut + parsimony_improvement <= (size_t) orig_parsimony) { donor_nodes.emplace_back(Recomb_Node(bfs[k]->identifier, node_set_difference[k], num_mut, 'n')); } } } }, ap); } tbb::parallel_sort (donor_nodes.begin(), donor_nodes.end()); tbb::parallel_sort (acceptor_nodes.begin(), acceptor_nodes.end()); if (donor_nodes.size() > 1000) { donor_nodes.resize(1000); } if (acceptor_nodes.size() > 1000) { acceptor_nodes.resize(1000); } // to print any pair of breakpoint interval exactly once for // multiple donor-acceptor pairs bool has_printed = false; for (auto d: donor_nodes) { if (T.is_ancestor(nid_to_consider,d.name)) { continue; } for (auto a:acceptor_nodes) { if (T.is_ancestor(nid_to_consider,a.name)) { continue; } // Ensure donor and acceptor are not the same and // neither of them is a descendant of the recombinant // node total parsimony is less than the maximum allowed if ((d.name!=a.name) && (d.name!=nid_to_consider) && (a.name!=nid_to_consider) && //(!T.is_ancestor(nid_to_consider,d.name)) && (!T.is_ancestor(nid_to_consider,a.name)) && (orig_parsimony >= d.parsimony + a.parsimony + parsimony_improvement)) { Pruned_Sample donor("curr-donor"); donor.sample_mutations.clear(); acceptor.sample_mutations.clear(); for (auto anc: T.rsearch(d.name, true)) { for (auto mut: anc->mutations) { donor.add_mutation(mut); } } for (auto mut: donor.sample_mutations) { if ((mut.position > start_range_low) && (mut.position <= start_range_high)) { bool in_pruned_sample = false; for (auto mut2: pruned_sample.sample_mutations) { if (mut.position == mut2.position) { in_pruned_sample = true; } } if (!in_pruned_sample) { start_range_low = mut.position; } } if ((mut.position > end_range_low) && (mut.position <= end_range_high)) { bool in_pruned_sample = false; for (auto mut2: pruned_sample.sample_mutations) { if (mut.position == mut2.position) { in_pruned_sample = true; } } if (!in_pruned_sample) { end_range_high = mut.position; } } } for (auto mut: pruned_sample.sample_mutations) { if ((mut.position > start_range_low) && (mut.position <= start_range_high)) { bool in_pruned_sample = false; for (auto mut2: donor.sample_mutations) { if (mut.position == mut2.position) { in_pruned_sample = true; } } if (!in_pruned_sample) { start_range_low = mut.position; } } if ((mut.position > end_range_low) && (mut.position <= end_range_high)) { bool in_pruned_sample = false; for (auto mut2: donor.sample_mutations) { if (mut.position == mut2.position) { in_pruned_sample = true; } } if (!in_pruned_sample) { end_range_high = mut.position; } } } //tbb_lock.lock(); valid_pairs.push_back(Recomb_Interval(d, a, start_range_low, start_range_high, end_range_low, end_range_high)); //tbb_lock.unlock(); has_recomb = true; has_printed = true; break; } } if (has_printed) { break; } } } } fprintf(stderr, "\n"); valid_pairs = combine_intervals(valid_pairs); //print combined pairs for(auto p: valid_pairs) { std::string end_range_high_str = (p.end_range_high == 1e9) ? "GENOME_SIZE" : std::to_string(p.end_range_high); fprintf(recomb_file, "%s\t(%i,%i)\t(%i,%s)\t%s\t%c\t%i\t%s\t%c\t%i\t%i\t%i\t%i\n", nid_to_consider.c_str(), p.start_range_low, p.start_range_high, p.end_range_low, end_range_high_str.c_str(), p.d.name.c_str(), p.d.is_sibling, p.d.node_parsimony, p.a.name.c_str(), p.a.is_sibling, p.a.node_parsimony, orig_parsimony, std::min({orig_parsimony, p.d.node_parsimony, p.a.node_parsimony}), p.d.parsimony+p.a.parsimony); fflush(recomb_file); } if (has_recomb) { fprintf(desc_file, "%s\t", nid_to_consider.c_str()); for (auto l: T.get_leaves(nid_to_consider)) { fprintf(desc_file, "%s,", l->identifier.c_str()); } fprintf(desc_file, "\n"); fflush(desc_file); fprintf(stderr, "Done %zu/%zu branches [RECOMBINATION FOUND!]\n\n", ++num_done, nodes_to_consider.size()); } else { fprintf(stderr, "Done %zu/%zu branches\n\n", ++num_done, nodes_to_consider.size()); } } fclose(desc_file); fclose(recomb_file); fprintf(stderr, "Completed in %ld msec \n\n", timer.Stop()); }
44.685835
263
0.473431
[ "vector" ]
8289a2397819e0889f8a7385b055acfdb8949458
1,522
cpp
C++
src/Core/Subsystems/Renderer/world/World.cpp
tmarrec/vulkan-testings
954421ca5365c9b509b0bd3765c9b804201d0df5
[ "MIT" ]
null
null
null
src/Core/Subsystems/Renderer/world/World.cpp
tmarrec/vulkan-testings
954421ca5365c9b509b0bd3765c9b804201d0df5
[ "MIT" ]
null
null
null
src/Core/Subsystems/Renderer/world/World.cpp
tmarrec/vulkan-testings
954421ca5365c9b509b0bd3765c9b804201d0df5
[ "MIT" ]
null
null
null
#include "World.h" #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYGLTF_NOEXCEPTION #include <tiny_gltf.h> World::World() { tinygltf::Model model; tinygltf::TinyGLTF loader; std::string err; std::string warn; //bool ret = loader.LoadASCIIFromFile(&model, &err, &warn, "models/BoxTextured.glb"); bool ret = loader.LoadBinaryFromFile(&model, &err, &warn, "models/BoxTextured.glb"); if (!warn.empty()) { WARNING(warn.c_str()); } if (!err.empty()) { ERROR(err.c_str()); } if (!ret) { ERROR_EXIT("Failed to load glTF file."); } for (const auto& gltfScene : model.scenes) { const Scene scene {gltfScene.nodes, model}; _scenes.emplace_back(scene); } _currentScene = model.defaultScene; _indicesBuffer = _scenes[_currentScene].getIndicesBuffer(); _vertexBuffer = _scenes[_currentScene].getPositionBuffer(); for (const auto& gltfTexture : model.textures) { const Texture texture {gltfTexture, model}; _textures.emplace_back(texture); } } const std::vector<uint16_t>& World::getIndicesBuffer() const { return _indicesBuffer; } const std::vector<float>& World::getVertexBuffer() const { return _vertexBuffer; } const std::vector<Node>& World::getNodes() const { return _scenes[_currentScene].getNodes(); } const std::vector<Texture>& World::getTextures() const { return _textures; }
21.43662
89
0.665572
[ "vector", "model" ]
8293316dd520df9ba187816c74e01f274885e5ad
3,785
cpp
C++
compiler/Java/JavaBuilder.cpp
patrickf2000/espresso
a83217ef206347516326780c617a9f2b9b6c379b
[ "BSD-3-Clause" ]
null
null
null
compiler/Java/JavaBuilder.cpp
patrickf2000/espresso
a83217ef206347516326780c617a9f2b9b6c379b
[ "BSD-3-Clause" ]
null
null
null
compiler/Java/JavaBuilder.cpp
patrickf2000/espresso
a83217ef206347516326780c617a9f2b9b6c379b
[ "BSD-3-Clause" ]
null
null
null
// // Copyright 2021 Patrick Flynn // This file is part of the Espresso compiler. // Espresso is licensed under the BSD-3 license. See the COPYING file for more information. // #include <Java/JavaIR.hpp> #include <Java/JavaBuilder.hpp> // Sets initial things up JavaClassBuilder::JavaClassBuilder(std::string className) { java = new JavaClassFile; this->className = className; // Sets the class name int pos = AddUTF8(className); JavaClassRef *classRef = new JavaClassRef(pos); pos = java->AddConst(classRef); classMap[className] = pos; superPos = pos; java->this_idx = htons(pos); // Set the super class pos = AddUTF8("java/lang/Object"); JavaClassRef *superRef = new JavaClassRef(pos); pos = java->AddConst(superRef); classMap["java/lang/Object"] = pos; java->super_idx = htons(pos); codeIdx = AddUTF8("Code"); // Import the object constructor ImportMethod("java/lang/Object", "<init>", "()V"); } // Adds a utf8 string to the constant pool int JavaClassBuilder::AddUTF8(std::string value) { JavaUTF8Entry *entry = new JavaUTF8Entry(value); java->const_pool.push_back(entry); int pos = java->const_pool.size(); UTF8Index[value] = pos; return pos; } // Imports a class int JavaClassBuilder::ImportClass(std::string baseClass) { int classPos = 0; if (classMap.find(baseClass) == classMap.end()) { classPos = AddUTF8(baseClass); JavaClassRef *classRef = new JavaClassRef(classPos); classPos = java->AddConst(classRef); classMap[baseClass] = classPos; } else { classPos = classMap[baseClass]; } return classPos; } // Imports a method void JavaClassBuilder::ImportMethod(std::string baseClass, std::string name, std::string signature) { int classPos = ImportClass(baseClass); // Create the name and type <name><type> int namePos = AddUTF8(name); int sigPos = AddUTF8(signature); JavaNameTypeEntry *nt = new JavaNameTypeEntry(namePos, sigPos); int ntPos = java->AddConst(nt); // Create the method ref <class><name_type> JavaMethodRefEntry *method = new JavaMethodRefEntry(classPos, ntPos); int methodPos = java->AddConst(method); //methodMap[name] = methodPos; Method m(name, methodPos, baseClass, signature); methodMap.push_back(m); } // Imports a field from another class void JavaClassBuilder::ImportField(std::string baseClass, std::string typeClass, std::string name) { int baseClassPos = ImportClass(baseClass); int typeClassPos = ImportClass(typeClass); // Create the signature: "L<typeClass>;" std::string sig = "L" + typeClass + ";"; int sigPos = AddUTF8(sig); int namePos = AddUTF8(name); // NameAndType <name><sig> JavaNameTypeEntry *nt = new JavaNameTypeEntry(namePos, sigPos); int ntPos = java->AddConst(nt); // FieldRef <baseClass><name_type> JavaFieldRefEntry *ref = new JavaFieldRefEntry(baseClassPos, ntPos); int refPos = java->AddConst(ref); fieldMap[name] = refPos; } // Finds a method in the method table int JavaClassBuilder::FindMethod(std::string name, std::string baseClass, std::string signature) { for (auto m : methodMap) { if (m.name == name) { bool found1 = true; bool found2 = true; if (baseClass != "") { if (m.baseClass != baseClass && baseClass != "this") found1 = false; } if (signature != "") { if (m.signature != signature) found2 = false; } if (found1 && found2) return m.pos; } } return 0; } // Writes out the class file void JavaClassBuilder::Write(FILE *file) { java->write(file); }
28.246269
101
0.643857
[ "object" ]
8297813c569d59de1e568f360adcb3a52758a27d
3,969
cpp
C++
test/unit/n_threaded_priority_task_queue_tests.cpp
Ravirael/concurrentpp
c018509074eee0abbcbc028fb53fed1ec8699666
[ "MIT" ]
2
2018-02-09T20:22:34.000Z
2020-11-28T09:14:19.000Z
test/unit/n_threaded_priority_task_queue_tests.cpp
Ravirael/concurrentpp
c018509074eee0abbcbc028fb53fed1ec8699666
[ "MIT" ]
null
null
null
test/unit/n_threaded_priority_task_queue_tests.cpp
Ravirael/concurrentpp
c018509074eee0abbcbc028fb53fed1ec8699666
[ "MIT" ]
1
2019-07-12T08:05:04.000Z
2019-07-12T08:05:04.000Z
#include <catch.hpp> #include <n_threaded_task_queue.hpp> #include <mutex> #include <functional> #include <unsafe_priority_queue.hpp> #include <barrier.hpp> #include <priority_task_queue_extension.hpp> #include "spy_thread.h" #include "test_configuration.h" SCENARIO("creating priority task queue, adding and executing tasks", "[concurrent::n_threaded_priority_task_queue]") { GIVEN("a 4-threaded priority task queue") { concurrent::priority_task_queue_extension< concurrent::n_threaded_task_queue< concurrent::unsafe_priority_queue<int, std::function<void(void)>>, concurrent::spy_thread > > task_queue(4); WHEN("task with different priorities are added") { auto barrier = std::make_unique<concurrent::barrier>(5); // add 4 tasks to block all workers for (auto i = 0u; i < 4u; ++i) { task_queue.emplace( 10, [&barrier] { barrier->wait(); } ); } auto mutex = std::make_shared<std::mutex>(); auto barriers = std::make_shared<std::vector<concurrent::barrier>>(); auto finished_tasks_priorities = std::make_shared<std::vector<int>>(); auto last_task_finished = std::make_shared<std::condition_variable>(); for (int i = 0; i < 4; ++i) { barriers->emplace_back(4); } // add 16 tasks with 4 priorieties for (auto i = 0u; i < 4u; ++i) { for (auto priority = 0; priority < 4; ++priority) { task_queue.emplace( priority, [mutex, priority, finished_tasks_priorities, barriers, last_task_finished] { { std::lock_guard<std::mutex> lock(*mutex); finished_tasks_priorities->push_back(priority); } barriers->at(priority).wait(); bool notify; { std::lock_guard<std::mutex> lock(*mutex); notify = (finished_tasks_priorities->size() == 16); } if (notify) { last_task_finished->notify_one(); } } ); } } // release workers REQUIRE(barrier->wait_for(config::default_timeout)); THEN("priorities of finished task should be descending") { std::unique_lock<std::mutex> lock(*mutex); REQUIRE( last_task_finished->wait_for( lock, config::default_timeout, [finished_tasks_priorities] { return finished_tasks_priorities->size() == 16;} ) ); for (auto i = 1u; i < finished_tasks_priorities->size(); ++i) { REQUIRE(finished_tasks_priorities->at(i) <= finished_tasks_priorities->at(i - 1)); } } } WHEN("task with result is pushed") { auto result = task_queue.push_with_result(std::make_pair(0, []{return 1;})); THEN("the task is finally finished") { REQUIRE(result.get() == 1); } } WHEN("task with result is emplaced") { auto result = task_queue.emplace_with_result(0, []{return 1;}); THEN("the task is finally finished") { REQUIRE(result.get() == 1); } } } }
38.911765
118
0.46586
[ "vector" ]
82995ccfe9a8faff6852113ce0a405ba5530bb92
4,294
cpp
C++
regress/fuzz/fuzz_ged.cpp
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
regress/fuzz/fuzz_ged.cpp
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
regress/fuzz/fuzz_ged.cpp
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* F U Z Z _ G E D . C P P * BRL-CAD * * Copyright (c) 2020-2022 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ #include "common.h" #include "bio.h" #include <string> #include <vector> #include <cassert> #include "bu.h" #include "bv.h" #include "ged.h" const size_t MAX_ARGS = 5; //const std::string OUTPUT = "fuzz_ged.g"; static size_t getArgc(uint8_t byte) { return (byte % MAX_ARGS) + 1; } static const std::string& getCommand(uint8_t byte) { static const std::vector<std::string> commands = { "help", "in", "ls", "tops" }; return commands[byte % commands.size()]; } static const std::string& getArg(uint8_t byte) { static const std::vector<std::string> args = { "COMMAND", "-a", "-b", "-c", "-d", "-e", "-f", "-g", "-h", "-i", "-j", "-k", "-l", "-m", "-n", "-o", "-p", "-q", "-r", "-s", "-t", "-u", "-v", "-w", "-x", "-y", "-z", "a", "b", "c", "x", "y", "z", /* auto-extracted using: * grep \", \ \" src/librt/primitives/table.cpp | grep FUNC | cut -f3 -d, | perl -p -0777 -e 's/"\n/", \n/g' */ "NULL", "tor", "tgc", "ell", "arb8", "ars", "half", "rec", "poly", "bspline", "sph", "nmg", "ebm", "vol", "arbn", "pipe", "part", "rpc", "rhc", "epa", "ehy", "eto", "grip", "joint", "hf", "dsp", "sketch", "extrude", "submodel", "cline", "bot", "comb", "unused1", "binunif", "unused2", "superell", "metaball", "brep", "hyp", "constrnt", "revolve", "pnts", "annot", "hrt", "datum", "script", "u", "-", "+", "-5", "-4", "-3", "-1", "0", "1", "2", "3", "4", "5", "-5.0", "-1.0", "-0.5", "-0.05", "0.0", "0.05", "0.5", "1.0", "5.0" }; assert(args.size() < UCHAR_MAX); size_t idx = byte % args.size(); if (idx == 0) return getCommand(byte); return args[idx]; } static void printCommand(std::vector<const char *> & argv) { std::cout << "Running"; for (size_t j = 0; j < argv.size(); j++) std::cout << " " << argv[j]; std::cout << std::endl; } extern "C" int LLVMFuzzerTestOneInput(const int8_t *data, size_t size) { if (size == 0) return 0; size_t i = 0; size_t argc = 0; if (i < size) argc = getArgc(data[i++]); std::vector<const char *> argv; argv.resize(argc+1, ""); argv[0] = getCommand(data[i++]).c_str(); for (size_t j = 1; j < argc; j++) { if (i < size) { argv[j] = getArg(data[i++]).c_str(); } else { /* loop around if we run out of slots */ argv[j] = getArg(data[i++ % size]).c_str(); } } printCommand(argv); struct ged g; struct rt_wdb *wdbp; struct db_i *dbip; dbip = db_create_inmem(); wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_INMEM); GED_INIT(&g, wdbp); /* FIXME: To draw, we need to init this LIBRT global */ BU_LIST_INIT(&RTG.rtg_vlfree); /* Need a view for commands that expect a view */ struct bview *gvp; BU_GET(gvp, struct bview); bv_init(gvp, &g.ged_views); g.ged_gvp = gvp; void *libged = bu_dlopen(NULL, BU_RTLD_LAZY); if (!libged) { std::cout << "ERROR: unable to dynamically load" << std::endl; return 1; } int (*func)(struct ged *, int, char *[]); std::string funcname = std::string("ged_") + argv[0]; *(void **)(&func) = bu_dlsym(libged, funcname.c_str()); int ret = 0; if (func) { ret = func(&g, argc, (char **)argv.data()); } bu_dlclose(libged); ged_close(&g); return ret; } // Local Variables: // tab-width: 8 // mode: C++ // c-basic-offset: 4 // indent-tabs-mode: t // c-file-style: "stroustrup" // End: // ex: shiftwidth=4 tabstop=8
15.962825
109
0.561481
[ "cad", "vector" ]
829a0f8f6c053613209f4b0a4d3106c6c6914e6d
4,929
cpp
C++
external/eba/src/modularity/community.cpp
Mickey253/hyperbolic-space-graphs
f23b071cf07e2a85a8a23a0af3aa99455f26b3e3
[ "MIT" ]
16
2015-07-14T02:17:35.000Z
2021-06-29T10:00:58.000Z
external/eba/src/modularity/community.cpp
Mickey253/hyperbolic-space-graphs
f23b071cf07e2a85a8a23a0af3aa99455f26b3e3
[ "MIT" ]
10
2016-06-30T08:49:45.000Z
2021-07-27T10:24:49.000Z
external/eba/src/modularity/community.cpp
Mickey253/hyperbolic-space-graphs
f23b071cf07e2a85a8a23a0af3aa99455f26b3e3
[ "MIT" ]
8
2015-01-09T01:10:41.000Z
2020-11-30T07:07:21.000Z
#include "community.h" #include <set> namespace modularity { double Community::modularity() const { double q = 0.; double m2 = g->totalWeight; for (int i = 0; i < g->n; i++) { if (tot[i] > 0) q += in[i] / m2 - (tot[i] / m2) * (tot[i] / m2); } return q; } // computation of all neighboring communities of current node map<int, double> Community::neigh_comm(int node) const { set<int> adj_comm; if (contiguity) { for (auto adj_neigh : g->adj[node]) { if (adj_neigh == node) continue; int neigh_comm = n2c[adj_neigh]; adj_comm.insert(neigh_comm); } } map<int, double> res; int comm = n2c[node]; res[comm] = 0; for (int i = 0; i < (int)g->links[node].size(); i++) { int neigh = g->links[node][i]; if (neigh == node) continue; int neigh_comm = n2c[neigh]; if (contiguity && neigh_comm != comm && !adj_comm.count(neigh_comm)) continue; double neigh_weight = g->weights[node][i]; res[neigh_comm] += neigh_weight; } return res; } double Community::one_level() { bool improvement = false; int nb_pass_done = 0; double new_mod = modularity(); double cur_mod = new_mod; // repeat while // there is an improvement of modularity // or there is an improvement of modularity greater than a given epsilon // or a predefined number of pass have been done do { cur_mod = new_mod; improvement = false; nb_pass_done++; // for each node: remove the node from its community and insert it in the best community for (int node_tmp = 0; node_tmp < g->n; node_tmp++) { int node = node_tmp; int node_comm = n2c[node]; // computation of all neighboring communities of current node map<int, double> ncomm = neigh_comm(node); // remove node from its current community remove(node, node_comm, ncomm[node_comm]); // compute the nearest community for node // default choice for future insertion is the former community int best_comm = node_comm; double best_nblinks = 0; double best_increase = 0; for (auto iter = ncomm.begin(); iter != ncomm.end(); iter++) { int new_comm = (*iter).first; double increase = gain_modularity(node, new_comm, ncomm[new_comm]); if (increase > best_increase + 1e-8) { best_comm = new_comm; best_nblinks = ncomm[new_comm]; best_increase = increase; } } insert(node, best_comm, best_nblinks); if (best_comm != node_comm) improvement = true; } new_mod = modularity(); //cerr << "pass number " << nb_pass_done << " of " << nb_pass << " : " << new_mod << " " << cur_mod << endl; } while (improvement && new_mod - cur_mod > 1e-6); return new_mod; } BinaryGraph* Community::prepareBinaryGraph() const { map<int, vector<int> > comm; map<int, int> comm2Order; vector<int> order; for (int i = 0; i < g->n; i++) { if (!comm.count(n2c[i])) { comm[n2c[i]] = vector<int>(); order.push_back(n2c[i]); comm2Order[n2c[i]] = (int)order.size() - 1; } comm[n2c[i]].push_back(i); } // unweigthed to weighted BinaryGraph* g2 = new BinaryGraph((int)order.size(), contiguity); // initialize edges for (int ci = 0; ci < (int)order.size(); ci++) { int cIndex = order[ci]; map<int, double> m; for (int i = 0; i < (int)comm[cIndex].size(); i++) { int vIndex = comm[cIndex][i]; for (int i = 0; i < (int)g->links[vIndex].size(); i++) { int neigh = g->links[vIndex][i]; int neigh_comm = comm2Order[n2c[neigh]]; double neigh_weight = g->weights[vIndex][i]; m[neigh_comm] += neigh_weight; } if (contiguity) { for (auto adj_neigh : g->adj[vIndex]) { int neigh_comm = comm2Order[n2c[adj_neigh]]; g2->adj[ci].insert(neigh_comm); } } } for (auto it : m) { int neigh_comm = it.first; g2->totalWeight += m[neigh_comm]; g2->links[ci].push_back(neigh_comm); g2->weights[ci].push_back(m[neigh_comm]); } } g2->InitWeights(); return g2; } Cluster* Community::prepareCluster(const Cluster* rootCluster) const { Cluster* cluster = new Cluster(); map<int, vector<int> > comm; vector<int> order; for (int i = 0; i < g->n; i++) { if (!comm.count(n2c[i])) { comm[n2c[i]] = vector<int>(); order.push_back(n2c[i]); } comm[n2c[i]].push_back(i); } for (int ci = 0; ci < (int)order.size(); ci++) { int cIndex = order[ci]; Cluster* subCluster = new Cluster(); for (int i = 0; i < (int)comm[cIndex].size(); i++) { int vIndex = comm[cIndex][i]; if (rootCluster->containsVertices()) subCluster->addVertex(rootCluster->getVertexes()[vIndex]); else subCluster->addSubCluster(rootCluster->getSubClusters()[vIndex]); } cluster->addSubCluster(subCluster); } return cluster; } } // namespace modularity
23.140845
111
0.601339
[ "vector" ]
829fcb8877be979e46f68e6c878ad98236421d01
4,063
cpp
C++
Hero.cpp
White-Hare/SDL_Dungeon_Crawl
277fcd02c795ca4227b254dfd5b0f5807a9a9ee1
[ "MIT" ]
1
2019-08-18T08:58:15.000Z
2019-08-18T08:58:15.000Z
Hero.cpp
White-Hare/SDL_Dungeon_Crawl
277fcd02c795ca4227b254dfd5b0f5807a9a9ee1
[ "MIT" ]
null
null
null
Hero.cpp
White-Hare/SDL_Dungeon_Crawl
277fcd02c795ca4227b254dfd5b0f5807a9a9ee1
[ "MIT" ]
null
null
null
#include "Hero.h" #include <iostream> Hero::Hero(const char* ID, SDL_Rect map_rect, const int velocity):Character(ID, map_rect) { this->velocity = velocity; this->direction_ = UP; this->current_frame_pair = new int[2]{0,0}; this->firing_time = 0; } void Hero::controller(const Uint8* keystates, float delta, std::vector<Object*> objects, std::vector<MultipleObjects*> multiple_objects) { int dx = 0, dy = 0; if (keystates[SDL_SCANCODE_W]) dy -= 1; if (keystates[SDL_SCANCODE_S]) dy += 1; if (keystates[SDL_SCANCODE_A]) dx -= 1; if (keystates[SDL_SCANCODE_D]) dx += 1; if (dx == NEGATIVE) this->direction_ = LEFT; if (dx == POSITIVE) this->direction_ = RIGHT; if (dy == NEGATIVE) this->direction_ = UP; if (dy == POSITIVE) this->direction_ = DOWN; SDL_Rect* hero_rect_before = new SDL_Rect{ *this->get_self_rect() }; this->move(this->velocity, static_cast<NormalVector>(dx), static_cast<NormalVector>(dy), delta); for (auto& m_obj : multiple_objects) { if (dx == 0 && dy == 0) break; if (m_obj->collision_list(this->get_self_rect()).size() == 0) continue; this->place(hero_rect_before->x, hero_rect_before->y); this->move(this->velocity, static_cast<NormalVector>(dx), NONE, delta); if (m_obj->collision_list(this->get_self_rect()).size() == 0) { dy = NONE; continue; } this->place(hero_rect_before->x, hero_rect_before->y); this->move(this->velocity, NONE, static_cast<NormalVector>(dy), delta); if (m_obj->collision_list(this->get_self_rect()).size() == 0) { dx = NONE; continue; } this->place(hero_rect_before->x, hero_rect_before->y); dx = NONE; dy = NONE; } for (auto& obj : objects) { if (dx == 0 && dy == 0) break; if (!obj->is_collided(this->get_self_rect())) continue; this->place(hero_rect_before->x, hero_rect_before->y); this->move(this->velocity, static_cast<NormalVector>(dx), NONE, delta); if (!obj->is_collided(this->get_self_rect())) continue; this->place(hero_rect_before->x, hero_rect_before->y); this->move(this->velocity, NONE, static_cast<NormalVector>(dy), delta); if (!obj->is_collided(this->get_self_rect())) continue; this->place(hero_rect_before->x, hero_rect_before->y); } } void Hero::gun_controller(Guns* gun, void function(SDL_Rect* rect, Direction direction, float delta), std::vector<Object*> objects, std::vector<Enemies*> enemies, float delta, const Uint8* keystate) { this->firing_time += delta; Direction gun_direction = this->direction_; if (keystate[SDL_SCANCODE_SPACE] && firing_time > gun->get_firing_frequency()) { gun->add_bullet(gun_direction); firing_time = 0; } gun->behavior(function, delta); for (auto& obj : objects) { for (int i : gun->collision_list(obj->get_self_rect())) { do { objects[0]->place(rand() % (640 - 40 - objects[0]->get_self_rect()->w) + 40, rand() % (480 - 40 - objects[0]->get_self_rect()->h) + 40); } while (is_collided(obj[0].get_self_rect())); gun->erase_rect(i); } } } void Hero::render_hero(SDL_Rect* camera, SDL_Renderer* renderer, float delta) { animation_time += delta; SDL_RendererFlip flip = SDL_FLIP_NONE; if(this->direction_ == RIGHT) { current_frame_pair[0] = frame_capes[1].first; current_frame_pair[1] = frame_capes[1].second; flip = SDL_FLIP_NONE; } if (this->direction_ == LEFT) { current_frame_pair[0] = frame_capes[1].first; current_frame_pair[1] = frame_capes[1].second; flip = SDL_FLIP_HORIZONTAL; } if (this->direction_ == UP) { current_frame_pair[0] = frame_capes[2].first; current_frame_pair[1] = frame_capes[2].second; flip = SDL_FLIP_HORIZONTAL; } if (this->direction_ == DOWN) { current_frame_pair[0] = frame_capes[0].first; current_frame_pair[1] = frame_capes[0].second; flip = SDL_FLIP_NONE; } render(camera, renderer, delta, flip); } Hero::~Hero() { frame_capes.clear(); }
24.77439
199
0.64952
[ "render", "object", "vector" ]
82a131492a0b4595cfc7dc09767adf73e492bc0a
17,335
cpp
C++
wifi_hal/cpp_bindings.cpp
lineage-woods/device_motorola_mt6737-common
886472335033ca811ffd58204228d6bfc506a5bf
[ "FTL" ]
9
2018-07-20T01:54:33.000Z
2021-03-29T08:38:55.000Z
wifi_hal/cpp_bindings.cpp
lineage-woods/device_motorola_mt6737-common
886472335033ca811ffd58204228d6bfc506a5bf
[ "FTL" ]
1
2022-03-06T06:19:47.000Z
2022-03-06T06:19:47.000Z
wifi_hal/cpp_bindings.cpp
lineage-woods/device_motorola_mt6737-common
886472335033ca811ffd58204228d6bfc506a5bf
[ "FTL" ]
6
2019-01-12T16:10:38.000Z
2021-10-05T01:16:22.000Z
#include <stdint.h> #include <fcntl.h> #include <sys/socket.h> #include <netlink/genl/genl.h> #include <netlink/genl/family.h> #include <netlink/genl/ctrl.h> #include <linux/rtnetlink.h> #include <netpacket/packet.h> #include <linux/filter.h> #include <linux/errqueue.h> #include <linux/pkt_sched.h> #include <netlink/object-api.h> #include <netlink/netlink.h> #include <netlink/socket.h> #include <netlink/handlers.h> #include <ctype.h> #include "wifi_hal.h" #include "common.h" #include "cpp_bindings.h" void appendFmt(char *buf, int &offset, const char *fmt, ...) { va_list params; va_start(params, fmt); offset += vsprintf(buf + offset, fmt, params); va_end(params); } #define C2S(x) case x: return #x; static const char *cmdToString(int cmd) { switch (cmd) { C2S(NL80211_CMD_UNSPEC) C2S(NL80211_CMD_GET_WIPHY) C2S(NL80211_CMD_SET_WIPHY) C2S(NL80211_CMD_NEW_WIPHY) C2S(NL80211_CMD_DEL_WIPHY) C2S(NL80211_CMD_GET_INTERFACE) C2S(NL80211_CMD_SET_INTERFACE) C2S(NL80211_CMD_NEW_INTERFACE) C2S(NL80211_CMD_DEL_INTERFACE) C2S(NL80211_CMD_GET_KEY) C2S(NL80211_CMD_SET_KEY) C2S(NL80211_CMD_NEW_KEY) C2S(NL80211_CMD_DEL_KEY) C2S(NL80211_CMD_GET_BEACON) C2S(NL80211_CMD_SET_BEACON) C2S(NL80211_CMD_START_AP) C2S(NL80211_CMD_STOP_AP) C2S(NL80211_CMD_GET_STATION) C2S(NL80211_CMD_SET_STATION) C2S(NL80211_CMD_NEW_STATION) C2S(NL80211_CMD_DEL_STATION) C2S(NL80211_CMD_GET_MPATH) C2S(NL80211_CMD_SET_MPATH) C2S(NL80211_CMD_NEW_MPATH) C2S(NL80211_CMD_DEL_MPATH) C2S(NL80211_CMD_SET_BSS) C2S(NL80211_CMD_SET_REG) C2S(NL80211_CMD_REQ_SET_REG) C2S(NL80211_CMD_GET_MESH_CONFIG) C2S(NL80211_CMD_SET_MESH_CONFIG) C2S(NL80211_CMD_SET_MGMT_EXTRA_IE) C2S(NL80211_CMD_GET_REG) C2S(NL80211_CMD_GET_SCAN) C2S(NL80211_CMD_TRIGGER_SCAN) C2S(NL80211_CMD_NEW_SCAN_RESULTS) C2S(NL80211_CMD_SCAN_ABORTED) C2S(NL80211_CMD_REG_CHANGE) C2S(NL80211_CMD_AUTHENTICATE) C2S(NL80211_CMD_ASSOCIATE) C2S(NL80211_CMD_DEAUTHENTICATE) C2S(NL80211_CMD_DISASSOCIATE) C2S(NL80211_CMD_MICHAEL_MIC_FAILURE) C2S(NL80211_CMD_REG_BEACON_HINT) C2S(NL80211_CMD_JOIN_IBSS) C2S(NL80211_CMD_LEAVE_IBSS) C2S(NL80211_CMD_TESTMODE) C2S(NL80211_CMD_CONNECT) C2S(NL80211_CMD_ROAM) C2S(NL80211_CMD_DISCONNECT) C2S(NL80211_CMD_SET_WIPHY_NETNS) C2S(NL80211_CMD_GET_SURVEY) C2S(NL80211_CMD_NEW_SURVEY_RESULTS) C2S(NL80211_CMD_SET_PMKSA) C2S(NL80211_CMD_DEL_PMKSA) C2S(NL80211_CMD_FLUSH_PMKSA) C2S(NL80211_CMD_REMAIN_ON_CHANNEL) C2S(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL) C2S(NL80211_CMD_SET_TX_BITRATE_MASK) C2S(NL80211_CMD_REGISTER_FRAME) C2S(NL80211_CMD_FRAME) C2S(NL80211_CMD_FRAME_TX_STATUS) C2S(NL80211_CMD_SET_POWER_SAVE) C2S(NL80211_CMD_GET_POWER_SAVE) C2S(NL80211_CMD_SET_CQM) C2S(NL80211_CMD_NOTIFY_CQM) C2S(NL80211_CMD_SET_CHANNEL) C2S(NL80211_CMD_SET_WDS_PEER) C2S(NL80211_CMD_FRAME_WAIT_CANCEL) C2S(NL80211_CMD_JOIN_MESH) C2S(NL80211_CMD_LEAVE_MESH) C2S(NL80211_CMD_UNPROT_DEAUTHENTICATE) C2S(NL80211_CMD_UNPROT_DISASSOCIATE) C2S(NL80211_CMD_NEW_PEER_CANDIDATE) C2S(NL80211_CMD_GET_WOWLAN) C2S(NL80211_CMD_SET_WOWLAN) C2S(NL80211_CMD_START_SCHED_SCAN) C2S(NL80211_CMD_STOP_SCHED_SCAN) C2S(NL80211_CMD_SCHED_SCAN_RESULTS) C2S(NL80211_CMD_SCHED_SCAN_STOPPED) C2S(NL80211_CMD_SET_REKEY_OFFLOAD) C2S(NL80211_CMD_PMKSA_CANDIDATE) C2S(NL80211_CMD_TDLS_OPER) C2S(NL80211_CMD_TDLS_MGMT) C2S(NL80211_CMD_UNEXPECTED_FRAME) C2S(NL80211_CMD_PROBE_CLIENT) C2S(NL80211_CMD_REGISTER_BEACONS) C2S(NL80211_CMD_UNEXPECTED_4ADDR_FRAME) C2S(NL80211_CMD_SET_NOACK_MAP) C2S(NL80211_CMD_CH_SWITCH_NOTIFY) C2S(NL80211_CMD_START_P2P_DEVICE) C2S(NL80211_CMD_STOP_P2P_DEVICE) C2S(NL80211_CMD_CONN_FAILED) C2S(NL80211_CMD_SET_MCAST_RATE) C2S(NL80211_CMD_SET_MAC_ACL) C2S(NL80211_CMD_RADAR_DETECT) C2S(NL80211_CMD_GET_PROTOCOL_FEATURES) C2S(NL80211_CMD_UPDATE_FT_IES) C2S(NL80211_CMD_FT_EVENT) C2S(NL80211_CMD_CRIT_PROTOCOL_START) C2S(NL80211_CMD_CRIT_PROTOCOL_STOP) C2S(NL80211_CMD_GET_COALESCE) C2S(NL80211_CMD_SET_COALESCE) C2S(NL80211_CMD_CHANNEL_SWITCH) C2S(NL80211_CMD_VENDOR) C2S(NL80211_CMD_SET_QOS_MAP) default: return "NL80211_CMD_UNKNOWN"; } } const char *attributeToString(int attribute) { switch (attribute) { C2S(NL80211_ATTR_UNSPEC) C2S(NL80211_ATTR_WIPHY) C2S(NL80211_ATTR_WIPHY_NAME) C2S(NL80211_ATTR_IFINDEX) C2S(NL80211_ATTR_IFNAME) C2S(NL80211_ATTR_IFTYPE) C2S(NL80211_ATTR_MAC) C2S(NL80211_ATTR_KEY_DATA) C2S(NL80211_ATTR_KEY_IDX) C2S(NL80211_ATTR_KEY_CIPHER) C2S(NL80211_ATTR_KEY_SEQ) C2S(NL80211_ATTR_KEY_DEFAULT) C2S(NL80211_ATTR_BEACON_INTERVAL) C2S(NL80211_ATTR_DTIM_PERIOD) C2S(NL80211_ATTR_BEACON_HEAD) C2S(NL80211_ATTR_BEACON_TAIL) C2S(NL80211_ATTR_STA_AID) C2S(NL80211_ATTR_STA_FLAGS) C2S(NL80211_ATTR_STA_LISTEN_INTERVAL) C2S(NL80211_ATTR_STA_SUPPORTED_RATES) C2S(NL80211_ATTR_STA_VLAN) C2S(NL80211_ATTR_STA_INFO) C2S(NL80211_ATTR_WIPHY_BANDS) C2S(NL80211_ATTR_MNTR_FLAGS) C2S(NL80211_ATTR_MESH_ID) C2S(NL80211_ATTR_STA_PLINK_ACTION) C2S(NL80211_ATTR_MPATH_NEXT_HOP) C2S(NL80211_ATTR_MPATH_INFO) C2S(NL80211_ATTR_BSS_CTS_PROT) C2S(NL80211_ATTR_BSS_SHORT_PREAMBLE) C2S(NL80211_ATTR_BSS_SHORT_SLOT_TIME) C2S(NL80211_ATTR_HT_CAPABILITY) C2S(NL80211_ATTR_SUPPORTED_IFTYPES) C2S(NL80211_ATTR_REG_ALPHA2) C2S(NL80211_ATTR_REG_RULES) C2S(NL80211_ATTR_MESH_CONFIG) C2S(NL80211_ATTR_BSS_BASIC_RATES) C2S(NL80211_ATTR_WIPHY_TXQ_PARAMS) C2S(NL80211_ATTR_WIPHY_FREQ) C2S(NL80211_ATTR_WIPHY_CHANNEL_TYPE) C2S(NL80211_ATTR_KEY_DEFAULT_MGMT) C2S(NL80211_ATTR_MGMT_SUBTYPE) C2S(NL80211_ATTR_IE) C2S(NL80211_ATTR_MAX_NUM_SCAN_SSIDS) C2S(NL80211_ATTR_SCAN_FREQUENCIES) C2S(NL80211_ATTR_SCAN_SSIDS) C2S(NL80211_ATTR_GENERATION) /* replaces old SCAN_GENERATION */ C2S(NL80211_ATTR_BSS) C2S(NL80211_ATTR_REG_INITIATOR) C2S(NL80211_ATTR_REG_TYPE) C2S(NL80211_ATTR_SUPPORTED_COMMANDS) C2S(NL80211_ATTR_FRAME) C2S(NL80211_ATTR_SSID) C2S(NL80211_ATTR_AUTH_TYPE) C2S(NL80211_ATTR_REASON_CODE) C2S(NL80211_ATTR_KEY_TYPE) C2S(NL80211_ATTR_MAX_SCAN_IE_LEN) C2S(NL80211_ATTR_CIPHER_SUITES) C2S(NL80211_ATTR_FREQ_BEFORE) C2S(NL80211_ATTR_FREQ_AFTER) C2S(NL80211_ATTR_FREQ_FIXED) C2S(NL80211_ATTR_WIPHY_RETRY_SHORT) C2S(NL80211_ATTR_WIPHY_RETRY_LONG) C2S(NL80211_ATTR_WIPHY_FRAG_THRESHOLD) C2S(NL80211_ATTR_WIPHY_RTS_THRESHOLD) C2S(NL80211_ATTR_TIMED_OUT) C2S(NL80211_ATTR_USE_MFP) C2S(NL80211_ATTR_STA_FLAGS2) C2S(NL80211_ATTR_CONTROL_PORT) C2S(NL80211_ATTR_TESTDATA) C2S(NL80211_ATTR_PRIVACY) C2S(NL80211_ATTR_DISCONNECTED_BY_AP) C2S(NL80211_ATTR_STATUS_CODE) C2S(NL80211_ATTR_CIPHER_SUITES_PAIRWISE) C2S(NL80211_ATTR_CIPHER_SUITE_GROUP) C2S(NL80211_ATTR_WPA_VERSIONS) C2S(NL80211_ATTR_AKM_SUITES) C2S(NL80211_ATTR_REQ_IE) C2S(NL80211_ATTR_RESP_IE) C2S(NL80211_ATTR_PREV_BSSID) C2S(NL80211_ATTR_KEY) C2S(NL80211_ATTR_KEYS) C2S(NL80211_ATTR_PID) C2S(NL80211_ATTR_4ADDR) C2S(NL80211_ATTR_SURVEY_INFO) C2S(NL80211_ATTR_PMKID) C2S(NL80211_ATTR_MAX_NUM_PMKIDS) C2S(NL80211_ATTR_DURATION) C2S(NL80211_ATTR_COOKIE) C2S(NL80211_ATTR_WIPHY_COVERAGE_CLASS) C2S(NL80211_ATTR_TX_RATES) C2S(NL80211_ATTR_FRAME_MATCH) C2S(NL80211_ATTR_ACK) C2S(NL80211_ATTR_PS_STATE) C2S(NL80211_ATTR_CQM) C2S(NL80211_ATTR_LOCAL_STATE_CHANGE) C2S(NL80211_ATTR_AP_ISOLATE) C2S(NL80211_ATTR_WIPHY_TX_POWER_SETTING) C2S(NL80211_ATTR_WIPHY_TX_POWER_LEVEL) C2S(NL80211_ATTR_TX_FRAME_TYPES) C2S(NL80211_ATTR_RX_FRAME_TYPES) C2S(NL80211_ATTR_FRAME_TYPE) C2S(NL80211_ATTR_CONTROL_PORT_ETHERTYPE) C2S(NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT) C2S(NL80211_ATTR_SUPPORT_IBSS_RSN) C2S(NL80211_ATTR_WIPHY_ANTENNA_TX) C2S(NL80211_ATTR_WIPHY_ANTENNA_RX) C2S(NL80211_ATTR_MCAST_RATE) C2S(NL80211_ATTR_OFFCHANNEL_TX_OK) C2S(NL80211_ATTR_BSS_HT_OPMODE) C2S(NL80211_ATTR_KEY_DEFAULT_TYPES) C2S(NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION) C2S(NL80211_ATTR_MESH_SETUP) C2S(NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX) C2S(NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX) C2S(NL80211_ATTR_SUPPORT_MESH_AUTH) C2S(NL80211_ATTR_STA_PLINK_STATE) C2S(NL80211_ATTR_WOWLAN_TRIGGERS) C2S(NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED) C2S(NL80211_ATTR_SCHED_SCAN_INTERVAL) C2S(NL80211_ATTR_INTERFACE_COMBINATIONS) C2S(NL80211_ATTR_SOFTWARE_IFTYPES) C2S(NL80211_ATTR_REKEY_DATA) C2S(NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS) C2S(NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN) C2S(NL80211_ATTR_SCAN_SUPP_RATES) C2S(NL80211_ATTR_HIDDEN_SSID) C2S(NL80211_ATTR_IE_PROBE_RESP) C2S(NL80211_ATTR_IE_ASSOC_RESP) C2S(NL80211_ATTR_STA_WME) C2S(NL80211_ATTR_SUPPORT_AP_UAPSD) C2S(NL80211_ATTR_ROAM_SUPPORT) C2S(NL80211_ATTR_SCHED_SCAN_MATCH) C2S(NL80211_ATTR_MAX_MATCH_SETS) C2S(NL80211_ATTR_PMKSA_CANDIDATE) C2S(NL80211_ATTR_TX_NO_CCK_RATE) C2S(NL80211_ATTR_TDLS_ACTION) C2S(NL80211_ATTR_TDLS_DIALOG_TOKEN) C2S(NL80211_ATTR_TDLS_OPERATION) C2S(NL80211_ATTR_TDLS_SUPPORT) C2S(NL80211_ATTR_TDLS_EXTERNAL_SETUP) C2S(NL80211_ATTR_DEVICE_AP_SME) C2S(NL80211_ATTR_DONT_WAIT_FOR_ACK) C2S(NL80211_ATTR_FEATURE_FLAGS) C2S(NL80211_ATTR_PROBE_RESP_OFFLOAD) C2S(NL80211_ATTR_PROBE_RESP) C2S(NL80211_ATTR_DFS_REGION) C2S(NL80211_ATTR_DISABLE_HT) C2S(NL80211_ATTR_HT_CAPABILITY_MASK) C2S(NL80211_ATTR_NOACK_MAP) C2S(NL80211_ATTR_INACTIVITY_TIMEOUT) C2S(NL80211_ATTR_RX_SIGNAL_DBM) C2S(NL80211_ATTR_BG_SCAN_PERIOD) C2S(NL80211_ATTR_WDEV) C2S(NL80211_ATTR_USER_REG_HINT_TYPE) C2S(NL80211_ATTR_CONN_FAILED_REASON) C2S(NL80211_ATTR_SAE_DATA) C2S(NL80211_ATTR_VHT_CAPABILITY) C2S(NL80211_ATTR_SCAN_FLAGS) C2S(NL80211_ATTR_CHANNEL_WIDTH) C2S(NL80211_ATTR_CENTER_FREQ1) C2S(NL80211_ATTR_CENTER_FREQ2) C2S(NL80211_ATTR_P2P_CTWINDOW) C2S(NL80211_ATTR_P2P_OPPPS) C2S(NL80211_ATTR_LOCAL_MESH_POWER_MODE) C2S(NL80211_ATTR_ACL_POLICY) C2S(NL80211_ATTR_MAC_ADDRS) C2S(NL80211_ATTR_MAC_ACL_MAX) C2S(NL80211_ATTR_RADAR_EVENT) C2S(NL80211_ATTR_EXT_CAPA) C2S(NL80211_ATTR_EXT_CAPA_MASK) C2S(NL80211_ATTR_STA_CAPABILITY) C2S(NL80211_ATTR_STA_EXT_CAPABILITY) C2S(NL80211_ATTR_PROTOCOL_FEATURES) C2S(NL80211_ATTR_SPLIT_WIPHY_DUMP) C2S(NL80211_ATTR_DISABLE_VHT) C2S(NL80211_ATTR_VHT_CAPABILITY_MASK) C2S(NL80211_ATTR_MDID) C2S(NL80211_ATTR_IE_RIC) C2S(NL80211_ATTR_CRIT_PROT_ID) C2S(NL80211_ATTR_MAX_CRIT_PROT_DURATION) C2S(NL80211_ATTR_PEER_AID) C2S(NL80211_ATTR_COALESCE_RULE) C2S(NL80211_ATTR_CH_SWITCH_COUNT) C2S(NL80211_ATTR_CH_SWITCH_BLOCK_TX) C2S(NL80211_ATTR_CSA_IES) C2S(NL80211_ATTR_CSA_C_OFF_BEACON) C2S(NL80211_ATTR_CSA_C_OFF_PRESP) C2S(NL80211_ATTR_RXMGMT_FLAGS) C2S(NL80211_ATTR_STA_SUPPORTED_CHANNELS) C2S(NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES) C2S(NL80211_ATTR_HANDLE_DFS) C2S(NL80211_ATTR_SUPPORT_5_MHZ) C2S(NL80211_ATTR_SUPPORT_10_MHZ) C2S(NL80211_ATTR_OPMODE_NOTIF) C2S(NL80211_ATTR_VENDOR_ID) C2S(NL80211_ATTR_VENDOR_SUBCMD) C2S(NL80211_ATTR_VENDOR_DATA) C2S(NL80211_ATTR_VENDOR_EVENTS) C2S(NL80211_ATTR_QOS_MAP) default: return "NL80211_ATTR_UNKNOWN"; } } void WifiEvent::log() { parse(); byte *data = (byte *)genlmsg_attrdata(mHeader, 0); int len = genlmsg_attrlen(mHeader, 0); ALOGD("cmd = %s, len = %d", get_cmdString(), len); ALOGD("vendor_id = %04x, vendor_subcmd = %d", get_vendor_id(), get_vendor_subcmd()); for (int i = 0; i < len; i += 16) { char line[81]; int linelen = min(16, len - i); int offset = 0; appendFmt(line, offset, "%02x", data[i]); for (int j = 1; j < linelen; j++) { appendFmt(line, offset, " %02x", data[i+j]); } for (int j = linelen; j < 16; j++) { appendFmt(line, offset, " "); } line[23] = '-'; appendFmt(line, offset, " "); for (int j = 0; j < linelen; j++) { if (isprint(data[i+j])) { appendFmt(line, offset, "%c", data[i+j]); } else { appendFmt(line, offset, "-"); } } ALOGD("%s", line); } for (unsigned i = 0; i < NL80211_ATTR_MAX_INTERNAL; i++) { if (mAttributes[i] != NULL) { ALOGD("found attribute %s", attributeToString(i)); } } ALOGD("-- End of message --"); } const char *WifiEvent::get_cmdString() { return cmdToString(get_cmd()); } int WifiEvent::parse() { if (mHeader != NULL) { return WIFI_SUCCESS; } mHeader = (genlmsghdr *)nlmsg_data(nlmsg_hdr(mMsg)); int result = nla_parse(mAttributes, NL80211_ATTR_MAX_INTERNAL, genlmsg_attrdata(mHeader, 0), genlmsg_attrlen(mHeader, 0), NULL); // ALOGD("event len = %d", nlmsg_hdr(mMsg)->nlmsg_len); return result; } int WifiRequest::create(int family, uint8_t cmd, int flags, int hdrlen) { mMsg = nlmsg_alloc(); if (mMsg != NULL) { genlmsg_put(mMsg, /* pid = */ 0, /* seq = */ 0, family, hdrlen, flags, cmd, /* version = */ 0); return WIFI_SUCCESS; } else { return WIFI_ERROR_OUT_OF_MEMORY; } } int WifiRequest::create(uint32_t id, int subcmd) { int res = create(NL80211_CMD_VENDOR); if (res < 0) { return res; } res = put_u32(NL80211_ATTR_VENDOR_ID, id); if (res < 0) { return res; } res = put_u32(NL80211_ATTR_VENDOR_SUBCMD, subcmd); if (res < 0) { return res; } if (mIface != -1) { res = set_iface_id(mIface); ALOGD("WifiRequest::create vendor command to iface %d, vendor_id=0x%x, subcmd=0x%04x, res=%d", mIface, id, subcmd, res); } return res; } static int no_seq_check(struct nl_msg *msg, void *arg) { return NL_OK; } int WifiCommand::requestResponse() { int err = create(); if (err < 0) { return err; } return requestResponse(mMsg); } int WifiCommand::requestResponse(WifiRequest& request) { int err = 0; struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT); if (!cb) goto out; /* send message */ err = nl_send_auto_complete(mInfo->cmd_sock, request.getMessage()); if (err < 0) goto out; err = 1; nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL); nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err); nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err); nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err); nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, response_handler, this); /* wait for reply */ while (err > 0) { int res = nl_recvmsgs(mInfo->cmd_sock, cb); if (res) { ALOGE("WifiCommand::requestResponse nl_recvmsgs failed: %d", res); } } if (err) ALOGD("WifiCommand::requestResponse err=%d", err); out: nl_cb_put(cb); return err; } int WifiCommand::requestEvent(int cmd) { ALOGD("WifiCommand::requestEvent for cmd %d", cmd); int res = wifi_register_handler(wifiHandle(), cmd, event_handler, this); if (res < 0) { return res; } res = create(); if (res < 0) goto out; res = nl_send_auto_complete(mInfo->cmd_sock, mMsg.getMessage()); if (res < 0) goto out; ALOGD("WifiCommand::requestEvent waiting for event"); res = mCondition.wait(); if (res < 0) goto out; out: wifi_unregister_handler(wifiHandle(), cmd); return res; } int WifiCommand::requestVendorEvent(uint32_t id, int subcmd) { int res = wifi_register_vendor_handler(wifiHandle(), id, subcmd, event_handler, this); if (res < 0) { return res; } res = create(); if (res < 0) goto out; res = nl_send_auto_complete(mInfo->cmd_sock, mMsg.getMessage()); if (res < 0) goto out; res = mCondition.wait(); if (res < 0) goto out; out: wifi_unregister_vendor_handler(wifiHandle(), id, subcmd); return res; } ////////////////////////////////////////////////////////////////////////// // Event handlers int WifiCommand::response_handler(struct nl_msg *msg, void *arg) { // ALOGD("response_handler called"); WifiCommand *cmd = (WifiCommand *)arg; WifiEvent reply(msg); int res = reply.parse(); if (res < 0) { ALOGE("Failed to parse reply message = %d", res); return NL_SKIP; } else { // reply.log(); return cmd->handleResponse(reply); } } int WifiCommand::event_handler(struct nl_msg *msg, void *arg) { WifiCommand *cmd = (WifiCommand *)arg; WifiEvent event(msg); int res = event.parse(); if (res < 0) { ALOGE("Failed to parse event = %d", res); res = NL_SKIP; } else { res = cmd->handleEvent(event); } cmd->mCondition.signal(); return res; } int WifiCommand::valid_handler(struct nl_msg *msg, void *arg) { // ALOGD("valid_handler called"); int *err = (int *)arg; *err = 0; return NL_SKIP; } int WifiCommand::ack_handler(struct nl_msg *msg, void *arg) { // ALOGD("ack_handler called"); int *err = (int *)arg; *err = 0; return NL_STOP; } int WifiCommand::finish_handler(struct nl_msg *msg, void *arg) { // ALOGD("finish_handler called"); int *ret = (int *)arg; *ret = 0; return NL_SKIP; } int WifiCommand::error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) { int *ret = (int *)arg; *ret = err->error; // ALOGD("error_handler called, err->error=%d", err->error); return NL_SKIP; }
23.585034
102
0.74664
[ "object" ]
82a1fe9608c936e2357ffe9e2447d2b3ee256e4a
2,531
cpp
C++
src/metaspades/src/common/adt/concurrent_dsu.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/common/adt/concurrent_dsu.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/common/adt/concurrent_dsu.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
2
2021-06-05T07:40:20.000Z
2021-06-05T08:02:58.000Z
//*************************************************************************** //* Copyright (c) 2019 Saint Petersburg State University //* All Rights Reserved //* See file LICENSE for details. //*************************************************************************** #include "concurrent_dsu.hpp" #include "io/kmers/mmapped_writer.hpp" #include "utils/logger/logger.hpp" #include <parallel_hashmap/phmap.h> #include <fstream> namespace dsu { size_t ConcurrentDSU::extract_to_file(const std::string &Prefix) { INFO("Connecting to root"); // First, touch all the sets to make them directly connect to the root # pragma omp parallel for for (size_t x = 0; x < data_.size(); ++x) (void) find_set(x); phmap::flat_hash_map<size_t, size_t> sizes; #if 0 for (size_t x = 0; x < size; ++x) { if (data_[x].parent != x) { size_t t = data_[x].parent; VERIFY(data_[t].parent == t) } } #endif INFO("Calculating counts"); // Insert all the root elements into the map sizes.reserve(num_sets()); for (size_t x = 0; x < data_.size(); ++x) { if (is_root(x)) sizes[x] = 0; } // Now, calculate the counts. We can do this in parallel, because we know no // insertion can occur. # pragma omp parallel for for (size_t x = 0; x < data_.size(); ++x) { size_t &entry = sizes[parent(x)]; # pragma omp atomic entry += 1; } // Now we know the sizes of each cluster. Go over again and calculate the // file-relative (cumulative) offsets. size_t off = 0; for (size_t x = 0; x < data_.size(); ++x) { if (is_root(x)) { size_t &entry = sizes[x]; size_t noff = off + entry; entry = off; off = noff; } } INFO("Writing down entries"); // Write down the entries std::vector<size_t> out(off); for (size_t x = 0; x < data_.size(); ++x) { size_t &entry = sizes[parent(x)]; out[entry++] = x; } std::ofstream os(Prefix, std::ios::binary | std::ios::out); os.write((char *) &out[0], out.size() * sizeof(out[0])); os.close(); // Write down the sizes MMappedRecordWriter <size_t> index(Prefix + ".idx"); index.reserve(sizes.size()); size_t *idx = index.data(); for (size_t x = 0, i = 0, sz = 0; x < data_.size(); ++x) { if (is_root(x)) { idx[i++] = sizes[x] - sz; sz = sizes[x]; } } return sizes.size(); } }
28.438202
80
0.525879
[ "vector" ]
82a3cb935e07a2529510da3b555f4c202d8ee2ea
4,425
cc
C++
3rdparty/rpcz/src/rpcz/zmq_utils.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
1
2016-05-10T16:06:42.000Z
2016-05-10T16:06:42.000Z
3rdparty/rpcz/src/rpcz/zmq_utils.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
null
null
null
3rdparty/rpcz/src/rpcz/zmq_utils.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
null
null
null
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: nadavs@google.com <Nadav Samet> #include "rpcz/zmq_utils.hpp" #include <boost/functional/hash.hpp> #include <sstream> #include <stddef.h> #include <string.h> #include <zmq.h> #include <ostream> #include <string> #include <vector> #include "google/protobuf/stubs/common.h" #include "zmq.hpp" #include "rpcz/logging.hpp" #include "rpcz/macros.hpp" #ifdef _MSC_VER #pragma warning( disable : 4018 ) // 'expression' : signed/unsigned mismatch #endif namespace rpcz { std::string message_to_string(zmq::message_t& msg) { return std::string((char*)msg.data(), msg.size()); } zmq::message_t* string_to_message(const std::string& str) { zmq::message_t* message = new zmq::message_t(str.length()); memcpy(message->data(), str.c_str(), str.length()); return message; } bool read_message_to_vector(zmq::socket_t* socket, message_vector* data) { while (1) { zmq::message_t *msg = new zmq::message_t; socket->recv(msg, 0); int64_t more = 0; // Multipart detection size_t more_size = sizeof (more); socket->getsockopt(ZMQ_RCVMORE, &more, &more_size); data->push_back(msg); if (!more) { break; } } return true; } bool read_message_to_vector(zmq::socket_t* socket, message_vector* routes, message_vector* data) { bool first_part = true; while (1) { zmq::message_t *msg = new zmq::message_t; socket->recv(msg, 0); int64_t more = 0; // Multipart detection size_t more_size = sizeof(more); socket->getsockopt(ZMQ_RCVMORE, &more, &more_size); if (first_part) { routes->push_back(msg); if (msg->size() == 0) { first_part = false; } } else { data->push_back(msg); } if (!more) { return !first_part; } } } void write_vector_to_socket(zmq::socket_t* socket, message_vector& data, int flags) { for (size_t i = 0; i < data.size(); ++i) { socket->send(data[i], flags | ((i < data.size() - 1) ? ZMQ_SNDMORE : 0)); } } void write_vectors_to_socket(zmq::socket_t* socket, message_vector& routes, message_vector& data) { CHECK_GE(data.size(), 1u); write_vector_to_socket(socket, routes, ZMQ_SNDMORE); write_vector_to_socket(socket, data, 0); } bool send_empty_message(zmq::socket_t* socket, int flags) { zmq::message_t message(0); return socket->send(message, flags); } bool send_string(zmq::socket_t* socket, const std::string& str, int flags) { zmq::message_t msg(str.size()); str.copy((char*)msg.data(), str.size(), 0); return socket->send(msg, flags); } bool send_uint64(zmq::socket_t* socket, google::protobuf::uint64 value, int flags) { zmq::message_t msg(8); memcpy(msg.data(), &value, 8); return socket->send(msg, flags); } bool forward_message(zmq::socket_t &socket_in, zmq::socket_t &socket_out) { message_vector routes; message_vector data; CHECK(!read_message_to_vector(&socket_in, &routes, &data)); write_vector_to_socket(&socket_out, routes); return true; } void log_message_vector(message_vector& vector) { LOG(INFO) << "---- " << static_cast<int>(vector.size()) << "----"; boost::hash<std::string> hash; for (int i = 0; i < vector.size(); ++i) { std::string message(message_to_string(vector[i])); std::stringstream ss; ss << std::hex << hash(message); LOG(INFO) << "(" << static_cast<int>(vector[i].size()) << "): " << "[" << ss.str() << "]: " << message_to_string(vector[i]); } LOG(INFO) << "----------"; } } // namespace
29.5
86
0.614011
[ "vector" ]
82a3f3aa03f4b21ff677ddeacdadfbbeb6ff3624
1,730
cpp
C++
aws-cpp-sdk-route53-recovery-control-config/source/model/GatingRuleUpdate.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-route53-recovery-control-config/source/model/GatingRuleUpdate.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-route53-recovery-control-config/source/model/GatingRuleUpdate.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/route53-recovery-control-config/model/GatingRuleUpdate.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Route53RecoveryControlConfig { namespace Model { GatingRuleUpdate::GatingRuleUpdate() : m_nameHasBeenSet(false), m_safetyRuleArnHasBeenSet(false), m_waitPeriodMs(0), m_waitPeriodMsHasBeenSet(false) { } GatingRuleUpdate::GatingRuleUpdate(JsonView jsonValue) : m_nameHasBeenSet(false), m_safetyRuleArnHasBeenSet(false), m_waitPeriodMs(0), m_waitPeriodMsHasBeenSet(false) { *this = jsonValue; } GatingRuleUpdate& GatingRuleUpdate::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("SafetyRuleArn")) { m_safetyRuleArn = jsonValue.GetString("SafetyRuleArn"); m_safetyRuleArnHasBeenSet = true; } if(jsonValue.ValueExists("WaitPeriodMs")) { m_waitPeriodMs = jsonValue.GetInteger("WaitPeriodMs"); m_waitPeriodMsHasBeenSet = true; } return *this; } JsonValue GatingRuleUpdate::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_safetyRuleArnHasBeenSet) { payload.WithString("SafetyRuleArn", m_safetyRuleArn); } if(m_waitPeriodMsHasBeenSet) { payload.WithInteger("WaitPeriodMs", m_waitPeriodMs); } return payload; } } // namespace Model } // namespace Route53RecoveryControlConfig } // namespace Aws
18.804348
71
0.730058
[ "model" ]
82aaaf7bb9a56032bb998680376f671a8e899a1d
11,200
cpp
C++
intern/iksolver/intern/IK_QJacobian.cpp
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
365
2015-02-10T15:10:55.000Z
2022-03-03T15:50:51.000Z
intern/iksolver/intern/IK_QJacobian.cpp
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
45
2015-01-09T15:34:20.000Z
2021-10-05T14:44:23.000Z
intern/iksolver/intern/IK_QJacobian.cpp
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
172
2015-01-25T15:16:53.000Z
2022-01-31T08:25:36.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. */ /** \file * \ingroup iksolver */ #include "IK_QJacobian.h" IK_QJacobian::IK_QJacobian() : m_sdls(true), m_min_damp(1.0) { } IK_QJacobian::~IK_QJacobian() { } void IK_QJacobian::ArmMatrices(int dof, int task_size) { m_dof = dof; m_task_size = task_size; m_jacobian.resize(task_size, dof); m_jacobian.setZero(); m_alpha.resize(dof); m_alpha.setZero(); m_nullspace.resize(dof, dof); m_d_theta.resize(dof); m_d_theta_tmp.resize(dof); m_d_norm_weight.resize(dof); m_norm.resize(dof); m_norm.setZero(); m_beta.resize(task_size); m_weight.resize(dof); m_weight_sqrt.resize(dof); m_weight.setOnes(); m_weight_sqrt.setOnes(); if (task_size >= dof) { m_transpose = false; m_jacobian_tmp.resize(task_size, dof); m_svd_u.resize(task_size, dof); m_svd_v.resize(dof, dof); m_svd_w.resize(dof); m_svd_u_beta.resize(dof); } else { // use the SVD of the transpose jacobian, it works just as well // as the original, and often allows using smaller matrices. m_transpose = true; m_jacobian_tmp.resize(dof, task_size); m_svd_u.resize(task_size, task_size); m_svd_v.resize(dof, task_size); m_svd_w.resize(task_size); m_svd_u_beta.resize(task_size); } } void IK_QJacobian::SetBetas(int id, int, const Vector3d &v) { m_beta[id + 0] = v.x(); m_beta[id + 1] = v.y(); m_beta[id + 2] = v.z(); } void IK_QJacobian::SetDerivatives(int id, int dof_id, const Vector3d &v, double norm_weight) { m_jacobian(id + 0, dof_id) = v.x() * m_weight_sqrt[dof_id]; m_jacobian(id + 1, dof_id) = v.y() * m_weight_sqrt[dof_id]; m_jacobian(id + 2, dof_id) = v.z() * m_weight_sqrt[dof_id]; m_d_norm_weight[dof_id] = norm_weight; } void IK_QJacobian::Invert() { if (m_transpose) { // SVD will decompose Jt into V*W*Ut with U,V orthogonal and W diagonal, // so J = U*W*Vt and Jinv = V*Winv*Ut Eigen::JacobiSVD<MatrixXd> svd(m_jacobian.transpose(), Eigen::ComputeThinU | Eigen::ComputeThinV); m_svd_u = svd.matrixV(); m_svd_w = svd.singularValues(); m_svd_v = svd.matrixU(); } else { // SVD will decompose J into U*W*Vt with U,V orthogonal and W diagonal, // so Jinv = V*Winv*Ut Eigen::JacobiSVD<MatrixXd> svd(m_jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV); m_svd_u = svd.matrixU(); m_svd_w = svd.singularValues(); m_svd_v = svd.matrixV(); } if (m_sdls) InvertSDLS(); else InvertDLS(); } bool IK_QJacobian::ComputeNullProjection() { double epsilon = 1e-10; // compute null space projection based on V int i, j, rank = 0; for (i = 0; i < m_svd_w.size(); i++) if (m_svd_w[i] > epsilon) rank++; if (rank < m_task_size) return false; MatrixXd basis(m_svd_v.rows(), rank); int b = 0; for (i = 0; i < m_svd_w.size(); i++) if (m_svd_w[i] > epsilon) { for (j = 0; j < m_svd_v.rows(); j++) basis(j, b) = m_svd_v(j, i); b++; } m_nullspace = basis * basis.transpose(); for (i = 0; i < m_nullspace.rows(); i++) for (j = 0; j < m_nullspace.cols(); j++) if (i == j) m_nullspace(i, j) = 1.0 - m_nullspace(i, j); else m_nullspace(i, j) = -m_nullspace(i, j); return true; } void IK_QJacobian::SubTask(IK_QJacobian &jacobian) { if (!ComputeNullProjection()) return; // restrict lower priority jacobian jacobian.Restrict(m_d_theta, m_nullspace); // add angle update from lower priority jacobian.Invert(); // note: now damps secondary angles with minimum damping value from // SDLS, to avoid shaking when the primary task is near singularities, // doesn't work well at all int i; for (i = 0; i < m_d_theta.size(); i++) m_d_theta[i] = m_d_theta[i] + /*m_min_damp * */ jacobian.AngleUpdate(i); } void IK_QJacobian::Restrict(VectorXd &d_theta, MatrixXd &nullspace) { // subtract part already moved by higher task from beta m_beta = m_beta - m_jacobian * d_theta; // note: should we be using the norm of the unrestricted jacobian for SDLS? // project jacobian on to null space of higher priority task m_jacobian = m_jacobian * nullspace; } void IK_QJacobian::InvertSDLS() { // Compute the dampeds least squeares pseudo inverse of J. // // Since J is usually not invertible (most of the times it's not even // square), the psuedo inverse is used. This gives us a least squares // solution. // // This is fine when the J*Jt is of full rank. When J*Jt is near to // singular the least squares inverse tries to minimize |J(dtheta) - dX)| // and doesn't try to minimize dTheta. This results in eratic changes in // angle. The damped least squares minimizes |dtheta| to try and reduce this // erratic behavior. // // The selectively damped least squares (SDLS) is used here instead of the // DLS. The SDLS damps individual singular values, instead of using a single // damping term. double max_angle_change = M_PI / 4.0; double epsilon = 1e-10; int i, j; m_d_theta.setZero(); m_min_damp = 1.0; for (i = 0; i < m_dof; i++) { m_norm[i] = 0.0; for (j = 0; j < m_task_size; j += 3) { double n = 0.0; n += m_jacobian(j, i) * m_jacobian(j, i); n += m_jacobian(j + 1, i) * m_jacobian(j + 1, i); n += m_jacobian(j + 2, i) * m_jacobian(j + 2, i); m_norm[i] += sqrt(n); } } for (i = 0; i < m_svd_w.size(); i++) { if (m_svd_w[i] <= epsilon) continue; double wInv = 1.0 / m_svd_w[i]; double alpha = 0.0; double N = 0.0; // compute alpha and N for (j = 0; j < m_svd_u.rows(); j += 3) { alpha += m_svd_u(j, i) * m_beta[j]; alpha += m_svd_u(j + 1, i) * m_beta[j + 1]; alpha += m_svd_u(j + 2, i) * m_beta[j + 2]; // note: for 1 end effector, N will always be 1, since U is // orthogonal, .. so could be optimized double tmp; tmp = m_svd_u(j, i) * m_svd_u(j, i); tmp += m_svd_u(j + 1, i) * m_svd_u(j + 1, i); tmp += m_svd_u(j + 2, i) * m_svd_u(j + 2, i); N += sqrt(tmp); } alpha *= wInv; // compute M, dTheta and max_dtheta double M = 0.0; double max_dtheta = 0.0, abs_dtheta; for (j = 0; j < m_d_theta.size(); j++) { double v = m_svd_v(j, i); M += fabs(v) * m_norm[j]; // compute tmporary dTheta's m_d_theta_tmp[j] = v * alpha; // find largest absolute dTheta // multiply with weight to prevent unnecessary damping abs_dtheta = fabs(m_d_theta_tmp[j]) * m_weight_sqrt[j]; if (abs_dtheta > max_dtheta) max_dtheta = abs_dtheta; } M *= wInv; // compute damping term and damp the dTheta's double gamma = max_angle_change; if (N < M) gamma *= N / M; double damp = (gamma < max_dtheta) ? gamma / max_dtheta : 1.0; for (j = 0; j < m_d_theta.size(); j++) { // slight hack: we do 0.80*, so that if there is some oscillation, // the system can still converge (for joint limits). also, it's // better to go a little to slow than to far double dofdamp = damp / m_weight[j]; if (dofdamp > 1.0) dofdamp = 1.0; m_d_theta[j] += 0.80 * dofdamp * m_d_theta_tmp[j]; } if (damp < m_min_damp) m_min_damp = damp; } // weight + prevent from doing angle updates with angles > max_angle_change double max_angle = 0.0, abs_angle; for (j = 0; j < m_dof; j++) { m_d_theta[j] *= m_weight[j]; abs_angle = fabs(m_d_theta[j]); if (abs_angle > max_angle) max_angle = abs_angle; } if (max_angle > max_angle_change) { double damp = (max_angle_change) / (max_angle_change + max_angle); for (j = 0; j < m_dof; j++) m_d_theta[j] *= damp; } } void IK_QJacobian::InvertDLS() { // Compute damped least squares inverse of pseudo inverse // Compute damping term lambda // Note when lambda is zero this is equivalent to the // least squares solution. This is fine when the m_jjt is // of full rank. When m_jjt is near to singular the least squares // inverse tries to minimize |J(dtheta) - dX)| and doesn't // try to minimize dTheta. This results in eratic changes in angle. // Damped least squares minimizes |dtheta| to try and reduce this // erratic behavior. // We don't want to use the damped solution everywhere so we // only increase lamda from zero as we approach a singularity. // find the smallest non-zero W value, anything below epsilon is // treated as zero double epsilon = 1e-10; double max_angle_change = 0.1; double x_length = sqrt(m_beta.dot(m_beta)); int i, j; double w_min = std::numeric_limits<double>::max(); for (i = 0; i < m_svd_w.size(); i++) { if (m_svd_w[i] > epsilon && m_svd_w[i] < w_min) w_min = m_svd_w[i]; } // compute lambda damping term double d = x_length / max_angle_change; double lambda; if (w_min <= d / 2) lambda = d / 2; else if (w_min < d) lambda = sqrt(w_min * (d - w_min)); else lambda = 0.0; lambda *= lambda; if (lambda > 10) lambda = 10; // immediately multiply with Beta, so we can do matrix*vector products // rather than matrix*matrix products // compute Ut*Beta m_svd_u_beta = m_svd_u.transpose() * m_beta; m_d_theta.setZero(); for (i = 0; i < m_svd_w.size(); i++) { if (m_svd_w[i] > epsilon) { double wInv = m_svd_w[i] / (m_svd_w[i] * m_svd_w[i] + lambda); // compute V*Winv*Ut*Beta m_svd_u_beta[i] *= wInv; for (j = 0; j < m_d_theta.size(); j++) m_d_theta[j] += m_svd_v(j, i) * m_svd_u_beta[i]; } } for (j = 0; j < m_d_theta.size(); j++) m_d_theta[j] *= m_weight[j]; } void IK_QJacobian::Lock(int dof_id, double delta) { int i; for (i = 0; i < m_task_size; i++) { m_beta[i] -= m_jacobian(i, dof_id) * delta; m_jacobian(i, dof_id) = 0.0; } m_norm[dof_id] = 0.0; // unneeded m_d_theta[dof_id] = 0.0; } double IK_QJacobian::AngleUpdate(int dof_id) const { return m_d_theta[dof_id]; } double IK_QJacobian::AngleUpdateNorm() const { int i; double mx = 0.0, dtheta_abs; for (i = 0; i < m_d_theta.size(); i++) { dtheta_abs = fabs(m_d_theta[i] * m_d_norm_weight[i]); if (dtheta_abs > mx) mx = dtheta_abs; } return mx; } void IK_QJacobian::SetDoFWeight(int dof, double weight) { m_weight[dof] = weight; m_weight_sqrt[dof] = sqrt(weight); }
26.29108
92
0.632143
[ "vector" ]
82adb334209edc54b403d9cbdec0032fd35fee27
1,606
cpp
C++
Codeforces/Rounds/Codeforces Round #222 (Div. 1)/A(dfs).cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
Codeforces/Rounds/Codeforces Round #222 (Div. 1)/A(dfs).cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
Codeforces/Rounds/Codeforces Round #222 (Div. 1)/A(dfs).cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
/** * author: MaGnsi0 * created: 05/06/2021 20:14:32 **/ #include <bits/stdc++.h> using namespace std; void dfs(int n, int m, int k, int s, vector<vector<char>>& g, vector<vector<bool>>& v, int x, int y) { static int cc = 0; static int dx[] = {-1, 0, 0, 1}; static int dy[] = {0, -1, 1, 0}; if (cc == s - k) { return; } v[x][y] = true; g[x][y] = '.'; cc++; for (int i = 0; i < 4; ++i) { if (x + dx[i] < 0 || x + dx[i] >= n) { continue; } if (y + dy[i] < 0 || y + dy[i] >= m) { continue; } if (v[x + dx[i]][y + dy[i]] || g[x + dx[i]][y + dy[i]] != 'X') { continue; } dfs(n, m, k, s, g, v, x + dx[i], y + dy[i]); } } int main() { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int n, m, k, s = 0; cin >> n >> m >> k; vector<vector<char>> g(n, vector<char>(m)); vector<vector<bool>> v(n, vector<bool>(m, false)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> g[i][j]; if (g[i][j] == '#') { v[i][j] = true; } else { g[i][j] = 'X'; s++; } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (g[i][j] == 'X') { dfs(n, m, k, s, g, v, i, j); break; } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cout << g[i][j]; } cout << "\n"; } }
25.09375
102
0.339352
[ "vector" ]
82b111a8660d1aedd26aafb280043c6d659a32ab
7,784
cpp
C++
source/fonts/character.cpp
graham-riches/led-matrix
31e570732a8acdcfb3ea35b21fb96286aa8cd22a
[ "MIT" ]
null
null
null
source/fonts/character.cpp
graham-riches/led-matrix
31e570732a8acdcfb3ea35b21fb96286aa8cd22a
[ "MIT" ]
null
null
null
source/fonts/character.cpp
graham-riches/led-matrix
31e570732a8acdcfb3ea35b21fb96286aa8cd22a
[ "MIT" ]
null
null
null
/** * \file character.cpp * \author Graham Riches (graham.riches@live.com) * \brief method declarations for character objects * \version 0.1 * \date 2021-02-06 * * @copyright Copyright (c) 2021 * */ /********************************** Includes *******************************************/ #include "font.hpp" #include "range/v3/all.hpp" #include "string_utilities.hpp" #include <fstream> #include <iostream> #include <sstream> #include <string> #include <charconv> /********************************** Constants *******************************************/ #define INTEGER_HEX_BASE (16ul) namespace fonts { /********************************** Local Function Definitions *******************************************/ /** * \brief convert a stringview into an int representation * * \param view the string view * \param base the integer base of the number. Defaults to a base 10 int * \retval int integer value of the string */ template <typename T> T stringview_to_int(const std::string_view& view, int base = 10) { T value; std::from_chars(view.data(), view.data() + view.size(), value, base); return value; } /** * \brief convert a stringview into a keyvalue pair containing integers * * \param view the string view * \retval key_value_pair<int> key-value pair object */ key_value_pair<int> to_property_kv_pair(const std::string_view& view) { auto tokens = view | ranges::views::split(' ') | ranges::views::transform([](auto&& range) { return std::string_view(&*range.begin(), ranges::distance(range)); }) | ranges::to_vector; auto values = tokens | ranges::views::drop(1) | ranges::views::transform([](auto &&item){ return stringview_to_int<int>(item); }) | ranges::to_vector; return key_value_pair<int>{tokens[0], values}; } /** * \brief converts a vector of keyvalue pair objects into a std::map * * \param pairs vector of pairs * \retval std::map<std::stringview, std::vector<int>> */ std::map<std::string_view, std::vector<int>> kv_pairs_to_map(const std::vector<key_value_pair<int>>& pairs) { std::map<std::string_view, std::vector<int>> map; for (const auto& pair : pairs) { map.insert(std::make_pair(pair.key, pair.values)); } return map; } /********************************** Public Function Definitions *******************************************/ /** * \brief factor method to create a bounding box object from a string view * * \param view the string view to create the box from * \retval expected<bounding_box, std::string> containing either the box, or an error message */ expected<bounding_box, std::string> bounding_box::from_stringview(const std::string_view& view) { key_value_pair<int> kv_pair = to_property_kv_pair(view); return bounding_box::from_key_value_pair(kv_pair); } /** * \brief factory method to create a bounding box from a key_value pair object * * \param kv_pair the key_value pair object * \retval expected<bounding_box, std::string> bounding box object if no errors, otherwise error string */ expected<bounding_box, std::string> bounding_box::from_key_value_pair(const key_value_pair<int>& kv_pair) { return (kv_pair.key != "BBX") ? expected<bounding_box, std::string>::error("Invalid key for constructor") : (kv_pair.values.size() != 4) ? expected<bounding_box, std::string>::error("BoundingBox: not enough arguments supplied") : expected<bounding_box, std::string>::success(bounding_box(kv_pair.values[0], kv_pair.values[1], kv_pair.values[2], kv_pair.values[3])); } /** * \brief factory method to create a character properties structure from a map * * \param map the map containing the property tags as keys and the values as fields * \retval expected<character_properties, std::string> */ expected<character_properties, std::string> character_properties::from_map(const std::map<std::string_view, std::vector<int>>& map) { try { auto scalable_width = std::make_pair<uint16_t, uint16_t>(map.at("SWIDTH")[0], map.at("SWIDTH")[1]); auto device_width = std::make_pair<uint8_t, uint8_t>(map.at("DWIDTH")[0], map.at("DWIDTH")[1]); auto encoding = map.at("ENCODING")[0]; auto maybe_b_box = bounding_box::from_key_value_pair(key_value_pair<int>{"BBX", map.at("BBX")}); //!< check the bounding box parsed successfully if (!maybe_b_box) { return expected<character_properties, std::string>::error(maybe_b_box.get_error()); } character_properties properties(encoding, scalable_width, device_width, maybe_b_box.get_value()); return expected<character_properties, std::string>::success(std::move(properties)); } catch (...) { return expected<character_properties, std::string>::error("failed to create character properties"); } } /** * \brief convert a vector of lines into a character structure * * \param encoding character encoded as a string * \retval expected<character, std::string> expected of character or an error */ expected<character, std::string> character::from_string(const std::string& encoding) { //!< splits the string by endlines, converts to string views, and splits into two ranges containing: properties, character bitmapping auto properties = encoding | ranges::views::split('\n') | ranges::views::transform([](auto&& range) { return std::string_view(&*range.begin(), ranges::distance(range)); }) | ranges::views::filter([](auto&& line){ return line != "ENDCHAR";}) | ranges::views::filter([](auto&& line){ return line.find(std::string_view{"STARTCHAR"}) == line.npos; }) | ranges::views::filter([](auto&& line){ return line != "";}) | ranges::views::split("BITMAP") | ranges::views::transform([](auto&& range){return range | ranges::to_vector; }) | ranges::to_vector; //!< check to make sure we got the correct set of values: TODO: not 100% sold on the hard-coded 2 but maybe it makes sense here? if (properties.size() != 2) { return expected<character, std::string>::error("Invalid character encoding: missing either bit encoding or character properties"); } //!< parse the properties and return an error if the property parsing failed auto property_fields = properties[0] | ranges::views::transform(to_property_kv_pair) | ranges::to_vector; auto maybe_properties = character_properties::from_map(kv_pairs_to_map(property_fields)); if (!maybe_properties) { return expected<character, std::string>::error(maybe_properties.get_error()); } //!< extract the properties struct from the expected auto c_properties = maybe_properties.get_value(); //!< parse the bitmap character encoding auto bit_encoding = properties[1] | ranges::views::transform([](auto &&view){return stringview_to_int<uint32_t>(view, INTEGER_HEX_BASE);}) | ranges::to_vector; //!< check to make sure there are enough rows in the bitmap to match the bounding box height if (bit_encoding.size() != c_properties.b_box.height ) { return expected<character, std::string>::error("Not enough bitmapped rows for the character type"); } //!< return the character object return expected<character, std::string>::success(character{std::move(c_properties), std::move(bit_encoding)}); } }; // namespace fonts
43.977401
186
0.628854
[ "object", "vector", "transform" ]
a118ba4346c4c98fae20b1916e026024ff656292
2,245
cpp
C++
hdu-winter-2020/problems/分块,莫队/1002.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
hdu-winter-2020/problems/分块,莫队/1002.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
hdu-winter-2020/problems/分块,莫队/1002.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<vector> #include<queue> #include<cmath> #include<map> #include<set> #define ll long long #define F(i,a,b) for(int i=(a);i<=(b);i++) #define mst(a,b) memset((a),(b),sizeof(a)) #define PII pair<int,int> #define rep(i,x,y) for(auto i=(x);i<=(y);++i) #define dep(i,x,y) for(auto i=(x);i>=(y);--i) using namespace std; template<class T>inline void rd(T &x) { x=0; int ch=getchar(),f=0; while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} if(f)x=-x; } const int inf=0x3f3f3f3f; const int maxn=30050; const ll p=1000000007; ll T,n,m,a[maxn],c[maxn],cnt[maxn],num,res,inv[maxn]; ll ksm(ll a,ll b) { ll res=1%p; while(b) { if(b&1) res=(res*a)%p; a=(a*a)%p; b>>=1; } return res; } struct node { int l,r,id,ans; bool operator<(const node &t) const{ if(c[l]==c[t.l]) return r<t.r; return c[l]<c[t.l]; } }q[maxn]; void add(ll x) { cnt[a[x]]++; num++; res=(res*num)%p; res=(res*inv[cnt[a[x]]])%p; } void del(ll x) { res=(res*cnt[a[x]])%p; res=(res*inv[num])%p; num--;cnt[a[x]]--; } bool cmp(const node&t1,const node&t2){ return t1.id<t2.id; } int main() { cin>>T; while(T--) { cin>>n>>m; mst(cnt,0); res=1;num=0; rep(i,1,n) { rd(a[i]); inv[i]=ksm(i,p-2); } int t=ceil(sqrt(n)); rep(i,1,n) c[i]=(i-1)/t; rep(i,1,m) rd(q[i].l),rd(q[i].r),q[i].id=i; sort(q+1,q+m+1); ll l,r;l=r=1; add(1); for(int i=1;i<=m;i++) { while(r<q[i].r) { r++; add(r); } while(r>q[i].r) { del(r); r--; } while(l<q[i].l) { del(l); l++; } while(l>q[i].l) { l--; add(l); } q[i].ans=res; } sort(q+1,q+m+1,cmp); rep(i,1,m) cout<<q[i].ans<<endl; } return 0; }
20.59633
67
0.423608
[ "vector" ]
a1273b0f7e1083a1dbc09fe66259c7fbcc60ef25
10,575
cpp
C++
legacy/libopensharding/src/logger/Logger.cpp
AgilData/open-sharding
7dcf5fe11d0184518fc63c1591e67fa0ffccf011
[ "Apache-2.0" ]
null
null
null
legacy/libopensharding/src/logger/Logger.cpp
AgilData/open-sharding
7dcf5fe11d0184518fc63c1591e67fa0ffccf011
[ "Apache-2.0" ]
null
null
null
legacy/libopensharding/src/logger/Logger.cpp
AgilData/open-sharding
7dcf5fe11d0184518fc63c1591e67fa0ffccf011
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2011, CodeFutures Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <time.h> #include <map> #include <syslog.h> #include <logger/Logger.h> using namespace std; namespace logger { static LoggerGlobalState *__loggerGlobalState__ = NULL; // get process-id and thread-id string getPidTid() { char temp[256]; #ifdef __APPLE__ sprintf(temp, "[PID:N/A]"); #else sprintf(temp, "[PID:%d] [TID:%u]", getpid(), (unsigned int)pthread_self()); #endif return string(temp); } LoggerGlobalState *__logger__getGlobalState() { //TODO: use mutex if (!__loggerGlobalState__) { //cerr << getPidTid() << " Logger creating LoggerGlobalState object" << endl; __loggerGlobalState__ = new LoggerGlobalState(); } return __loggerGlobalState__; } // MACRO for readable code #define LOGGER_GLOBAL_STATE __logger__getGlobalState() ////////////////////////////// // // STATIC METHODS // ////////////////////////////// /*static*/ Logger &Logger::getLogger(string name) { return *getLoggerPtr(name); } /*static*/ Logger *Logger::getLoggerPtr(string name) { //cerr << getPidTid() << " Logger::getLogger(" << name << ")" << endl; Logger *logger = LOGGER_GLOBAL_STATE->loggerMap[name]; if (!logger) { // get log level from map string levelName = LOGGER_GLOBAL_STATE->logLevelMap[name]; // convert level name to int int level = LOG_LEVEL_NONE; if (levelName == "TRACE") { level = LOG_LEVEL_TRACE; } else if (levelName == "DEBUG") { level = LOG_LEVEL_DEBUG; } else if (levelName == "INFO") { level = LOG_LEVEL_INFO; } else if (levelName == "WARN") { level = LOG_LEVEL_WARN; } else if (levelName == "ERROR") { level = LOG_LEVEL_ERROR; } else { // default level = LOG_LEVEL_INFO; } // create new Logger instance logger = new Logger(name, level); // store logger in map LOGGER_GLOBAL_STATE->loggerMap[name] = logger; } char temp[256]; sprintf(temp, "%p", (void*) logger); //cerr << getPidTid() << " Logger::getLogger(" << name << ") returning " << temp << endl; return logger; } /** * Configure logging from log.properties file, each line in the file is either: * - Blank line * - Comment (starts with #) * - Log level setting in format NAME=LEVEL where LEVEL is one of TRACE,DEBUG,INFO,WARN,ERROR */ /*static*/ void Logger::configure(string filename) { //cerr << getPidTid() << " Logger::configure(" << filename << ")" << endl; string line; ifstream myfile(filename.c_str()); if (myfile.is_open()) { while (! myfile.eof()) { getline (myfile,line); if (line.size() == 0 || line[0] == '#' || line[0] == ' ' || line[0] == '\t') { // ignore - comment or blank line continue; } // look for '=' int pos = line.find('='); if (pos<=0) { // ignore, not valid continue; } string className = line.substr(0,pos); string levelName = line.substr(pos+1); // store log level in map LOGGER_GLOBAL_STATE->logLevelMap[className] = levelName; if (className == "log.output") { if (levelName == "STDERR") { LOGGER_GLOBAL_STATE->logMode = LOG_OUTPUT_STDERR; } else if (levelName == "STDOUT") { LOGGER_GLOBAL_STATE->logMode = LOG_OUTPUT_STDOUT; } else if (levelName == "SYSLOG") { LOGGER_GLOBAL_STATE->logMode = LOG_OUTPUT_SYSLOG; } else { LOGGER_GLOBAL_STATE->logMode = LOG_OUTPUT_FILE; if (!LOGGER_GLOBAL_STATE->file) { LOGGER_GLOBAL_STATE->file = fopen(levelName.c_str(), "a"); } } } // convert level name to int int level = LOG_LEVEL_NONE; if (levelName == "TRACE") { level = LOG_LEVEL_TRACE; } else if (levelName == "DEBUG") { level = LOG_LEVEL_DEBUG; } else if (levelName == "INFO") { level = LOG_LEVEL_INFO; } else if (levelName == "WARN") { level = LOG_LEVEL_WARN; } else if (levelName == "ERROR") { level = LOG_LEVEL_ERROR; } else { // default level = LOG_LEVEL_INFO; } // configure existing logger, if it exists Logger *logger = LOGGER_GLOBAL_STATE->loggerMap[className]; if (logger) { //cerr << getPidTid() << " Logger::configure() reconfiguring logger (" << className << ")" << endl; logger->setLevel(level); } else { //cerr << getPidTid() << " Logger::configure() could not find logger (" << className << ")" << endl; } } myfile.close(); } else { //cerr << getPidTid() << " Logger::configure() failed to open file" << endl; } } ////////////////////////////// // // NON-STATIC METHODS // ////////////////////////////// Logger::Logger(string name, int logLevel) { this->name = name; //cerr << getPidTid() << " Logger::Logger(" << name << ")" << endl; setLevel(logLevel); } void Logger::setLevel(int logLevel) { //cerr << getPidTid() << " Logger::setLevel(" << name << ", " << logLevel << ")" << endl; isTrace = logLevel > LOG_LEVEL_NONE && logLevel <= LOG_LEVEL_TRACE; isDebug = logLevel > LOG_LEVEL_NONE && logLevel <= LOG_LEVEL_DEBUG; isInfo = logLevel <= LOG_LEVEL_INFO; } Logger::~Logger() { } void Logger::log(const char *level, const char *message) { if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_STDERR) { cerr << "[" << time(NULL) << "s] " << getPidTid() << " [opensharding] [" << level << "] [" << name << "] " << message << "\n"; } else if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_STDOUT) { cout << "[" << time(NULL) << "s] " << getPidTid() << " [opensharding] [" << level << "] [" << name << "] " << message << "\n"; } else if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_SYSLOG) { int slevel = LOG_ERR; if (strcmp("DEBUG",level)==0) { slevel = LOG_DEBUG; } else if (strcmp("INFO",level)==0) { slevel = LOG_NOTICE; } else if (strcmp("WARN",level)==0) { slevel = LOG_WARNING; } else if (strcmp("ERROR",level)==0) { slevel = LOG_ERR; } syslog ( slevel, "[%d] %s [opensharding] [%s] [%s] %s", (int) time(NULL), getPidTid().c_str(), level, name.c_str(), message ); } else { fprintf(LOGGER_GLOBAL_STATE->file, "[%ld s] %s [opensharding] [%s] [%s] %s\n", time(NULL), getPidTid().c_str(), level, name.c_str(), message); fflush(LOGGER_GLOBAL_STATE->file); } } // raw output - no formatting void Logger::output(const char *message) { if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_STDERR) { cerr << message << "\n"; } else if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_STDOUT) { cout << message << "\n"; } else if (LOGGER_GLOBAL_STATE->logMode == LOG_OUTPUT_SYSLOG) { syslog ( LOG_NOTICE, "%s", message ); } else { fprintf(LOGGER_GLOBAL_STATE->file, "%s\n", message); fflush(LOGGER_GLOBAL_STATE->file); } } //TODO: make the rest of these methods inline to avoid the cost of a function call bool Logger::isTraceEnabled() { return isTrace; } bool Logger::isDebugEnabled() { return isDebug; } bool Logger::isInfoEnabled() { return isInfo; } bool Logger::isWarnEnabled() { return true; } void Logger::trace(string message) { trace(message.c_str()); } void Logger::debug(string message) { debug(message.c_str()); } void Logger::info(string message) { info(message.c_str()); } void Logger::warn(string message) { warn(message.c_str()); } void Logger::error(string message) { error(message.c_str()); } void Logger::output(string message) { output(message.c_str()); } void Logger::trace(const char *message) { if (!isTrace) return; log("TRACE", message); } void Logger::debug(const char *message) { if (!isDebug) return; log("DEBUG", message); } void Logger::info(const char *message) { if (!isInfo) return; log("INFO", message); } void Logger::warn(const char *message) { log("WARN", message); } void Logger::error(const char *message) { log("ERROR", message); } }
28.581081
150
0.559716
[ "object" ]
a12fd70256932f772abe5eb08404626f4ba73faf
974
cc
C++
src/events/types/quotaExceeded.cc
indigo-dc/oneclient
f0f4d502e8a38ed0bc526b99bddd19cb8d9f7f38
[ "MIT" ]
4
2016-02-15T15:52:28.000Z
2021-03-31T11:04:22.000Z
src/events/types/quotaExceeded.cc
onedata/oneclient
46b2ca465bd4785f1b9a63aa7ce7fc5b2faaf130
[ "MIT" ]
11
2016-04-01T15:30:19.000Z
2021-12-13T13:18:18.000Z
src/events/types/quotaExceeded.cc
indigo-dc/oneclient
f0f4d502e8a38ed0bc526b99bddd19cb8d9f7f38
[ "MIT" ]
3
2016-08-26T17:38:06.000Z
2021-12-12T20:10:59.000Z
/** * @file quotaExceeded.cc * @author Krzysztof Trzepla * @copyright (C) 2016 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "quotaExceeded.h" #include "messages.pb.h" #include <sstream> namespace one { namespace client { namespace events { QuotaExceeded::QuotaExceeded(const ProtocolMessage &msg) { for (const auto &spaceId : msg.spaces()) { m_spaces.emplace_back(spaceId); } } StreamKey QuotaExceeded::streamKey() const { return StreamKey::QUOTA_EXCEEDED; } const std::vector<std::string> &QuotaExceeded::spaces() const { return m_spaces; } std::string QuotaExceeded::toString() const { std::stringstream stream; stream << "type: 'QuotaExceeded', spaces: ["; for (const auto &spaceId : m_spaces) { stream << "'" << spaceId << "', "; } stream << "]"; return stream.str(); } } // namespace events } // namespace client } // namespace one
20.723404
80
0.665298
[ "vector" ]
a1407803118c58ac414c2f4a4f4a84e08b26557e
13,949
cpp
C++
Applications/SpGEMM3D.cpp
neuralvis/CombBLAS
79d143496bf9d2a2d8f5359251b3c30f48ec2eff
[ "BSD-3-Clause-LBNL" ]
22
2020-08-14T19:14:13.000Z
2022-02-05T20:14:59.000Z
Applications/SpGEMM3D.cpp
neuralvis/CombBLAS
79d143496bf9d2a2d8f5359251b3c30f48ec2eff
[ "BSD-3-Clause-LBNL" ]
8
2020-10-09T23:23:36.000Z
2021-08-05T20:35:18.000Z
Applications/SpGEMM3D.cpp
neuralvis/CombBLAS
79d143496bf9d2a2d8f5359251b3c30f48ec2eff
[ "BSD-3-Clause-LBNL" ]
8
2020-12-04T09:10:06.000Z
2022-01-04T15:37:59.000Z
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.6 -------------------------------------------------*/ /* date: 6/15/2017 ---------------------------------------------*/ /* authors: Ariful Azad, Aydin Buluc --------------------------*/ /****************************************************************/ /* Copyright (c) 2010-2017, The Regents of the University of California Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <mpi.h> #include <sys/time.h> #include <iostream> #include <functional> #include <algorithm> #include <vector> #include <sstream> #include "CombBLAS/CombBLAS.h" #include "CombBLAS/CommGrid3D.h" #include "CombBLAS/SpParMat3D.h" #include "CombBLAS/ParFriends.h" using namespace std; using namespace combblas; #define EPS 0.0001 #ifdef TIMING double cblas_alltoalltime; double cblas_allgathertime; /////////////////////////// double sym_Abcasttime = 0; double sym_Bbcasttime = 0; double sym_estimatefloptime = 0; double sym_estimatennztime = 0; double sym_SUMMAnnzreductiontime = 0; /////////////////////////// double mcl3d_conversiontime; double mcl3d_symbolictime; double mcl3d_Abcasttime; double mcl3d_Bbcasttime; double mcl3d_SUMMAtime; double mcl3d_localspgemmtime; double mcl3d_SUMMAmergetime; double mcl3d_reductiontime; double mcl3d_3dmergetime; double mcl3d_kselecttime; double mcl3d_totaltime; double mcl_kselecttime; double mcl_prunecolumntime; int64_t mcl3d_layer_nnza; int64_t mcl3d_layer_nnzc; int64_t mcl3d_nnza; int64_t mcl3d_proc_flop; int64_t mcl3d_layer_flop; int64_t mcl3d_flop; int64_t mcl3d_proc_nnzc_pre_red; int64_t mcl3d_layer_nnzc_pre_red; int64_t mcl3d_nnzc_pre_red; int64_t mcl3d_proc_nnzc_post_red; int64_t mcl3d_layer_nnzc_post_red; int64_t mcl3d_nnzc_post_red; /////////////////////////// double g_mcl3d_conversiontime; double g_mcl3d_symbolictime; double g_mcl3d_Abcasttime; double g_mcl3d_Bbcasttime; double g_mcl3d_SUMMAtime; double g_mcl3d_localspgemmtime; double g_mcl3d_SUMMAmergetime; double g_mcl3d_reductiontime; double g_mcl3d_3dmergetime; double g_mcl3d_kselecttime; double g_mcl3d_totaltime; double g_mcl3d_floptime; int64_t g_mcl3d_layer_flop; int64_t g_mcl3d_layer_nnzc; //////////////////////////// double l_mcl3d_conversiontime; double l_mcl3d_symbolictime; double l_mcl3d_Abcasttime; double l_mcl3d_Bbcasttime; double l_mcl3d_SUMMAtime; double l_mcl3d_localspgemmtime; double l_mcl3d_SUMMAmergetime; double l_mcl3d_reductiontime; double l_mcl3d_3dmergetime; double l_mcl3d_kselecttime; double l_mcl3d_totaltime; double l_mcl3d_floptime; int64_t l_mcl3d_layer_flop; int64_t l_mcl3d_layer_nnzc; //////////////////////////// double a_mcl3d_conversiontime; double a_mcl3d_symbolictime; double a_mcl3d_Abcasttime; double a_mcl3d_Bbcasttime; double a_mcl3d_SUMMAtime; double a_mcl3d_localspgemmtime; double a_mcl3d_SUMMAmergetime; double a_mcl3d_reductiontime; double a_mcl3d_3dmergetime; double a_mcl3d_kselecttime; double a_mcl3d_totaltime; double a_mcl3d_floptime; int64_t a_mcl3d_layer_flop; int64_t a_mcl3d_layer_nnzc; /////////////////////////// double mcl3d_conversiontime_prev; double mcl3d_symbolictime_prev; double mcl3d_Abcasttime_prev; double mcl3d_Bbcasttime_prev; double mcl3d_SUMMAtime_prev; double mcl3d_localspgemmtime_prev; double mcl3d_SUMMAmergetime_prev; double mcl3d_reductiontime_prev; double mcl3d_3dmergetime_prev; double mcl3d_kselecttime_prev; double mcl3d_totaltime_prev; double mcl3d_floptime_prev; int64_t mcl3d_layer_flop_prev; int64_t mcl3d_layer_nnzc_prev; #endif #ifdef _OPENMP int cblas_splits = omp_get_max_threads(); #else int cblas_splits = 1; #endif // Simple helper class for declarations: Just the numerical type is templated // The index type and the sequential matrix type stays the same for the whole code // In this case, they are "int" and "SpDCCols" template <class NT> class PSpMat { public: typedef SpDCCols < int64_t, NT > DCCols; typedef SpParMat < int64_t, NT, DCCols > MPI_DCCols; }; int main(int argc, char* argv[]) { int nprocs, myrank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD,&nprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myrank); if(argc < 2){ if(myrank == 0) { cout << "Usage: ./<Binary> <MatrixA> " << endl; } MPI_Finalize(); return -1; } else { double vm_usage, resident_set; string Aname(argv[1]); if(myrank == 0){ fprintf(stderr, "Data: %s\n", argv[1]); } shared_ptr<CommGrid> fullWorld; fullWorld.reset( new CommGrid(MPI_COMM_WORLD, 0, 0) ); double t0, t1; SpParMat<int64_t, double, SpDCCols < int64_t, double >> M(fullWorld); //// Read matrix market files //t0 = MPI_Wtime(); //M.ParallelReadMM(Aname, true, maximum<double>()); //t1 = MPI_Wtime(); //if(myrank == 0) fprintf(stderr, "Time taken to read file: %lf\n", t1-t0); //t0 = MPI_Wtime(); //FullyDistVec<int64_t, int64_t> p( M.getcommgrid() ); //FullyDistVec<int64_t, int64_t> q( M.getcommgrid() ); //p.iota(M.getnrow(), 0); //q.iota(M.getncol(), 0); //p.RandPerm(); //q.RandPerm(); //(M)(p,q,true);// in-place permute to save memory //t1 = MPI_Wtime(); //if(myrank == 0) fprintf(stderr, "Time taken to permuatate input: %lf\n", t1-t0); // Read labelled triple files t0 = MPI_Wtime(); M.ReadGeneralizedTuples(Aname, maximum<double>()); t1 = MPI_Wtime(); if(myrank == 0) fprintf(stderr, "Time taken to read file: %lf\n", t1-t0); //// Sparsify the matrix //MCLPruneRecoverySelect<int64_t, double, SpDCCols < int64_t, double >>(M, 2.0, 52, 55, 0.9, 1); typedef PlusTimesSRing<double, double> PTFF; // Run 2D multiplication to compare against SpParMat<int64_t, double, SpDCCols < int64_t, double >> A2D(M); SpParMat<int64_t, double, SpDCCols < int64_t, double >> B2D(M); SpParMat<int64_t, double, SpDCCols < int64_t, double >> C2D = Mult_AnXBn_Synch<PTFF, double, SpDCCols<int64_t, double>, int64_t, double, double, SpDCCols<int64_t, double>, SpDCCols<int64_t, double> > (A2D, B2D); // Increase number of layers 1 -> 4 -> 16 for(int layers = 1; layers <= 16; layers = layers * 4){ // Create two copies of input matrix which would be used in multiplication SpParMat<int64_t, double, SpDCCols < int64_t, double >> A2(M); SpParMat<int64_t, double, SpDCCols < int64_t, double >> B2(M); // Convert 2D matrices to 3D SpParMat3D<int64_t, double, SpDCCols < int64_t, double >> A3D(A2, layers, true, false); SpParMat3D<int64_t, double, SpDCCols < int64_t, double >> B3D(B2, layers, false, false); if(myrank == 0) fprintf(stderr, "Running 3D with %d layers\n", layers); /**/ int phases = 1; while(phases <= 1){ #ifdef TIMING mcl3d_conversiontime = 0; mcl3d_symbolictime = 0; mcl3d_Abcasttime = 0; mcl3d_Bbcasttime = 0; mcl3d_localspgemmtime = 0; mcl3d_SUMMAmergetime = 0; mcl3d_reductiontime = 0; mcl3d_3dmergetime = 0; mcl3d_kselecttime = 0; mcl3d_totaltime = 0; #endif int it; // Number of iterations to run for(it = 0; it < 1; it++){ #ifdef TIMING mcl3d_conversiontime_prev = mcl3d_conversiontime; mcl3d_symbolictime_prev = mcl3d_symbolictime; mcl3d_Abcasttime_prev = mcl3d_Abcasttime; mcl3d_Bbcasttime_prev = mcl3d_Bbcasttime; mcl3d_SUMMAtime_prev = mcl3d_SUMMAtime; mcl3d_localspgemmtime_prev = mcl3d_localspgemmtime; mcl3d_SUMMAmergetime_prev = mcl3d_SUMMAmergetime; mcl3d_reductiontime_prev = mcl3d_reductiontime; mcl3d_3dmergetime_prev = mcl3d_3dmergetime; mcl3d_kselecttime_prev = mcl3d_kselecttime; mcl3d_totaltime_prev = mcl3d_totaltime; #endif #ifdef TIMING MPI_Barrier(MPI_COMM_WORLD); t0 = MPI_Wtime(); #endif SpParMat3D<int64_t, double, SpDCCols < int64_t, double >> C3D = Mult_AnXBn_SUMMA3D<PTFF, double, SpDCCols<int64_t, double>, int64_t, double, double, SpDCCols<int64_t, double>, SpDCCols<int64_t, double> > (A3D, B3D); //MemEfficientSpGEMM3D<PTFF, double, SpDCCols<int64_t, double>, int64_t, double, double, SpDCCols<int64_t, double>, SpDCCols<int64_t, double> > //(A3D, B3D, 1, 0.9, 1400, 1100, 0.9, 1, 27); #ifdef TIMING MPI_Barrier(MPI_COMM_WORLD); t1 = MPI_Wtime(); mcl3d_totaltime += (t1-t0); #endif SpParMat<int64_t, double, SpDCCols < int64_t, double >> C3D2D = C3D.Convert2D(); if(C2D == C3D2D){ if(myrank == 0) fprintf(stderr, "Correct!\n"); } else{ if(myrank == 0) fprintf(stderr, "Not correct!\n"); } #ifdef TIMING MPI_Allreduce(&mcl3d_proc_flop, &mcl3d_layer_flop, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetLayerWorld()); MPI_Allreduce(&mcl3d_proc_flop, &mcl3d_flop, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetWorld()); MPI_Allreduce(&mcl3d_proc_nnzc_pre_red, &mcl3d_layer_nnzc_pre_red, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetLayerWorld()); MPI_Allreduce(&mcl3d_proc_nnzc_pre_red, &mcl3d_nnzc_pre_red, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetWorld()); MPI_Allreduce(&mcl3d_proc_nnzc_post_red, &mcl3d_layer_nnzc_post_red, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetLayerWorld()); MPI_Allreduce(&mcl3d_proc_nnzc_post_red, &mcl3d_nnzc_post_red, 1, MPI_LONG_LONG_INT, MPI_SUM, A3D.getcommgrid3D()->GetWorld()); mcl3d_layer_nnza = A3D.GetLayerMat()->getnnz(); mcl3d_nnza = A3D.getnnz(); if(myrank == 0){ fprintf(stderr, "[3D: Iteration: %d] Symbolictime: %lf\n", it, (mcl3d_symbolictime - mcl3d_symbolictime_prev)); fprintf(stderr, "[3D: Iteration: %d] Abcasttime: %lf\n", it, (mcl3d_Abcasttime - mcl3d_Abcasttime_prev)); fprintf(stderr, "[3D: Iteration: %d] Bbcasttime: %lf\n", it, (mcl3d_Bbcasttime - mcl3d_Bbcasttime_prev)); fprintf(stderr, "[3D: Iteration: %d] LocalSPGEMM: %lf\n", it, (mcl3d_localspgemmtime - mcl3d_localspgemmtime_prev)); fprintf(stderr, "[3D: Iteration: %d] SUMMAmerge: %lf\n", it, (mcl3d_SUMMAmergetime - mcl3d_SUMMAmergetime_prev)); fprintf(stderr, "[3D: Iteration: %d] Reduction: %lf\n", it, (mcl3d_reductiontime - mcl3d_reductiontime_prev)); fprintf(stderr, "[3D: Iteration: %d] 3D Merge: %lf\n", it, (mcl3d_3dmergetime - mcl3d_3dmergetime_prev)); fprintf(stderr, "[3D: Iteration: %d] SelectionRecovery: %lf\n", it, (mcl3d_kselecttime - mcl3d_kselecttime_prev)); fprintf(stderr, "[3D: Iteration: %d] Total time: %lf\n", it, (mcl3d_totaltime - mcl3d_totaltime_prev)); fprintf(stderr, "[Iteration: %d] layer nnza: %lld\n", it, mcl3d_layer_nnza); fprintf(stderr, "[Iteration: %d] layer flop: %lld\n", it, mcl3d_layer_flop); fprintf(stderr, "[Iteration: %d] layer nnzc pre reduction: %lld\n", it, mcl3d_layer_nnzc_pre_red); fprintf(stderr, "[Iteration: %d] layer nnzc post reduction: %lld\n", it, mcl3d_layer_nnzc_post_red); fprintf(stderr, "[Iteration: %d] flop: %lld\n", it, mcl3d_flop); fprintf(stderr, "[Iteration: %d] nnzc pre reduction: %lld\n", it, mcl3d_nnzc_pre_red); fprintf(stderr, "[Iteration: %d] nnzc post reduction: %lld\n", it, mcl3d_nnzc_post_red); fprintf(stderr, "-----------------------------------------------------\n"); } #endif } int ii = 1; while(ii <= phases) ii = ii * 2; phases = ii; } if(myrank == 0) fprintf(stderr, "\n\n********************************************\n\n"); /**/ } } MPI_Finalize(); return 0; }
42.398176
167
0.627644
[ "vector", "3d" ]
a147a40ecfbdcf0951f508f0bc2d334efe383d02
1,038
cpp
C++
JS/expressions/call_expression.cpp
dorin131/dorin-browser
0bf362482955185c590a9d82ffaeb64f0f106547
[ "MIT" ]
1
2020-08-14T09:27:27.000Z
2020-08-14T09:27:27.000Z
JS/expressions/call_expression.cpp
dorin131/dorin-browser
0bf362482955185c590a9d82ffaeb64f0f106547
[ "MIT" ]
null
null
null
JS/expressions/call_expression.cpp
dorin131/dorin-browser
0bf362482955185c590a9d82ffaeb64f0f106547
[ "MIT" ]
null
null
null
#include "call_expression.h" #include "../interpreter.h" namespace js { CallExpression::CallExpression(std::shared_ptr<Node> exp, std::vector<std::shared_ptr<Node>> args) : expression(exp), arguments(args) { } Value CallExpression::execute(Interpreter& i) { std::shared_ptr<Node> callee = expression; if (expression->get_type() == "Identifier") { callee = i.find_in_scope(*std::static_pointer_cast<Identifier>(callee)); } if (callee->get_type() == "FunctionDeclaration") { auto function = std::static_pointer_cast<FunctionDeclaration>(callee); auto body = function->get_body(); auto body_copy = std::make_shared<BlockStatement>(*body); body_copy->associate_arguments(i, arguments); body_copy->set_parent(function); return body_copy->execute(i); } return callee->execute(i); } void CallExpression::dump(int indent) { print_indent(indent); std::cout << "CallExpression" << std::endl; expression->dump(indent + 1); }; } // namespace js
25.95
98
0.67052
[ "vector" ]
a1537727955132b03dcbb4b0801e9a118f5e0b3b
10,951
cpp
C++
plugins/plants.cpp
dlmarquis/dfhack
bd216dbc117bdb197fe12febaf1285f5a67c57d7
[ "CC-BY-3.0" ]
5
2016-03-06T15:54:20.000Z
2020-04-20T03:57:15.000Z
plugins/plants.cpp
dlmarquis/dfhack
bd216dbc117bdb197fe12febaf1285f5a67c57d7
[ "CC-BY-3.0" ]
3
2016-10-11T18:01:09.000Z
2019-02-18T11:45:54.000Z
plugins/plants.cpp
dlmarquis/dfhack
bd216dbc117bdb197fe12febaf1285f5a67c57d7
[ "CC-BY-3.0" ]
1
2020-05-17T21:27:09.000Z
2020-05-17T21:27:09.000Z
#include <iostream> #include <iomanip> #include <map> #include <algorithm> #include <vector> #include <string> #include "Core.h" #include "Console.h" #include "Export.h" #include "PluginManager.h" #include "modules/Maps.h" #include "modules/Gui.h" #include "TileTypes.h" #include "modules/MapCache.h" #include "df/plant.h" #include "df/world.h" using std::vector; using std::string; using namespace DFHack; DFHACK_PLUGIN("plants"); REQUIRE_GLOBAL(world); const uint32_t sapling_to_tree_threshold = 120 * 28 * 12 * 3 - 1; // 3 years minus 1 - let the game handle the actual growing-up /* Immolate/Extirpate no longer work in 0.40 enum do_what { do_immolate, do_extirpate }; static bool getoptions( vector <string> & parameters, bool & shrubs, bool & trees, bool & help) { for(size_t i = 0;i < parameters.size();i++) { if(parameters[i] == "shrubs") { shrubs = true; } else if(parameters[i] == "trees") { trees = true; } else if(parameters[i] == "all") { trees = true; shrubs = true; } else if(parameters[i] == "help" || parameters[i] == "?") { help = true; } else { return false; } } return true; } // // Book of Immolations, chapter 1, verse 35: // Armok emerged from the hellish depths and beheld the sunny realms for the first time. // And he cursed the plants and trees for their bloodless wood, turning them into ash and smoldering ruin. // Armok was pleased and great temples were built by the dwarves, for they shared his hatred for trees and plants. // static command_result immolations (color_ostream &out, do_what what, bool shrubs, bool trees) { CoreSuspender suspend; if (!Maps::IsValid()) { out.printerr("Map is not available!\n"); return CR_FAILURE; } uint32_t x_max, y_max, z_max; Maps::getSize(x_max, y_max, z_max); MapExtras::MapCache map; if(shrubs || trees) { int destroyed = 0; for(size_t i = 0 ; i < world->plants.all.size(); i++) { df::plant *p = world->plants.all[i]; if(shrubs && p->flags.bits.is_shrub || trees && !p->flags.bits.is_shrub) { if (what == do_immolate) p->damage_flags.bits.is_burning = true; p->hitpoints = 0; destroyed ++; } } out.print("Praise Armok! %i plants destroyed.\n", destroyed); } else { int32_t x,y,z; if(Gui::getCursorCoords(x,y,z)) { bool didit = false; for(size_t i = 0; i < world->plants.all.size(); i++) { df::plant *tree = world->plants.all[i]; if(tree->pos.x == x && tree->pos.y == y && tree->pos.z == z) { if(what == do_immolate) tree->damage_flags.bits.is_burning = true; tree->hitpoints = 0; didit = true; break; } } if(didit) out.print("Praise Armok! Selected plant destroyed.\n"); else out.printerr("No plant found at specified location!\n"); } else { out.printerr("No mass destruction and no cursor...\n" ); } } return CR_OK; } command_result df_immolate (color_ostream &out, vector <string> & parameters, do_what what) { bool shrubs = false, trees = false, help = false; if (getoptions(parameters, shrubs, trees, help) && !help) { return immolations(out, what, shrubs, trees); } string mode; if (what == do_immolate) mode = "Set plants on fire"; else mode = "Kill plants"; if (!help) out.printerr("Invalid parameter!\n"); out << "Usage:\n" << mode << " (under cursor, 'shrubs', 'trees' or 'all').\n" "Without any options, this command acts on the plant under the cursor.\n" "Options:\n" "shrubs - affect all shrubs\n" "trees - affect all trees\n" "all - affect all plants\n"; return CR_OK; } */ command_result df_grow (color_ostream &out, vector <string> & parameters) { for(size_t i = 0; i < parameters.size();i++) { if(parameters[i] == "help" || parameters[i] == "?") { out.print("Usage:\n" "This command turns all living saplings on the map into full-grown trees.\n" "With active cursor, work on the targetted one only.\n"); return CR_OK; } } CoreSuspender suspend; if (!Maps::IsValid()) { out.printerr("Map is not available!\n"); return CR_FAILURE; } MapExtras::MapCache map; int32_t x,y,z; int grown = 0; if(Gui::getCursorCoords(x,y,z)) { for(size_t i = 0; i < world->plants.all.size(); i++) { df::plant * tree = world->plants.all[i]; if(tree->pos.x == x && tree->pos.y == y && tree->pos.z == z) { if(tileShape(map.tiletypeAt(DFCoord(x,y,z))) == tiletype_shape::SAPLING && tileSpecial(map.tiletypeAt(DFCoord(x,y,z))) != tiletype_special::DEAD) { tree->grow_counter = sapling_to_tree_threshold; grown++; } break; } } } else { for(size_t i = 0 ; i < world->plants.all.size(); i++) { df::plant *p = world->plants.all[i]; df::tiletype ttype = map.tiletypeAt(df::coord(p->pos.x,p->pos.y,p->pos.z)); if(!p->flags.bits.is_shrub && tileShape(ttype) == tiletype_shape::SAPLING && tileSpecial(ttype) != tiletype_special::DEAD) { p->grow_counter = sapling_to_tree_threshold; grown++; } } } if (grown) out.print("%i plants grown.\n", grown); else out.printerr("No plant(s) found!\n"); return CR_OK; } command_result df_createplant (color_ostream &out, vector <string> & parameters) { if ((parameters.size() != 1) || (parameters[0] == "help" || parameters[0] == "?")) { out.print("Usage:\n" "Create a new plant at the cursor.\n" "Specify the type of plant to create by its raw ID (e.g. TOWER_CAP or MUSHROOM_HELMET_PLUMP).\n" "Only shrubs and saplings can be placed, and they must be located on a dirt or grass floor.\n"); return CR_OK; } CoreSuspender suspend; if (!Maps::IsValid()) { out.printerr("Map is not available!\n"); return CR_FAILURE; } int32_t x,y,z; if(!Gui::getCursorCoords(x,y,z)) { out.printerr("No cursor detected - please place the cursor over the location in which you wish to create a new plant.\n"); return CR_FAILURE; } df::map_block *map = Maps::getTileBlock(x, y, z); df::map_block_column *col = Maps::getBlockColumn((x / 48) * 3, (y / 48) * 3); if (!map || !col) { out.printerr("Invalid location selected!\n"); return CR_FAILURE; } int tx = x & 15, ty = y & 15; int mat = tileMaterial(map->tiletype[tx][ty]); if ((tileShape(map->tiletype[tx][ty]) != tiletype_shape::FLOOR) || ((mat != tiletype_material::SOIL) && (mat != tiletype_material::GRASS_DARK) && (mat != tiletype_material::GRASS_LIGHT))) { out.printerr("Plants can only be placed on dirt or grass floors!\n"); return CR_FAILURE; } int plant_id = -1; df::plant_raw *plant_raw = NULL; for (size_t i = 0; i < world->raws.plants.all.size(); i++) { plant_raw = world->raws.plants.all[i]; if (plant_raw->id == parameters[0]) { plant_id = i; break; } } if (plant_id == -1) { out.printerr("Invalid plant ID specified!\n"); return CR_FAILURE; } if (plant_raw->flags.is_set(plant_raw_flags::GRASS)) { out.printerr("You cannot plant grass using this command.\n"); return CR_FAILURE; } df::plant *plant = df::allocate<df::plant>(); if (plant_raw->flags.is_set(plant_raw_flags::TREE)) plant->hitpoints = 400000; else { plant->hitpoints = 100000; plant->flags.bits.is_shrub = 1; } // for now, always set "watery" for WET-permitted plants, even if they're spawned away from water // the proper method would be to actually look for nearby water features, but it's not clear exactly how that works if (plant_raw->flags.is_set(plant_raw_flags::WET)) plant->flags.bits.watery = 1; plant->material = plant_id; plant->pos.x = x; plant->pos.y = y; plant->pos.z = z; plant->update_order = rand() % 10; world->plants.all.push_back(plant); switch (plant->flags.whole & 3) { case 0: world->plants.tree_dry.push_back(plant); break; case 1: world->plants.tree_wet.push_back(plant); break; case 2: world->plants.shrub_dry.push_back(plant); break; case 3: world->plants.shrub_wet.push_back(plant); break; } col->plants.push_back(plant); if (plant->flags.bits.is_shrub) map->tiletype[tx][ty] = tiletype::Shrub; else map->tiletype[tx][ty] = tiletype::Sapling; return CR_OK; } command_result df_plant (color_ostream &out, vector <string> & parameters) { if (parameters.size() >= 1) { if (parameters[0] == "grow") { parameters.erase(parameters.begin()); return df_grow(out, parameters); } else /* if (parameters[0] == "immolate") { parameters.erase(parameters.begin()); return df_immolate(out, parameters, do_immolate); } else if (parameters[0] == "extirpate") { parameters.erase(parameters.begin()); return df_immolate(out, parameters, do_extirpate); } else */ if (parameters[0] == "create") { parameters.erase(parameters.begin()); return df_createplant(out, parameters); } } return CR_WRONG_USAGE; } DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) { commands.push_back(PluginCommand("plant", "Plant creation and removal.", df_plant, false, "Command to create, grow or remove plants on the map. For more details, check the subcommand help :\n" "plant grow help - Grows saplings into trees.\n" // "plant immolate help - Set plants on fire.\n" // "plant extirpate help - Kill plants.\n" "plant create help - Create a new plant.\n")); return CR_OK; } DFhackCExport command_result plugin_shutdown ( color_ostream &out ) { return CR_OK; }
30.589385
191
0.56214
[ "vector" ]
a15403872966269bf4017ee4245f1556b98cc1cc
2,735
cc
C++
mediapipe/framework/profiler/reporter/print_profile.cc
Ensteinjun/mediapipe
38be2ec58f2a1687f4ffca287094c7bbd7791f58
[ "Apache-2.0" ]
2
2021-12-02T02:14:31.000Z
2021-12-02T02:16:24.000Z
mediapipe/framework/profiler/reporter/print_profile.cc
Ensteinjun/mediapipe
38be2ec58f2a1687f4ffca287094c7bbd7791f58
[ "Apache-2.0" ]
null
null
null
mediapipe/framework/profiler/reporter/print_profile.cc
Ensteinjun/mediapipe
38be2ec58f2a1687f4ffca287094c7bbd7791f58
[ "Apache-2.0" ]
3
2021-01-19T14:40:59.000Z
2021-06-09T13:43:49.000Z
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This program takes one input file and encodes its contents as a C++ // std::string, which can be included in a C++ source file. It is similar to // filewrapper (and borrows some of its code), but simpler. #include <algorithm> #include <fstream> #include "absl/container/btree_map.h" #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "mediapipe/framework/port/advanced_proto_inc.h" #include "mediapipe/framework/port/commandlineflags.h" #include "mediapipe/framework/port/file_helpers.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/profiler/reporter/reporter.h" ABSL_FLAG(std::vector<std::string>, logfiles, {}, "comma-separated list of .binarypb files to process."); ABSL_FLAG(std::vector<std::string>, cols, {"*"}, "comma-separated list of columns to show. Suffix wildcards, '*', '?' " "allowed."); ABSL_FLAG(bool, compact, false, "if true, then don't print unnecessary whitespace."); using mediapipe::reporter::Reporter; // The command line utility to mine trace files of useful statistics to // determine bottlenecks and performance of a graph. int main(int argc, char** argv) { absl::SetProgramUsageMessage("Display statistics from MediaPipe log files."); absl::ParseCommandLine(argc, argv); Reporter reporter; reporter.set_compact(absl::GetFlag(FLAGS_compact)); const auto result = reporter.set_columns(absl::GetFlag(FLAGS_cols)); if (result.message().length()) { std::cout << "WARNING" << std::endl << result.message(); } const auto& flags_logfiles = absl::GetFlag(FLAGS_logfiles); for (const auto& file_name : flags_logfiles) { std::ifstream ifs(file_name.c_str(), std::ifstream::in); mediapipe::proto_ns::io::IstreamInputStream isis(&ifs); mediapipe::proto_ns::io::CodedInputStream coded_input_stream(&isis); mediapipe::GraphProfile proto; if (!proto.ParseFromCodedStream(&coded_input_stream)) { std::cerr << "Failed to parse proto.\n"; } else { reporter.Accumulate(proto); } } reporter.Report()->Print(std::cout); return 1; }
39.071429
80
0.719561
[ "vector" ]
a15cc7be9fdfc32c64ab7aadb3beba261e28631a
1,783
cpp
C++
source/core/FsdkObj/ObjPath.cpp
fengsheng66/FsdkObjSys
33827a4cde6a89b3113fbd2b9f0b0943529c6c8a
[ "Apache-2.0" ]
null
null
null
source/core/FsdkObj/ObjPath.cpp
fengsheng66/FsdkObjSys
33827a4cde6a89b3113fbd2b9f0b0943529c6c8a
[ "Apache-2.0" ]
null
null
null
source/core/FsdkObj/ObjPath.cpp
fengsheng66/FsdkObjSys
33827a4cde6a89b3113fbd2b9f0b0943529c6c8a
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 FengSheng. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <FsdkObj/ObjPath.h> using namespace FsdkObj; ObjPath::ObjPath(const std::string& _path) : m_path(_path) { } ObjPath::~ObjPath() { } const std::string& ObjPath::path() const { return m_path; } bool ObjPath::registerObj(IObject* obj) { ObjectMap::iterator iter = m_objects.find(obj->name()); if (iter != m_objects.end()) { return false; } else { m_objects[obj->name()] = obj; return true; } } bool ObjPath::writeoffObj(const std::string& name) { ObjectMap::iterator iter = m_objects.find(name); if (iter != m_objects.end()) { m_objects.erase(iter); return true; } else { return false; } } std::vector<IObject*> ObjPath::allObj() const { std::vector<IObject*> objectVec; objectVec.resize(m_objects.size(), 0); ObjectMap::const_iterator iter = m_objects.begin(); for (int i = 0; iter != m_objects.end(); iter++, i++) { objectVec[i] = iter->second; } return objectVec; } int ObjPath::getObjectNum() const { return m_objects.size(); } IObject* ObjPath::getObj(const std::string& name) const { ObjectMap::const_iterator iter = m_objects.find(name); if (iter != m_objects.end()) { return iter->second; } else { return NULL; } }
19.593407
75
0.689849
[ "vector" ]
a15f04e7c641de49bc69f6ecb1740c40438e568d
1,355
cc
C++
RecoMTD/TransientTrackingRecHit/src/MTDTransientTrackingRecHit.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoMTD/TransientTrackingRecHit/src/MTDTransientTrackingRecHit.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoMTD/TransientTrackingRecHit/src/MTDTransientTrackingRecHit.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/** \file * */ #include "RecoMTD/TransientTrackingRecHit/interface/MTDTransientTrackingRecHit.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "DataFormats/GeometryCommonDetAlgo/interface/ErrorFrameTransformer.h" #include "DataFormats/ForwardDetId/interface/MTDDetId.h" #include "DataFormats/TrackingRecHit/interface/AlignmentPositionError.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" #include <map> typedef MTDTransientTrackingRecHit::MTDRecHitPointer MTDRecHitPointer; typedef MTDTransientTrackingRecHit::RecHitContainer MTDRecHitContainer; MTDTransientTrackingRecHit::MTDTransientTrackingRecHit(const GeomDet* geom, const TrackingRecHit* rh) : GenericTransientTrackingRecHit(*geom,*rh){} MTDTransientTrackingRecHit::MTDTransientTrackingRecHit(const MTDTransientTrackingRecHit& other ) : GenericTransientTrackingRecHit(*other.det(), *(other.hit())) {} bool MTDTransientTrackingRecHit::isBTL() const{ MTDDetId temp(geographicalId()); return (temp.mtdSubDetector() == MTDDetId::BTL); } bool MTDTransientTrackingRecHit::isETL() const{ MTDDetId temp(geographicalId()); return (temp.mtdSubDetector() == MTDDetId::ETL); } void MTDTransientTrackingRecHit::invalidateHit(){ setType(bad); //trackingRecHit_->setType(bad); // maybe add in later }
33.04878
103
0.80369
[ "geometry" ]
a15fdd503bcd53efbd8a200ed3d85cbcbf803c5d
2,872
hpp
C++
core/consensus/grandpa/vote_weight.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/consensus/grandpa/vote_weight.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/consensus/grandpa/vote_weight.hpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_CONSENSUS_GRANDPA_VOTE_WEIGHT_HPP #define KAGOME_CORE_CONSENSUS_GRANDPA_VOTE_WEIGHT_HPP #include <numeric> #include <boost/dynamic_bitset.hpp> #include <boost/operators.hpp> #include "consensus/grandpa/structs.hpp" #include "consensus/grandpa/voter_set.hpp" namespace kagome::consensus::grandpa { inline const size_t kMaxNumberOfVoters = 256; /** * Vote weight is a structure that keeps track of who voted for the vote and * with which weight */ class VoteWeight : public boost::equality_comparable<VoteWeight>, public boost::less_than_comparable<VoteWeight> { public: explicit VoteWeight(size_t voters_size = kMaxNumberOfVoters); /** * Get total weight of current vote's weight * @param prevotes_equivocators describes peers which equivocated (voted * twice for different block) during prevote. Index in vector corresponds to * the authority index of the peer. Bool is true if peer equivocated, false * otherwise * @param precommits_equivocators same for precommits * @param voter_set list of peers with their weight * @return totol weight of current vote's weight */ TotalWeight totalWeight(const std::vector<bool> &prevotes_equivocators, const std::vector<bool> &precommits_equivocators, const std::shared_ptr<VoterSet> &voter_set) const; VoteWeight &operator+=(const VoteWeight &vote); bool operator==(const VoteWeight &other) const { return prevotes_sum == other.prevotes_sum and precommits_sum == other.precommits_sum and prevotes == other.prevotes and precommits == other.precommits; } size_t prevotes_sum = 0; size_t precommits_sum = 0; std::vector<size_t> prevotes = std::vector<size_t>(kMaxNumberOfVoters, 0UL); std::vector<size_t> precommits = std::vector<size_t>(kMaxNumberOfVoters, 0UL); void setPrevote(size_t index, size_t weight) { prevotes_sum -= prevotes[index]; prevotes[index] = weight; prevotes_sum += weight; } void setPrecommit(size_t index, size_t weight) { precommits_sum -= precommits[index]; precommits[index] = weight; precommits_sum += weight; } static inline const struct { bool operator()(const VoteWeight &lhs, const VoteWeight &rhs) { return lhs.prevotes_sum < rhs.prevotes_sum; } } prevoteComparator; static inline const struct { bool operator()(const VoteWeight &lhs, const VoteWeight &rhs) { return lhs.precommits_sum < rhs.precommits_sum; } } precommitComparator; }; } // namespace kagome::consensus::grandpa #endif // KAGOME_CORE_CONSENSUS_GRANDPA_VOTE_WEIGHT_HPP
33.395349
80
0.693245
[ "vector" ]
a163e59d3f19df7ed2e50dea14c30574ac83a45e
7,281
cc
C++
core/metrics.cc
sbilly/seastar
4d4a58d15ac20c9037bd52222c9046be8fadc0dc
[ "Apache-2.0" ]
1
2021-04-30T04:44:45.000Z
2021-04-30T04:44:45.000Z
core/metrics.cc
sbilly/seastar
4d4a58d15ac20c9037bd52222c9046be8fadc0dc
[ "Apache-2.0" ]
null
null
null
core/metrics.cc
sbilly/seastar
4d4a58d15ac20c9037bd52222c9046be8fadc0dc
[ "Apache-2.0" ]
null
null
null
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2016 ScyllaDB. */ #include "metrics.hh" #include "metrics_api.hh" #include <boost/range/algorithm.hpp> namespace seastar { namespace metrics { metric_groups::metric_groups() noexcept : _impl(impl::create_metric_groups()) { } void metric_groups::clear() { _impl = impl::create_metric_groups(); } metric_groups::metric_groups(std::initializer_list<metric_group_definition> mg) : _impl(impl::create_metric_groups()) { for (auto&& i : mg) { add_group(i.name, i.metrics); } } metric_groups& metric_groups::add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_group::metric_group() noexcept = default; metric_group::~metric_group() = default; metric_group::metric_group(const group_name_type& name, std::initializer_list<metric_definition> l) { add_group(name, l); } metric_group_definition::metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l) : name(name), metrics(l) { } metric_group_definition::~metric_group_definition() = default; metric_groups::~metric_groups() = default; metric_definition::metric_definition(metric_definition&& m) noexcept : _impl(std::move(m._impl)) { } metric_definition::~metric_definition() = default; metric_definition::metric_definition(impl::metric_definition_impl const& m) noexcept : _impl(std::make_unique<impl::metric_definition_impl>(m)) { } bool label_instance::operator<(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) < std::tie(id2.key(), id2.value()); } bool label_instance::operator==(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) == std::tie(id2.key(), id2.value()); } bool label_instance::operator!=(const label_instance& id2) const { auto& id1 = *this; return !(id1 == id2); } label shard_label("shard"); label type_label("type"); namespace impl { registered_metric::registered_metric(data_type type, metric_function f, description d, bool enabled) : _type(type), _d(d), _enabled(enabled), _f(f), _impl(get_local_impl()) { } metric_value metric_value::operator+(const metric_value& c) { metric_value res(*this); switch (_type) { case data_type::HISTOGRAM: boost::get<histogram>(res.u) += boost::get<histogram>(c.u); default: boost::get<double>(res.u) += boost::get<double>(c.u); break; } return res; } metric_definition_impl::metric_definition_impl( metric_name_type name, metric_type type, metric_function f, description d, std::vector<label_instance> _labels) : name(name), type(type), f(f) , d(d), enabled(true) { for (auto i: _labels) { labels[i.key()] = i.value(); } if (labels.find(shard_label.name()) == labels.end()) { labels[shard_label.name()] = shard(); } if (labels.find(type_label.name()) == labels.end()) { labels[type_label.name()] = type.type_name; } } metric_definition_impl& metric_definition_impl::operator ()(bool _enabled) { enabled = _enabled; return *this; } metric_definition_impl& metric_definition_impl::operator ()(const label_instance& label) { labels[label.key()] = label.value(); return *this; } std::unique_ptr<metric_groups_def> create_metric_groups() { return std::make_unique<metric_groups_impl>(); } metric_groups_impl::~metric_groups_impl() { for (auto i : _registration) { unregister_metric(i); } } metric_groups_impl& metric_groups_impl::add_metric(group_name_type name, const metric_definition& md) { metric_id id(name, md._impl->name, md._impl->labels); shared_ptr<registered_metric> rm = ::make_shared<registered_metric>(md._impl->type.base_type, md._impl->f, md._impl->d, md._impl->enabled); get_local_impl()->add_registration(id, rm); _registration.push_back(id); return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::vector<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *(i->_impl.get())); } return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::initializer_list<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *i); } return *this; } bool metric_id::operator<( const metric_id& id2) const { return as_tuple() < id2.as_tuple(); } bool metric_id::operator==( const metric_id & id2) const { return as_tuple() == id2.as_tuple(); } // Unfortunately, metrics_impl can not be shared because it // need to be available before the first users (reactor) will call it shared_ptr<impl> get_local_impl() { static thread_local auto the_impl = make_shared<impl>(); return the_impl; } void unregister_metric(const metric_id & id) { shared_ptr<impl> map = get_local_impl(); auto i = map->get_value_map().find(id); if (i != map->get_value_map().end()) { i->second = nullptr; } } const value_map& get_value_map() { return get_local_impl()->get_value_map(); } values_copy get_values() { values_copy res; for (auto i : get_local_impl()->get_value_map()) { if (i.second.get() && i.second->is_enabled()) { res[i.first] = (*(i.second))(); } } return std::move(res); } instance_id_type shard() { if (engine_is_ready()) { return to_sstring(engine().cpu_id()); } return sstring("0"); } void impl::add_registration(const metric_id& id, shared_ptr<registered_metric> rm) { _value_map[id] = rm; } } const bool metric_disabled = false; histogram& histogram::operator+=(const histogram& c) { for (size_t i = 0; i < c.buckets.size(); i++) { if (buckets.size() <= i) { buckets.push_back(c.buckets[i]); } else { if (buckets[i].upper_bound != c.buckets[i].upper_bound) { throw std::out_of_range("Trying to add histogram with different bucket limits"); } buckets[i].count += c.buckets[i].count; } } return *this; } histogram histogram::operator+(const histogram& c) const { histogram res = *this; res += c; return res; } histogram histogram::operator+(histogram&& c) const { c += *this; return std::move(c); } } }
28.441406
148
0.667491
[ "vector" ]
a16829bd799d7d81291ee33e0a3e1d0937b010d5
662
cpp
C++
C++/802.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
1
2021-08-31T08:53:47.000Z
2021-08-31T08:53:47.000Z
C++/802.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
null
null
null
C++/802.cpp
TianChenjiang/LeetCode
a680c90bc968eba5aa76c3674af1f2d927986ec7
[ "MIT" ]
null
null
null
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { int n = graph.size(); vector<int> res, color(n); // 0 - while 1 - gray 2 - black for (int i = 0; i < n; i++) { if (helper(graph, i, color)) res.push_back(i); } return res; } bool helper(vector<vector<int>>& graph, int i, vector<int>& color) { if (color[i] == 2) return true; if (color[i] == 1) return false; color[i] = 1; for (int next : graph[i]) { if (!helper(graph, next, color)) return false; } color[i] = 2; return true; } };
27.583333
72
0.490937
[ "vector" ]
a16874d0ab7303649d6fb03bf94993639909e7b5
839
cpp
C++
216.combination-sum-iii.161158372.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
216.combination-sum-iii.161158372.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
216.combination-sum-iii.161158372.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
class Solution { public: void util(vector<vector<int>> &ans,vector<int> temp,int sum,int target,int k,int index,vector<int> nums) { if(temp.size()==k) { if(sum==target) { cout<<"h"; ans.push_back(temp); } return; } if(temp.size()>k||(index==nums.size())||sum>target)return; for(int i= index;i<nums.size();i++) { temp.push_back(nums[i]); util(ans,temp,sum+nums[i],target,k,i+1,nums); temp.pop_back(); } } vector<vector<int>> combinationSum3(int k, int n) { vector<int> nums(9); for(int i=0;i<9;i++)nums[i]=i+1; vector<vector<int>> ans; vector<int> temp; util(ans,temp,0,n,k,0,nums); return ans; } };
27.064516
108
0.475566
[ "vector" ]
a16892f49db858b53558a4b62b80c240063b21ed
17,810
cpp
C++
Source/Runtime/VariantContainer.cpp
huangfeidian/CPP-Reflection
e55882bb8da0728f6a993f3e5c0b18838564e438
[ "MIT" ]
1
2020-06-18T10:42:33.000Z
2020-06-18T10:42:33.000Z
Source/Runtime/VariantContainer.cpp
huangfeidian/CPP-Reflection
e55882bb8da0728f6a993f3e5c0b18838564e438
[ "MIT" ]
null
null
null
Source/Runtime/VariantContainer.cpp
huangfeidian/CPP-Reflection
e55882bb8da0728f6a993f3e5c0b18838564e438
[ "MIT" ]
1
2021-09-30T02:05:41.000Z
2021-09-30T02:05:41.000Z
/* ---------------------------------------------------------------------------- ** Copyright (c) 2016 Austin Brunkhorst, All Rights Reserved. ** ** VariantContainer.cpp ** --------------------------------------------------------------------------*/ #include "Precompiled.h" #include "VariantContainer.h" #include "Type.h" #include <algorithm> namespace ursine { namespace meta { /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // void /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region void VariantContainer<void>::VariantContainer(void) { } Type VariantContainer<void>::GetType(void) const { return meta_typeof( void ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<void>::GetPtr(void) const { return nullptr; } /////////////////////////////////////////////////////////////////////// int VariantContainer<void>::ToInt(void) const { return int( ); } /////////////////////////////////////////////////////////////////////// bool VariantContainer<void>::ToBool(void) const { return bool( ); } /////////////////////////////////////////////////////////////////////// float VariantContainer<void>::ToFloat(void) const { return float( ); } /////////////////////////////////////////////////////////////////////// double VariantContainer<void>::ToDouble(void) const { return double( ); } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<void>::ToString(void) const { return std::string( ); } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<void>::Clone(void) const { return new VariantContainer<void>( ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // int /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region int VariantContainer<int>::VariantContainer(const int &value) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<int>::VariantContainer(const int &&value) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<int>::GetType(void) const { return meta_typeof( int ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<int>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<int>::ToInt(void) const { return m_value; } /////////////////////////////////////////////////////////////////////// bool VariantContainer<int>::ToBool(void) const { return m_value == 0 ? false : true; } /////////////////////////////////////////////////////////////////////// float VariantContainer<int>::ToFloat(void) const { return static_cast<float>( m_value ); } /////////////////////////////////////////////////////////////////////// double VariantContainer<int>::ToDouble(void) const { return static_cast<double>( m_value ); } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<int>::ToString(void) const { return std::to_string( m_value ); } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<int>::Clone(void) const { return new VariantContainer<int>( m_value ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // unsigned int /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region unsigned unsigned VariantContainer<unsigned>::VariantContainer(const unsigned &value) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<unsigned>::VariantContainer(const unsigned &&value) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<unsigned>::GetType(void) const { return meta_typeof( unsigned ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<unsigned>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<unsigned>::ToInt(void) const { return static_cast<int>( m_value ); } /////////////////////////////////////////////////////////////////////// bool VariantContainer<unsigned>::ToBool(void) const { return m_value == 0 ? false : true; } /////////////////////////////////////////////////////////////////////// float VariantContainer<unsigned>::ToFloat(void) const { return static_cast<float>( m_value ); } /////////////////////////////////////////////////////////////////////// double VariantContainer<unsigned>::ToDouble(void) const { return static_cast<double>( m_value ); } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<unsigned>::ToString(void) const { return std::to_string( m_value ); } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<unsigned>::Clone(void) const { return new VariantContainer<unsigned>( m_value ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // bool /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region bool VariantContainer<bool>::VariantContainer(const bool &value) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<bool>::VariantContainer(const bool &&value) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<bool>::GetType(void) const { return meta_typeof( bool ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<bool>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<bool>::ToInt(void) const { return m_value ? 1 : 0; } /////////////////////////////////////////////////////////////////////// bool VariantContainer<bool>::ToBool(void) const { return m_value; } /////////////////////////////////////////////////////////////////////// float VariantContainer<bool>::ToFloat(void) const { return m_value ? 1.0f : 0.0f; } /////////////////////////////////////////////////////////////////////// double VariantContainer<bool>::ToDouble(void) const { return m_value ? 1.0 : 0.0; } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<bool>::ToString(void) const { return m_value ? "true" : "false"; } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<bool>::Clone(void) const { return new VariantContainer<bool>( m_value ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // float /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region float VariantContainer<float>::VariantContainer(const float &value) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<float>::VariantContainer(const float &&value) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<float>::GetType(void) const { return meta_typeof( float ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<float>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<float>::ToInt(void) const { return static_cast<int>( m_value ); } /////////////////////////////////////////////////////////////////////// bool VariantContainer<float>::ToBool(void) const { return m_value == 0.0f ? false : true; } /////////////////////////////////////////////////////////////////////// float VariantContainer<float>::ToFloat(void) const { return m_value; } /////////////////////////////////////////////////////////////////////// double VariantContainer<float>::ToDouble(void) const { return static_cast<double>( m_value ); } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<float>::ToString(void) const { return std::to_string( m_value ); } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<float>::Clone(void) const { return new VariantContainer<float>( m_value ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // double /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region double VariantContainer<double>::VariantContainer(const double &value) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<double>::VariantContainer(const double &&value) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<double>::GetType(void) const { return meta_typeof( double ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<double>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<double>::ToInt(void) const { return static_cast<int>( m_value ); } /////////////////////////////////////////////////////////////////////// bool VariantContainer<double>::ToBool(void) const { return m_value == 0.0 ? false : true; } /////////////////////////////////////////////////////////////////////// float VariantContainer<double>::ToFloat(void) const { return static_cast<float>( m_value ); } /////////////////////////////////////////////////////////////////////// double VariantContainer<double>::ToDouble(void) const { return m_value; } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<double>::ToString(void) const { return std::to_string( m_value ); } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<double>::Clone(void) const { return new VariantContainer<double>( m_value ); } #pragma endregion /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// // string /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// #pragma region string VariantContainer<std::string>::VariantContainer( const std::string &value ) : m_value( value ) { } /////////////////////////////////////////////////////////////////////// VariantContainer<std::string>::VariantContainer( const std::string &&value ) : m_value( std::move( value ) ) { } /////////////////////////////////////////////////////////////////////// Type VariantContainer<std::string>::GetType(void) const { return meta_typeof( std::string ); } /////////////////////////////////////////////////////////////////////// void *VariantContainer<std::string>::GetPtr(void) const { return const_cast<void*>( reinterpret_cast<const void*>( std::addressof( m_value ) ) ); } /////////////////////////////////////////////////////////////////////// int VariantContainer<std::string>::ToInt(void) const { return stoi( m_value ); } /////////////////////////////////////////////////////////////////////// bool VariantContainer<std::string>::ToBool(void) const { // 0 -> false // 1 -> true // "true" -> true (case insensitive) // "false" -> false (case insensitive) if (m_value == "0") return false; if (m_value == "1") return true; auto copy = m_value; // convert to lowercase transform( copy.begin( ), copy.end( ), copy.begin( ), tolower ); if (copy == "true") return true; return false; } /////////////////////////////////////////////////////////////////////// float VariantContainer<std::string>::ToFloat(void) const { return stof( m_value ); } /////////////////////////////////////////////////////////////////////// double VariantContainer<std::string>::ToDouble(void) const { return stod( m_value ); } /////////////////////////////////////////////////////////////////////// std::string VariantContainer<std::string>::ToString(void) const { return m_value; } /////////////////////////////////////////////////////////////////////// VariantBase *VariantContainer<std::string>::Clone(void) const { return new VariantContainer<std::string>( m_value ); } #pragma endregion } }
30.866551
80
0.304323
[ "transform" ]
a16b8dc95a7d8f73034de8c7d8335e57cb9b146e
2,150
cpp
C++
Project II Game/Motor2D/Lines.cpp
Sanmopre/Sea_Conquest
52c46c218b38eeaa8f7f224e7bff74ef2cc5d934
[ "Zlib" ]
null
null
null
Project II Game/Motor2D/Lines.cpp
Sanmopre/Sea_Conquest
52c46c218b38eeaa8f7f224e7bff74ef2cc5d934
[ "Zlib" ]
1
2020-03-03T09:56:15.000Z
2020-05-24T22:29:01.000Z
Project II Game/Motor2D/Lines.cpp
Sanmopre/Sea_Conquest
52c46c218b38eeaa8f7f224e7bff74ef2cc5d934
[ "Zlib" ]
null
null
null
#include "j1Render.h" #include "Lines.h" #include "j1Scene.h" #include "j1Scene2.h" #include "j1SceneManager.h" #include "j1App.h" #include "j1Window.h" Lines::Lines(j1Color color, float time, int scene) : j1Transitions(time) { this->color = color; this->scene = scene; App->win->GetWindowSize(w, h); screen = { -(int)w, 0, (int)w, (int)h }; SDL_SetRenderDrawBlendMode(App->render->renderer, SDL_BLENDMODE_BLEND); initial_x_left = App->render->camera.x; initial_x_right = App->render->camera.x + (int)w; for (int i = 0; i < 11; i++) { // All lines have window width as width and height/10 as height lines[i].h = ((int)h / 10); lines[i].w = (int)w; // 5 lines are placed at the left of the screen if (i % 2 == 0) lines[i].x = initial_x_left; // 5 lines are placed at the right of the screen else lines[i].x = initial_x_right; } // Each one is placed h += h/10 than the previous one for (int i = 0; i < 11; i++) { lines[i].y = height; height += h / 10; } } Lines::~Lines() {} void Lines::Start() { j1Transitions::Start(); for (int i = 0; i < 11; i++) { if (i % 2 == 0) lines[i].x = Interpolation(-(int)w, 0, percentage); else lines[i].x = Interpolation((int)w, 0, percentage); } SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); for (int i = 0; i < 11; i++) SDL_RenderFillRect(App->render->renderer, &lines[i]); } void Lines::Change() { j1Transitions::Change(); SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); SDL_RenderFillRect(App->render->renderer, &screen); if (scene == 1) App->scenemanager->ChangeScene(1); if (scene == 2) App->scenemanager->ChangeScene(2); if (scene == 3) App->scenemanager->ChangeScene(3); } void Lines::Exit() { j1Transitions::Exit(); for (int i = 0; i < 11; i++) { if (i % 2 == 0) lines[i].x = Interpolation(0, (int)w, percentage); else lines[i].x = Interpolation(0, -(int)w, percentage); } SDL_SetRenderDrawColor(App->render->renderer, color.r, color.g, color.b, 255); for (int i = 0; i < 11; i++) SDL_RenderFillRect(App->render->renderer, &lines[i]); }
22.164948
79
0.633023
[ "render" ]
a16fbb299772c0b550e38afb47723f57310a427f
1,808
hpp
C++
cpp_sim/Node.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
3
2022-03-12T14:11:56.000Z
2022-03-21T00:48:06.000Z
cpp_sim/Node.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
2
2022-03-22T21:28:05.000Z
2022-03-22T21:28:06.000Z
cpp_sim/Node.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
null
null
null
#pragma once #include <inttypes.h> #include "Array.hpp" #include <vector> #include <random> #include "Hash.hpp" #define SEED_MAX UINT32_MAX #define ID_INVALID (uint32_t)-1 namespace rps { class Node final { private: /* data */ uint32_t _r=0; uint32_t _viewSize; Array<uint32_t> _view; uint32_t* _seeds = nullptr; uint32_t* _hits = nullptr; uint32_t _maliciousCount = 0; uint32_t(*_rankingFunction)(uint32_t, uint32_t); std::random_device _rng; /* private methods */ uint32_t genSeed(); ArrayView<uint32_t> pull() const; void push(ArrayView<uint32_t> view, const Node* sender); uint32_t selectPeer() const; public: void updateView(ArrayView<uint32_t> candidates, const Node* sender=nullptr); uint32_t id; bool isByzantine = false; /* Constructors and assignement operators */ Node(uint32_t viewSize, uint32_t(*rankingFunction)(uint32_t, uint32_t)); Node(){} Node(const Node&) = delete; Node(Node&&); ~Node(); Node& operator=(const Node&) = delete; Node& operator=(Node&&); void init(ArrayView<uint32_t> bootstrap); void step(ArrayView<Node> nodes); /* step method for malicious nodes */ void step(ArrayView<Node> honestNodes, unsigned F); void reset(uint32_t k); /* accessors */ uint32_t seeds(size_t i) const; uint32_t operator[] (size_t i) const; uint32_t viewSize() const; uint32_t maliciousCount() const; }; Array<uint32_t> sample_n(size_t n, const rps::ArrayView<rps::Node>& nodes); } // namespace basalt
29.16129
85
0.58573
[ "vector" ]
a170f4e7dbb98526df300557c0bab378a67c64d6
8,281
cpp
C++
gearoenix/glc3/texture/gx-glc3-txt-cube.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/glc3/texture/gx-glc3-txt-cube.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/glc3/texture/gx-glc3-txt-cube.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#include "gx-glc3-txt-cube.hpp" #ifdef GX_USE_OPENGL_CLASS_3 #include "../../core/gx-cr-function-loader.hpp" #include "../../gl/gx-gl-constants.hpp" #include "../../gl/gx-gl-loader.hpp" #include "../../render/texture/gx-rnd-txt-image.hpp" #include "../../system/stream/gx-sys-stm-local.hpp" #include "../engine/gx-glc3-eng-engine.hpp" #include "gx-glc3-txt-2d.hpp" #include "gx-glc3-txt-sample.hpp" #ifdef GX_DEBUG_MODE //#define GX_DEBUG_TEXTURE_WRITE #endif static const gearoenix::gl::enumerated FACES[] = { GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, }; gearoenix::glc3::texture::TextureCube::TextureCube( const core::Id id, std::string name, const render::texture::TextureFormat texture_format, const render::texture::SamplerInfo& sampler_info, engine::Engine* const engine) noexcept : render::texture::TextureCube(id, std::move(name), texture_format, sampler_info, engine) { } std::shared_ptr<gearoenix::glc3::texture::TextureCube> gearoenix::glc3::texture::TextureCube::construct( const core::Id id, std::string name, engine::Engine* const engine, std::vector<std::vector<std::vector<std::uint8_t>>> data, const render::texture::TextureInfo& info, const std::size_t aspect, const core::sync::EndCaller<core::sync::EndCallerIgnore>& call) noexcept { std::shared_ptr<TextureCube> result(new TextureCube(id, std::move(name), info.format, info.sampler_info, engine)); result->aspect = aspect; const SampleInfo sample_info = SampleInfo(info.sampler_info); const auto internal_format = Texture2D::convert_internal_format(engine, result->texture_format); const auto format = Texture2D::convert_format(result->texture_format); const auto data_format = Texture2D::convert_data_format(result->texture_format); const auto gl_aspect = static_cast<gl::sizei>(aspect); std::vector<std::vector<std::vector<std::uint8_t>>> pixels; if (data.empty() || data[0].empty() || data[0][0].empty()) { pixels.resize(6); std::vector<std::vector<std::uint8_t>> black(1); black[0].resize(aspect * aspect * 16); for (auto& p : black[0]) p = 0; pixels[0] = black; pixels[1] = black; pixels[2] = black; pixels[3] = black; pixels[4] = black; pixels[5] = std::move(black); } else { switch (info.format) { case render::texture::TextureFormat::RgbaFloat32: { if (engine->get_engine_type() == render::engine::Type::OpenGLES3) { pixels = convert_float_pixels(data, 4, 4); } else { pixels = std::move(data); } break; } case render::texture::TextureFormat::RgbaUint8: { pixels = std::move(data); break; } default: GXLOGF("Unsupported/Unimplemented setting for cube texture with id " << id) } } engine->get_function_loader()->load([result, needs_mipmap { info.has_mipmap }, gl_aspect, pixels { move(pixels) }, internal_format, format, data_format, sample_info, call] { gl::Loader::gen_textures(1, &(result->texture_object)); gl::Loader::bind_texture(GL_TEXTURE_CUBE_MAP, result->texture_object); gl::Loader::tex_parameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, sample_info.mag_filter); gl::Loader::tex_parameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, sample_info.min_filter); gl::Loader::tex_parameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, sample_info.wrap_s); gl::Loader::tex_parameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, sample_info.wrap_t); for (int fi = 0; fi < static_cast<int>(GX_COUNT_OF(FACES)); ++fi) { const auto& face_pixels = pixels[fi]; auto level_aspect = gl_aspect; for (std::size_t level_index = 0; level_index < face_pixels.size(); ++level_index, level_aspect >>= 1u) { gl::Loader::tex_image_2d( FACES[fi], static_cast<gl::sint>(level_index), internal_format, level_aspect, level_aspect, 0, format, data_format, face_pixels[level_index].data()); } } #ifdef GX_DEBUG_GL_CLASS_3 gl::Loader::check_for_error(); #endif if (needs_mipmap && pixels[0].size() < 2) { gl::Loader::generate_mipmap(GL_TEXTURE_CUBE_MAP); // It clears the errors, some drivers does not support mip-map generation for cube texture gl::Loader::get_error(); } }); return result; } gearoenix::glc3::texture::TextureCube::~TextureCube() noexcept { if (texture_object == 0) return; const gl::uint c_texture_object = texture_object; render_engine->get_function_loader()->load([c_texture_object] { gl::Loader::bind_texture(GL_TEXTURE_CUBE_MAP, 0); gl::Loader::delete_textures(1, &c_texture_object); }); texture_object = 0; } void gearoenix::glc3::texture::TextureCube::write_gx3d( const std::shared_ptr<system::stream::Stream>& s, const gearoenix::core::sync::EndCaller<gearoenix::core::sync::EndCallerIgnore>& end_call) noexcept { render::texture::TextureCube::write_gx3d(s, end_call); render_engine->get_function_loader()->load([this, s, end_call] { gl::uint framebuffer; gl::Loader::gen_framebuffers(1, &framebuffer); gl::Loader::bind_framebuffer(GL_FRAMEBUFFER, framebuffer); bind(); (void)s->write(true); // It means, texture has mipmap data if (render::texture::format_has_float_component(texture_format)) { std::vector<float> data(aspect * aspect * 4); for (auto i : FACES) { auto level_aspect = static_cast<gl::sizei>(aspect); for (gl::sint j = 0; level_aspect > 0; ++j, level_aspect >>= 1u) { gl::Loader::framebuffer_texture_2d(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, i, texture_object, j); gl::Loader::read_pixels(0, 0, level_aspect, level_aspect, GL_RGBA, GL_FLOAT, data.data()); #ifdef GX_DEBUG_TEXTURE_WRITE system::stream::Local l( "texture-cube-glc3-id" + std::to_string(asset_id) + "-face" + std::to_string(i) + "-level" + std::to_string(j) + ".hdr", true); render::texture::Image::encode_hdr(&l, data.data(), level_aspect, level_aspect, 4); #endif write_gx3d_image(s.get(), data.data(), level_aspect, level_aspect, 4); } } } else { std::vector<unsigned char> data(aspect * aspect * 4); for (auto i : FACES) { auto level_aspect = static_cast<gl::sizei>(aspect); for (gl::sint j = 0; level_aspect > 0; ++j, level_aspect >>= 1u) { gl::Loader::framebuffer_texture_2d(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, i, texture_object, j); gl::Loader::read_pixels(0, 0, level_aspect, level_aspect, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); #ifdef GX_DEBUG_TEXTURE_WRITE system::stream::Local l( "texture-cube-glc3-id" + std::to_string(asset_id) + "-face" + std::to_string(i) + "-level" + std::to_string(j) + ".png", true); render::texture::Image::encode_png(&l, data.data(), level_aspect, level_aspect, 4); #endif write_gx3d_image(s.get(), data.data(), level_aspect, level_aspect, 4); } } } gl::Loader::bind_framebuffer(GL_FRAMEBUFFER, 0); gl::Loader::delete_framebuffers(1, &framebuffer); }); } void gearoenix::glc3::texture::TextureCube::bind(gl::enumerated texture_unit) const noexcept { gl::Loader::active_texture(GL_TEXTURE0 + texture_unit); bind(); } void gearoenix::glc3::texture::TextureCube::bind() const noexcept { gl::Loader::bind_texture(GL_TEXTURE_CUBE_MAP, texture_object); } void gearoenix::glc3::texture::TextureCube::generate_mipmap() const noexcept { bind(); gl::Loader::generate_mipmap(GL_TEXTURE_CUBE_MAP); } #endif
44.047872
177
0.639295
[ "render", "vector" ]
a170f868e4c14c1a637dbe10e369ef7067422e9e
11,400
cpp
C++
MindlessEngine/src/window.cpp
morswin22/mindless
293070c90d47a675c39ca9dae629a81407bbdaa7
[ "MIT" ]
null
null
null
MindlessEngine/src/window.cpp
morswin22/mindless
293070c90d47a675c39ca9dae629a81407bbdaa7
[ "MIT" ]
null
null
null
MindlessEngine/src/window.cpp
morswin22/mindless
293070c90d47a675c39ca9dae629a81407bbdaa7
[ "MIT" ]
null
null
null
#include <MindlessEngine/window.hpp> #include <MindlessEngine/input.hpp> #include <MindlessEngine/math.hpp> #include <glm/gtc/matrix_transform.hpp> #include <sstream> #include <iostream> namespace MindlessEngine { Constraints::Constraints(float left, float right, float top, float bottom) : left(left), right(right), top(top), bottom(bottom) {} Constraints operator+(const Constraints& constraints, const glm::vec3& offset) { return { constraints.left + offset.x, constraints.right + offset.x, constraints.top + offset.y, constraints.bottom + offset.y }; } Camera::Camera(float left, float right, float bottom, float top) : projectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), viewMatrix(1.0f), position(0.0f, 0.0f, 0.0f), rotation(0.0f), constraints(left, right, bottom, top), scale(1.0f) { viewProjectionMatrix = projectionMatrix * viewMatrix; } void Camera::recalculateViewMatrix() { glm::mat4 transform = glm::translate(glm::mat4(1.0f), position); transform = glm::rotate(transform, rotation, glm::vec3(0.0, 0.0, 1.0f)); viewMatrix = glm::inverse(transform); viewProjectionMatrix = projectionMatrix * viewMatrix; } const glm::vec3& Camera::getPosition() const { return position; } float Camera::getRotation() const { return rotation; } void Camera::setProjection(float left, float right, float bottom, float top) { projectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); viewProjectionMatrix = projectionMatrix * viewMatrix; constraints = { left, right, bottom, top }; } void Camera::setPosition(const glm::vec3& position) { this->position = position; recalculateViewMatrix(); } void Camera::setRotation(float rotation) { this->rotation = rotation; recalculateViewMatrix(); } void Camera::setScale(float scale) { const float scaleFactor = scale / this->scale; setProjection(constraints.left * scaleFactor, constraints.right * scaleFactor, constraints.top * scaleFactor, constraints.bottom * scaleFactor); this->scale = scale; } void Camera::moveTo(const Vector& position) { this->position = { position.x, position.y, 0.0f }; recalculateViewMatrix(); } void Camera::move(const Vector& amount) { position += glm::vec3(amount.x, amount.y, 0.0f); recalculateViewMatrix(); } const glm::mat4& Camera::getProjectionMatrix() const { return projectionMatrix; } const glm::mat4& Camera::getViewMatrix() const { return viewMatrix; } const glm::mat4& Camera::getViewProjectionMatrix() const { return viewProjectionMatrix; } Constraints Camera::getConstraints() const { return constraints + position; } float Camera::getScale() const { return scale; } void Camera::handleWASD() { float dx = 0.0f; float dy = 0.0f; if (Keyboard::isPressed(Keys::W)) dy++; if (Keyboard::isPressed(Keys::S)) dy--; if (Keyboard::isPressed(Keys::A)) dx--; if (Keyboard::isPressed(Keys::D)) dx++; if (dx != 0.0f || dy != 0.0f) move(normalize({ dx, dy }) * scale * 8.0f); } void Camera::handleScroll() { const float scrollY = Mouse::getScrollY(); if (scrollY != 0.0f) { const float amount = (scrollY > 0.0f) ? 0.8f : 1.25f; setScale(scale * amount); } } void GLAPIENTRY GLMessageCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) { if ( type == GL_DEBUG_TYPE_ERROR ) fprintf( stderr, "GL CALLBACK: type = 0x%x, severity = 0x%x, message = %s\n", type, severity, message ); } Window::Window(int width, int height, const std::string& title, const std::string& shaderVertPath, const std::string& shaderFragPath) : window(nullptr), width(width), height(height), title(title), shader(nullptr), desiredFrameRate(60.0f), desiredInterval(1.0f / desiredFrameRate), lastMeasuredTime(0), camera(-width * 0.5f, width * 0.5f, -height * 0.5f, height * 0.5f) { if (!glfwInit()) return; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (!window) { glfwTerminate(); return; } glfwMakeContextCurrent(window); glfwSwapInterval(0); if (glewInit() != GLEW_OK) return; glEnable(GL_PROGRAM_POINT_SIZE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(GLMessageCallback, 0); glfwSetKeyCallback(window, keyboardCallback); glfwSetMouseButtonCallback(window, mouseCallback); glfwSetScrollCallback(window, scrollCallback); shader = createRef<Shader>(shaderVertPath, shaderFragPath); Renderer::init(shader, width, height, rendererBuffer); } Window::~Window() { Renderer::shutdown(); glfwDestroyWindow(window); glfwTerminate(); } void Window::setTitle(const std::string& title) { this->title = title; glfwSetWindowTitle(window, title.c_str()); } std::string Window::getTitle() const { return title; } GLuint Window::getRendererBuffer() const { return rendererBuffer; } bool Window::shouldClose() const { return glfwWindowShouldClose(window); } void Window::getCursorPosition(Vector& v) const { double x, y; glfwGetCursorPos(window, &x, &y); v.x = (float) x; v.y = (float) y; } void Window::getFrameSize() { int newWidth, newHeight; glfwGetFramebufferSize(window, &newWidth, &newHeight); if (newWidth == width && newHeight == height) return; width = newWidth; height = newHeight; glViewport(0, 0, width, height); const float scale = camera.getScale(); camera.setProjection(-width * 0.5f * scale, width * 0.5f * scale, -height * 0.5f * scale, height * 0.5f * scale); glBindTexture(GL_TEXTURE_2D, rendererBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindTexture(GL_TEXTURE_2D, 0); } void Window::clear() const { glClear(GL_COLOR_BUFFER_BIT); } void Window::swapBuffers() const { glfwSwapBuffers(window); } void Window::pollEvents() const { glfwPollEvents(); } float Window::getElapsedTime() { while ((float) glfwGetTime() - lastMeasuredTime < desiredInterval && !shouldClose()) pollEvents(); float temp = lastMeasuredTime; lastMeasuredTime = (float) glfwGetTime(); return lastMeasuredTime - temp; } void Window::setSize(int width, int height) { glfwSetWindowSize(window, width, height); glViewport(0, 0, width, height); this->width = width; this->height = height; const float scale = camera.getScale(); camera.setProjection(-width * 0.5f * scale, width * 0.5f * scale, -height * 0.5f * scale, height * 0.5f * scale); glBindTexture(GL_TEXTURE_2D, rendererBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindTexture(GL_TEXTURE_2D, 0); } void Window::setBackground(const Color& color) { glClearColor(color.r, color.g, color.b, color.a); } void Window::setDesiredFrameRate(float desiredFrameRate) { this->desiredFrameRate = desiredFrameRate; desiredInterval = 1.0f / desiredFrameRate; } float Window::getDesiredFrameRate() const { return desiredFrameRate; } void Window::draw(Ref<Body>& body) { if (body->isStroked) { Vector* vertices = body->getTransformedVertices(); int numVertices = body->getNumVertices(); for (int j = 0; j < numVertices; j++) draw(vertices[j], vertices[(j + 1) % numVertices], 1.0f, body->strokeColor); } if (body->isAnimated) { glm::vec4* frame = body->animationAtlas->getAnimation(body->animationState.currentName)->getNext(body->animationState); Vector* vertices = body->useTextureVertices ? body->getTextureVertices() : body->getTransformedVertices(); Renderer::draw(vertices[0], vertices[1], vertices[2], vertices[3], body->textureIndex, *frame, body->fillColor); } else if (body->isTextured) { Vector* vertices = body->useTextureVertices ? body->getTextureVertices() : body->getTransformedVertices(); Renderer::draw(vertices[0], vertices[1], vertices[2], vertices[3], body->textureIndex, body->texturePositions, body->fillColor); } else if (body->isFilled) { Renderer::draw(body->getTransformedVertices(), body->getNumVertices(), body->getTriangles(), body->fillColor); } } void Window::draw(const AABB& aabb, const Color& color) { Vector a(aabb.min.x, aabb.min.y); Vector b(aabb.max.x, aabb.min.y); Vector c(aabb.max.x, aabb.max.y); Vector d(aabb.min.x, aabb.max.y); draw(a, b, 1.0, color); draw(b, c, 1.0, color); draw(c, d, 1.0, color); draw(d, a, 1.0, color); } void Window::draw(const Vector& a, const Vector& b, float weight, const Color& color) { Vector line = b - a; const float scale = camera.getScale(); Vector axis = normalize(line) * weight * scale; Vector normal = normalize({ -axis.y, axis.x }) * weight * scale; Vector vertices[4]{ a + normal - axis, a - normal - axis, b - normal + axis, b + normal + axis }; constexpr uint32_t triangles[6]{ 0, 1, 2, 2, 3, 0 }; Renderer::draw(vertices, 4, triangles, color); } void Window::draw(Ref<FontAtlas>& atlas, const Vector& position, const std::string& text, float scale, const Color& color) { std::stringstream ss(text); std::string line; if (text.size() == 0.0f) return; float lineOffset = 0.0f; while(std::getline(ss, line, '\n')) { glm::vec4 texturePositions[line.size()]; GLuint texture = atlas->get(line, texturePositions); glm::vec2 offsets = atlas->getOffsets() * scale; for (float i = 0; i < line.size(); i++) { Renderer::draw( {position.x + i * offsets.x, position.y - lineOffset}, {position.x + (i + 1.0f) * offsets.x, position.y - lineOffset}, {position.x + (i + 1.0f) * offsets.x, position.y - offsets.y - lineOffset}, {position.x + i * offsets.x, position.y - offsets.y - lineOffset}, texture, texturePositions[(int)i], color ); } lineOffset += offsets.y; } } void Window::draw(const Ref<LightScene>& scene, const Color& nightColor, float darkness) { const float scale = camera.getScale(); scene->render( nightColor, darkness, camera.getPosition(), { width * scale, height * scale }, rendererBuffer ); } void Window::draw(const Vector& position, float size, const WFC::Tile* tile, const Color& color) { Renderer::draw( {position.x + tile->ab.x * size, position.y + tile->ab.y * size}, {position.x + tile->ab.z * size, position.y + tile->ab.w * size}, {position.x + tile->cd.x * size, position.y + tile->cd.y * size}, {position.x + tile->cd.z * size, position.y + tile->cd.w * size}, tile->texture, tile->textureCoords, color ); } };
27.669903
148
0.644211
[ "render", "vector", "transform" ]
a173340db7229d778c23f96d103964c6d285aa37
9,524
cpp
C++
addons/ofxOculusRift/libs/LibOVR/Src/OVR_OSX_DeviceManager.cpp
colejd/OculusEye
3fb408721a47640ce841904e5474d5bf51329475
[ "MIT" ]
1
2018-08-30T05:28:15.000Z
2018-08-30T05:28:15.000Z
addons/ofxOculusRift/libs/LibOVR/Src/OVR_OSX_DeviceManager.cpp
colejd/OculusEye
3fb408721a47640ce841904e5474d5bf51329475
[ "MIT" ]
null
null
null
addons/ofxOculusRift/libs/LibOVR/Src/OVR_OSX_DeviceManager.cpp
colejd/OculusEye
3fb408721a47640ce841904e5474d5bf51329475
[ "MIT" ]
null
null
null
/************************************************************************************ Filename : OVR_OSX_DeviceManager.cpp Content : OSX specific DeviceManager implementation. Created : March 14, 2013 Authors : Lee Cooper Copyright : Copyright 2013 Oculus VR, Inc. All Rights reserved. Use of this software is subject to the terms of the Oculus license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. *************************************************************************************/ #include "OVR_OSX_DeviceManager.h" // Sensor & HMD Factories #include "OVR_LatencyTestImpl.h" #include "OVR_SensorImpl.h" #include "OVR_OSX_HMDDevice.h" #include "OVR_OSX_HIDDevice.h" #include "Kernel/OVR_Timer.h" #include "Kernel/OVR_Std.h" #include "Kernel/OVR_Log.h" #include <IOKit/hid/IOHIDManager.h> #include <IOKit/hid/IOHIDKeys.h> namespace OVR { namespace OSX { //------------------------------------------------------------------------------------- // **** OSX::DeviceManager DeviceManager::DeviceManager() { } DeviceManager::~DeviceManager() { } bool DeviceManager::Initialize(DeviceBase*) { if (!DeviceManagerImpl::Initialize(0)) return false; // Start the background thread. pThread = *new DeviceManagerThread(); if (!pThread || !pThread->Start()) return false; // Wait for the thread to be fully up and running. pThread->StartupEvent.Wait(); // Do this now that we know the thread's run loop. HidDeviceManager = *HIDDeviceManager::CreateInternal(this); pCreateDesc->pDevice = this; LogText("OVR::DeviceManager - initialized.\n"); return true; } void DeviceManager::Shutdown() { LogText("OVR::DeviceManager - shutting down.\n"); // Set Manager shutdown marker variable; this prevents // any existing DeviceHandle objects from accessing device. pCreateDesc->pLock->pManager = 0; // Push for thread shutdown *WITH NO WAIT*. // This will have the following effect: // - Exit command will get enqueued, which will be executed later on the thread itself. // - Beyond this point, this DeviceManager object may be deleted by our caller. // - Other commands, such as CreateDevice, may execute before ExitCommand, but they will // fail gracefully due to pLock->pManager == 0. Future commands can't be enqued // after pManager is null. // - Once ExitCommand executes, ThreadCommand::Run loop will exit and release the last // reference to the thread object. pThread->PushExitCommand(false); pThread.Clear(); DeviceManagerImpl::Shutdown(); } ThreadCommandQueue* DeviceManager::GetThreadQueue() { return pThread; } bool DeviceManager::GetDeviceInfo(DeviceInfo* info) const { if ((info->InfoClassType != Device_Manager) && (info->InfoClassType != Device_None)) return false; info->Type = Device_Manager; info->Version = 0; OVR_strcpy(info->ProductName, DeviceInfo::MaxNameLength, "DeviceManager"); OVR_strcpy(info->Manufacturer,DeviceInfo::MaxNameLength, "Oculus VR, Inc."); return true; } DeviceEnumerator<> DeviceManager::EnumerateDevicesEx(const DeviceEnumerationArgs& args) { // TBD: Can this be avoided in the future, once proper device notification is in place? pThread->PushCall((DeviceManagerImpl*)this, &DeviceManager::EnumerateAllFactoryDevices, true); return DeviceManagerImpl::EnumerateDevicesEx(args); } //------------------------------------------------------------------------------------- // ***** DeviceManager Thread DeviceManagerThread::DeviceManagerThread() : Thread(ThreadStackSize) { } DeviceManagerThread::~DeviceManagerThread() { } int DeviceManagerThread::Run() { SetThreadName("OVR::DeviceManagerThread"); LogText("OVR::DeviceManagerThread - running (ThreadId=0x%p).\n", GetThreadId()); // Store out the run loop ref. RunLoop = CFRunLoopGetCurrent(); // Create a 'source' to enable us to signal the run loop to process the command queue. CFRunLoopSourceContext sourceContext; memset(&sourceContext, 0, sizeof(sourceContext)); sourceContext.version = 0; sourceContext.info = this; sourceContext.perform = &staticCommandQueueSourceCallback; CommandQueueSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0 , &sourceContext); CFRunLoopAddSource(RunLoop, CommandQueueSource, kCFRunLoopDefaultMode); // Signal to the parent thread that initialization has finished. StartupEvent.SetEvent(); ThreadCommand::PopBuffer command; while(!IsExiting()) { // PopCommand will reset event on empty queue. if (PopCommand(&command)) { command.Execute(); } else { SInt32 exitReason = 0; do { UInt32 waitMs = INT_MAX; // If devices have time-dependent logic registered, get the longest wait // allowed based on current ticks. if (!TicksNotifiers.IsEmpty()) { UInt64 ticksMks = Timer::GetTicks(); UInt32 waitAllowed; for (UPInt j = 0; j < TicksNotifiers.GetSize(); j++) { waitAllowed = (UInt32)(TicksNotifiers[j]->OnTicks(ticksMks) / Timer::MksPerMs); if (waitAllowed < waitMs) waitMs = waitAllowed; } } // Enter blocking run loop. We may continue until we timeout in which // case it's time to service the ticks. Or if commands arrive in the command // queue then the source callback will call 'CFRunLoopStop' causing this // to return. CFTimeInterval blockInterval = 0.001 * (double) waitMs; exitReason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, blockInterval, false); if (exitReason == kCFRunLoopRunFinished) { // Maybe this will occur during shutdown? break; } else if (exitReason == kCFRunLoopRunStopped ) { // Commands need processing or we're being shutdown. break; } else if (exitReason == kCFRunLoopRunTimedOut) { // Timed out so that we can service our ticks callbacks. continue; } else if (exitReason == kCFRunLoopRunHandledSource) { // Should never occur since the last param when we call // 'CFRunLoopRunInMode' is false. OVR_ASSERT(false); break; } else { OVR_ASSERT_LOG(false, ("CFRunLoopRunInMode returned unexpected code")); break; } } while(true); } } CFRunLoopRemoveSource(RunLoop, CommandQueueSource, kCFRunLoopDefaultMode); CFRelease(CommandQueueSource); LogText("OVR::DeviceManagerThread - exiting (ThreadId=0x%p).\n", GetThreadId()); return 0; } void DeviceManagerThread::staticCommandQueueSourceCallback(void* pContext) { DeviceManagerThread* pThread = (DeviceManagerThread*) pContext; pThread->commandQueueSourceCallback(); } void DeviceManagerThread::commandQueueSourceCallback() { CFRunLoopStop(RunLoop); } bool DeviceManagerThread::AddTicksNotifier(Notifier* notify) { TicksNotifiers.PushBack(notify); return true; } bool DeviceManagerThread::RemoveTicksNotifier(Notifier* notify) { for (UPInt i = 0; i < TicksNotifiers.GetSize(); i++) { if (TicksNotifiers[i] == notify) { TicksNotifiers.RemoveAt(i); return true; } } return false; } } // namespace OSX //------------------------------------------------------------------------------------- // ***** Creation // Creates a new DeviceManager and initializes OVR. DeviceManager* DeviceManager::Create() { if (!System::IsInitialized()) { // Use custom message, since Log is not yet installed. OVR_DEBUG_STATEMENT(Log::GetDefaultLog()-> LogMessage(Log_Debug, "DeviceManager::Create failed - OVR::System not initialized"); ); return 0; } Ptr<OSX::DeviceManager> manager = *new OSX::DeviceManager; if (manager) { if (manager->Initialize(0)) { manager->AddFactory(&LatencyTestDeviceFactory::Instance); manager->AddFactory(&SensorDeviceFactory::Instance); manager->AddFactory(&OSX::HMDDeviceFactory::Instance); manager->AddRef(); } else { manager.Clear(); } } return manager.GetPtr(); } } // namespace OVR
31.22623
104
0.567934
[ "object" ]
a17601eac230ec8f50e06a8cb2f7bb52a8fe948e
1,700
cpp
C++
Model Algorithms/Dynamic Programming/Knapsack/0-1 KnapSack.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
13
2021-09-02T07:30:02.000Z
2022-03-22T19:32:03.000Z
Model Algorithms/Dynamic Programming/Knapsack/0-1 KnapSack.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
null
null
null
Model Algorithms/Dynamic Programming/Knapsack/0-1 KnapSack.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
3
2021-08-24T16:06:22.000Z
2021-09-17T15:39:53.000Z
/* Author: Utkarsh Ashok Pathrabe * Algorithm: Getting the 0-1 Knapsack value using Tabulation (Bottom Up) */ /* Problem Statement: Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer * arrays val[0...n-1] and wt[0...n-1] which represent values and weights associated with n items respectively, also given an integer W which represents knapsack capacity, find out the * maximum value of this subset which is smaller than or equal to W. You cannot break an item, either pick the complete item, or don't pick it(0-1 property). */ /* Time Complexity: O(nW) where n is the number of items and W is the capacity of knapsack. */ #include <bits/stdc++.h> using namespace std; int KnapSack (int W, vector<int> &val, vector<int> &wt, int n) { int KS[n + 1][W + 1]; for (int i = 0; i <= n; i++) { for (int w = 0; w <= W; w++) { if (i == 0 || w == 0) { KS[i][w] = 0; } else if (wt[i - 1] > W) { KS[i][w] = KS[i - 1][w]; } else { KS[i][w] = max(val[i - 1] + KS[i - 1][w - wt[i - 1]], KS[i - 1][w]); } } } return KS[n][W]; } int main (void) { int W, n; cout << "Enter the number of items and the maximum capacity:" << endl; cin >> n >> W; vector<int> val; vector<int> wt; for (int i = 0; i < n; i++) { int v, w; cout << "Enter value and weight of " << (i + 1) << " item:" << endl; cin >> v >> w; val.push_back(v); wt.push_back(w); } cout << "The maximum sum of values that we can get (given the restrictions on weights) is:" << KnapSack(W, val, wt, n) << endl; val.erase(val.begin(), val.end()); wt.erase(wt.begin(), wt.end()); return 0; }
34
184
0.614118
[ "vector" ]
a17655800687fb52e869b0ddbf5cc2025ef177c3
1,274
hpp
C++
TileMap.hpp
Sparkolo/Codename-LightOfTheMoon
03579d0c47c05df16e6dd0cf946947688dbe2273
[ "MIT" ]
null
null
null
TileMap.hpp
Sparkolo/Codename-LightOfTheMoon
03579d0c47c05df16e6dd0cf946947688dbe2273
[ "MIT" ]
null
null
null
TileMap.hpp
Sparkolo/Codename-LightOfTheMoon
03579d0c47c05df16e6dd0cf946947688dbe2273
[ "MIT" ]
null
null
null
/* * Created by Jeppe Faber on 05/12/2019. * LIST OF EDITS (reverse chronological order - add last on top): * + * + Jeppe Faber [05/12/19] - Basic implementation - Tilemap reads json file for structure. */ #pragma once #include <vector> #include <string> #include "sre/Sprite.hpp" #include "sre/SpriteBatch.hpp" class TileMap{ public: explicit TileMap(); /*Load the tileMap from a json file*/ void loadMap(std::string filename); void clearMap(); void printMap();//Prints the tilemap indexes in a matrix form void renderMap(sre::SpriteBatch::SpriteBatchBuilder& spriteBatchBuilder); void loadSprites(std::shared_ptr<sre::SpriteAtlas>); /*Generate every necessary edge colliders for each tile*/ void generateColliders(); private: /*Returns a matrix with information regarding the empty tiles of the tilemap, including the extended borders. * tileMap has size n*m, the function return a (n+1)*(m+1) matrix */ std::vector<std::vector<bool>> calculateBorderCells(); void generateEdgeBottomLeft(int i, int j); void generateEdgeBottomRight(int i, int j); void generateEdgeTopLeft(int i, int j); void generateEdgeTopRight(int i, int j); std::vector<std::vector<int>> tileMap; int tileHeight; int tileWidth; std::vector<sre::Sprite> sprites; };
26
110
0.734694
[ "vector" ]
a1793312614abc4e0339a36cf4dec27d03b78f0f
11,327
cc
C++
test/t_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
21
2019-03-18T18:35:35.000Z
2022-01-27T06:57:47.000Z
test/t_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
105
2019-01-19T07:09:25.000Z
2021-01-11T20:06:24.000Z
test/t_util.cc
LeeOHzzZ/ILAng
24225294ac133e5d08af5037350ede8f78610c45
[ "MIT" ]
7
2019-01-28T19:48:09.000Z
2020-11-05T14:42:05.000Z
/// \file /// Unit test for utility functions #include <vector> #include <ilang/util/fs.h> #include <ilang/util/str_util.h> #include "unit-include/config.h" #include "unit-include/util.h" namespace ilang { void RecordLog() { // precondition for log test SetLogLevel(0); // log all SetLogPath(""); // log to /tmp SetToStdErr(1); // log to stderr for easy catching } void EndRecordLog() { // reset to default condition SetLogLevel(0); // log all SetLogPath(""); // log to /tmp SetToStdErr(0); // not log to stderr } #define EXPECT_ERROR(m) \ do { \ RecordLog(); \ std::string error_msg; \ GET_STDERR_MSG(m, error_msg); \ EndRecordLog(); \ } while (0); #if defined(_WIN32) || defined(_WIN64) TEST(TestUtil, DirAppend) { EXPECT_EQ(os_portable_join_dir({}), ""); EXPECT_EQ(os_portable_append_dir("\\a", "b"), "\\a\\b"); EXPECT_EQ(os_portable_append_dir("\\a\\", "b"), "\\a\\b"); EXPECT_EQ(os_portable_append_dir("a\\", "b"), "a\\b"); EXPECT_EQ(os_portable_append_dir("a", "b"), "a\\b"); EXPECT_EQ(os_portable_append_dir("a\\", ".\\b"), "a\\.\\b"); EXPECT_EQ(os_portable_append_dir("\\a\\", ".\\b"), "\\a\\.\\b"); EXPECT_ERROR(os_portable_append_dir("a", "\\b")); EXPECT_ERROR(os_portable_append_dir("\\a\\", "\\b")); EXPECT_ERROR(os_portable_append_dir("\\a", "\\b")); EXPECT_EQ(os_portable_append_dir("a", {"b", "c"}), "a\\b\\c"); } #else TEST(TestUtil, DirAppend) { EXPECT_EQ(os_portable_join_dir({}), ""); EXPECT_EQ(os_portable_append_dir("/a", "b"), "/a/b"); EXPECT_EQ(os_portable_append_dir("/a/", "b"), "/a/b"); EXPECT_EQ(os_portable_append_dir("a/", "b"), "a/b"); EXPECT_EQ(os_portable_append_dir("a", "b"), "a/b"); EXPECT_EQ(os_portable_append_dir("a/", "./b"), "a/./b"); EXPECT_EQ(os_portable_append_dir("/a/", "./b"), "/a/./b"); EXPECT_ERROR(os_portable_append_dir("a", "/b")); EXPECT_ERROR(os_portable_append_dir("/a/", "/b")); EXPECT_ERROR(os_portable_append_dir("/a", "/b")); EXPECT_EQ(os_portable_append_dir("/a", std::vector<std::string>({"b", "c"})), "/a/b/c"); } #endif TEST(TestUtil, CopyDir) { auto src_dir = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), {"unit-data", "fs", "cpsrc"}); auto dst_dir = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), {"unit-data", "fs", "cpdst"}); auto dummy_path = os_portable_append_dir(dst_dir, "dummy"); EXPECT_TRUE(os_portable_mkdir(dst_dir)); EXPECT_TRUE(os_portable_copy_dir(src_dir, dst_dir)); EXPECT_TRUE(fs::exists(dummy_path)); EXPECT_FALSE(fs::is_directory(dummy_path)); EXPECT_FALSE(os_portable_mkdir(dummy_path)); EXPECT_TRUE(fs::exists(dummy_path)); EXPECT_FALSE(fs::is_directory(dummy_path)); } #if defined(_WIN32) || defined(_WIN64) TEST(TestUtil, FileNameFromDir) { EXPECT_EQ(os_portable_remove_file_name_extension(".\\a"), ".\\a"); EXPECT_EQ(os_portable_remove_file_name_extension(".\\a.out"), ".\\a"); EXPECT_EQ(os_portable_remove_file_name_extension("a.out"), "a"); EXPECT_EQ(os_portable_remove_file_name_extension("a"), "a"); EXPECT_EQ(os_portable_path_from_path("a"), ".\\"); EXPECT_EQ(os_portable_file_name_from_path("a"), "a"); EXPECT_EQ(os_portable_file_name_from_path("a\\b"), "b"); EXPECT_EQ(os_portable_file_name_from_path(".\\a\\b"), "b"); EXPECT_ERROR(os_portable_file_name_from_path("a\\")); } #else TEST(TestUtil, FileNameFromDir) { EXPECT_EQ(os_portable_remove_file_name_extension("./a"), "./a"); EXPECT_EQ(os_portable_remove_file_name_extension("./a.out"), "./a"); EXPECT_EQ(os_portable_remove_file_name_extension("a.out"), "a"); EXPECT_EQ(os_portable_remove_file_name_extension("a"), "a"); EXPECT_EQ(os_portable_path_from_path("a"), "./"); EXPECT_EQ(os_portable_file_name_from_path("a"), "a"); EXPECT_EQ(os_portable_file_name_from_path("a/b"), "b"); EXPECT_EQ(os_portable_file_name_from_path("./a/b"), "b"); EXPECT_ERROR(os_portable_file_name_from_path("a/")); } #endif #if defined(__unix__) || defined(unix) || defined(__APPLE__) || \ defined(__MACH__) || defined(__linux__) || defined(__FreeBSD__) TEST(TestUtil, ExecShell) { typedef std::vector<std::string> P; auto scriptName = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), P({"unit-data", "shell_ex", "shell.sh"})); std::vector<std::string> cmd; cmd.push_back("bash"); cmd.push_back(scriptName); auto res = os_portable_execute_shell(cmd); EXPECT_EQ(res.failure, execute_result::NONE); } TEST(TestUtil, ExecShellOSPath) { auto scriptName = "ls"; std::vector<std::string> cmd; cmd.push_back(scriptName); auto res = os_portable_execute_shell(cmd); EXPECT_EQ(res.failure, execute_result::NONE); } TEST(TestUtil, ExecShellRedirect) { auto redirect_file = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), {"unit-data", "shell_ex", "date_out.txt"}); auto pid_file = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), {"unit-data", "shell_ex", "pid_out.txt"}); auto scriptName = "date"; std::vector<std::string> cmd; cmd.push_back(scriptName); execute_result res; res = os_portable_execute_shell(cmd, redirect_file, BOTH, 0, pid_file); EXPECT_EQ(res.failure, execute_result::NONE); std::ifstream d1(redirect_file); std::string l1; EXPECT_TRUE(d1.is_open()); if (d1.is_open()) { std::getline(d1, l1); d1.close(); } sleep(2); // wait for at ~ 2 seconds res = os_portable_execute_shell(cmd, redirect_file, BOTH, 0, pid_file); EXPECT_EQ(res.failure, execute_result::NONE); std::ifstream d2(redirect_file); std::string l2; EXPECT_TRUE(d2.is_open()); if (d2.is_open()) { std::getline(d2, l2); d2.close(); } EXPECT_TRUE(l1 != l2); } TEST(TestUtil, ExecShellRedirectTimeOut) { auto redirect_file = os_portable_append_dir(std::string(ILANG_TEST_SRC_ROOT), {"unit-data", "shell_ex", "sleep_out.txt"}); std::vector<std::string> s1cmd({"sleep", "1"}); std::vector<std::string> s10cmd({"sleep", "10"}); execute_result res; res = os_portable_execute_shell(s1cmd, redirect_file, BOTH, 5); EXPECT_TRUE(res.failure == execute_result::NONE); EXPECT_EQ(res.timeout, false); EXPECT_EQ(res.ret, 0); res = os_portable_execute_shell(s10cmd, redirect_file, BOTH, 2); EXPECT_EQ(res.failure, execute_result::NONE); EXPECT_EQ(res.timeout, true); // EXPECT_EQ(res.ret, 0); if timeout return value not usable } #endif TEST(TestUtil, RegularExpr) { if (IsRExprUsable()) { auto l = ReFindList("s1 == 2", "[A-Za-z0-9]+"); EXPECT_EQ(l.size(), 2); EXPECT_EQ(l[0], "s1"); EXPECT_EQ(l[1], "2"); auto l2 = ReFindAndDo("s1 == 2", "[A-Za-z0-9]+", [](std::string s) -> std::string { return s; }); EXPECT_EQ(l2.size(), 2); EXPECT_EQ(l2[0], "s1"); EXPECT_EQ(l2[1], "2"); } } TEST(TestUtil, LongWidth) { std::string msg; SetToStdErr(1); long long ret; std::string bit1_times63 = ""; unsigned long long v = 0; for (int i = 0; i < 63; ++i) { bit1_times63 += "1"; v = v << 1; v = v | 1; } GET_STDERR_MSG(ret = StrToLong(bit1_times63, 2), msg); EXPECT_EQ(ret, v); // 63-bit should work #ifndef NDEBUG EXPECT_TRUE(msg.empty()); #endif std::string bit1_times64 = bit1_times63 + "1"; GET_STDERR_MSG(ret = StrToLong(bit1_times64, 2), msg); EXPECT_EQ(ret, 0); // 64-bit should not work #ifndef NDEBUG EXPECT_FALSE(msg.empty()); #endif } TEST(TestUtil, LongWidth_unsigned) { std::string msg; SetToStdErr(1); unsigned long long ret; std::string bit1_times63 = ""; unsigned long long v = 0; for (int i = 0; i < 63; ++i) { bit1_times63 += "1"; v = v << 1; v = v | 1; } GET_STDERR_MSG(ret = StrToULongLong(bit1_times63, 2), msg); EXPECT_EQ(ret, v); // 63-bit should work #ifndef NDEBUG EXPECT_TRUE(msg.empty()); #endif std::string bit1_times64 = bit1_times63 + "1"; GET_STDERR_MSG(ret = StrToULongLong(bit1_times64, 2), msg); EXPECT_EQ(ret, v * 2 + 1); // 64-bit should work #ifndef NDEBUG EXPECT_TRUE(msg.empty()); #endif std::string bit1_times65 = bit1_times64 + "1"; GET_STDERR_MSG(ret = StrToULongLong(bit1_times65, 2), msg); EXPECT_EQ(ret, 0); // 65-bit should not work #ifndef NDEBUG EXPECT_FALSE(msg.empty()); #endif } TEST(TestUtil, Int2Str) { EXPECT_EQ(IntToStrCustomBase(0, 16, true), "0"); EXPECT_EQ(IntToStrCustomBase(0, 10, true), "0"); EXPECT_EQ(IntToStrCustomBase(0, 2, true), "0"); EXPECT_EQ(IntToStrCustomBase(16, 16, true), "10"); EXPECT_EQ(IntToStrCustomBase(16, 16, false), "10"); EXPECT_EQ(IntToStrCustomBase(15, 16, false), "f"); EXPECT_EQ(IntToStrCustomBase(15, 16, true), "F"); EXPECT_EQ(IntToStrCustomBase(16, 8, true), "20"); EXPECT_EQ(IntToStrCustomBase(16, 8, false), "20"); EXPECT_EQ(IntToStrCustomBase(16, 3, false), "121"); EXPECT_EQ(IntToStrCustomBase(16, 10, false), "16"); EXPECT_EQ(IntToStrCustomBase(255, 16, true), "FF"); EXPECT_EQ(IntToStrCustomBase(255, 16, false), "ff"); EXPECT_EQ(IntToStrCustomBase(100, 16, true), "64"); EXPECT_EQ(IntToStrCustomBase(100, 10, false), "100"); EXPECT_EQ(IntToStrCustomBase(2121, 16, false), "849"); EXPECT_EQ(IntToStrCustomBase(255, 2, true), "11111111"); EXPECT_EQ(IntToStrCustomBase(255, 2, false), "11111111"); { unsigned max_unsigned_int = -1; size_t int_max_size = sizeof(int); std::string hex; for (int i = 0; i < int_max_size * 2; i++) hex += 'F'; std::string bin; for (int i = 0; i < int_max_size * 8; i++) bin += '1'; EXPECT_EQ(IntToStrCustomBase(max_unsigned_int, 16, true), hex); EXPECT_EQ(IntToStrCustomBase(max_unsigned_int, 16, false), StrToLower(hex)); EXPECT_EQ(IntToStrCustomBase(max_unsigned_int, 2, false), bin); } } #define TestTrim(fa, in, out) \ { \ std::string a = in; \ fa(a); \ EXPECT_EQ(a, out); \ } TEST(TestUtil, StrTrim) { TestTrim(StrLeftTrim, " dfs a b ", "dfs a b "); TestTrim(StrLeftTrim, " dfs a b ", "dfs a b "); TestTrim(StrLeftTrim, " dfs a b ", "dfs a b "); TestTrim(StrRightTrim, " dfs a b", " dfs a b"); TestTrim(StrRightTrim, " dfs a b ", " dfs a b"); TestTrim(StrRightTrim, " dfs a b ", " dfs a b"); TestTrim(StrTrim, "dfs a b", "dfs a b"); TestTrim(StrTrim, " dfs a b ", "dfs a b"); TestTrim(StrTrim, " dfs a b ", "dfs a b"); TestTrim(StrTrim, " dfs a b", "dfs a b"); TestTrim(StrTrim, " dfs a b ", "dfs a b"); TestTrim(StrTrim, " dfs a b ", "dfs a b"); } } // namespace ilang
31.817416
80
0.612342
[ "vector" ]
a179b70685504846c7574c93d8c7f57e99da3eae
35,050
cpp
C++
src/swcomponents/one_shot_learning/src/ObjectModeller.cpp
tlund80/MARVIN
9fddfd4c8e298850fc8ce49c02ff437f139309d0
[ "Apache-2.0" ]
null
null
null
src/swcomponents/one_shot_learning/src/ObjectModeller.cpp
tlund80/MARVIN
9fddfd4c8e298850fc8ce49c02ff437f139309d0
[ "Apache-2.0" ]
null
null
null
src/swcomponents/one_shot_learning/src/ObjectModeller.cpp
tlund80/MARVIN
9fddfd4c8e298850fc8ce49c02ff437f139309d0
[ "Apache-2.0" ]
1
2021-11-03T09:10:44.000Z
2021-11-03T09:10:44.000Z
#include <one_shot_learning/ObjectModeller.hpp> //--------------PCL Includes------------------- //#include <pcl_ros/transforms.h> #include <pcl/io/pcd_io.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/crop_box.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/filters/radius_outlier_removal.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/features/normal_3d.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/common/pca.h> #include <pcl/common/io.h> #include <pcl/exceptions.h> #include <pcl/features/fpfh_omp.h> #include <pcl/registration/ia_ransac.h> #include <pcl/registration/icp.h> #include <pcl/registration/icp_nl.h> #include <qcoreapplication.h> namespace dti{ namespace one_shot_learning { typedef pcl::FPFHSignature33 FeatureT; typedef pcl::FPFHEstimationOMP<PointNT,PointNT,FeatureT> FeatureEstimationT; typedef pcl::PointCloud<FeatureT> FeatureCloudT; ObjectModeller::ObjectModeller(SharedData *data, QObject *parent) : _sharedData(data){ // start(); leaf_size_ = 0.005f; doModel = false; doSolidModel = false; doModelAlignment = false; _post_processed_cloud.reset(new PointCloudT); _raw_model.reset(new PointCloudT); } ObjectModeller::~ObjectModeller() { } void ObjectModeller::shutdown(){ //isRunning = false; } void ObjectModeller::createmodel(PointCloudT in) { PointCloudT::Ptr src (new PointCloudT); PointCloudT::Ptr tar (new PointCloudT); PointCloudNT::Ptr srcNT (new PointCloudNT); PointCloudNT::Ptr tarNT (new PointCloudNT); PointCloudT::Ptr cloud = in.makeShared(); std::vector<int> dummy; pcl::removeNaNFromPointCloud(*cloud, *cloud, dummy); //EstimateNormals(cloud,src); pcl::copyPointCloud(*cloud,*_raw_model); ///Concatenate the XYZRGBA and normal fields* // pcl::copyPointCloud(*_cloud, *_point_normals); views.push_back(cloud); //src->clear(); if(views.size() > 1){ Eigen::Matrix4f initial_transformation, final_transformation; src = views[0]; tar = views[1]; pcl::copyPointCloud(*src,*srcNT); pcl::copyPointCloud(*tar,*tarNT); pcl::io::savePCDFile("/home/thso/full_model0.pcd",*src); pcl::io::savePCDFile("/home/thso/full_model1.pcd",*tar); /* initial_alignment(srcNT, tarNT,initial_transformation,true,false, false); PointCloudT::Ptr new_source(new PointCloudT); PointCloudT::Ptr output(new PointCloudT); pcl::transformPointCloud(*src, *new_source, initial_transformation); pcl::io::savePCDFile("/home/thso/ia0.pcd",*new_source); pcl::io::savePCDFile("/home/thso/ia1.pcd",*tar); std::cout << "running ICP!!" << std::endl; pairAlign(new_source,tar,output,final_transformation,true); //Copy result to global pointCloud instance pcl::copyPointCloud(*output, *_raw_model); pcl::io::savePCDFile("/home/thso/registred_model.pcd",*output); */ std::cout << "Done ...." << std::endl; }//else{ Q_EMIT modelCreated(); //} } void ObjectModeller::createSolidmodel(PointCloudT in) { /* PointCloudT::Ptr cloud = in.makeShared(); //Create solid model from _cloud PointCloudNT::Ptr _normals(new PointCloudNT); pcl::io::savePCDFile("/home/thso/before_filtering.pcd",*cloud); radiusOutlierRemoval(cloud, _post_processed_cloud, 0.003, 8); // pcl::io::savePCDFile("/home/thso/radius_filter.pcd",*_post_processed_cloud); // statisticalOutlierRemoval(cloud, _post_processed_cloud,0.001); pcl::io::savePCDFile("/home/thso/radius_std_filter.pcd",*_post_processed_cloud); */ //MLS algorithm cannot take a PointNT type -> gives rumtime error /* PointCloudT::Ptr d (new PointCloudT); d->points.resize(_post_processed_cloud->size()); for (size_t i = 0; i < _post_processed_cloud->points.size(); i++) { d->points[i].x = _post_processed_cloud->points[i].x; d->points[i].y = _post_processed_cloud->points[i].y; d->points[i].z = _post_processed_cloud->points[i].z; } */ /* reconstruct->MLSApproximation(_post_processed_cloud, _normals, 0.01); pcl::io::savePCDFile("/home/thso/mls_model.pcd",*_normals); */ //reconstruct->BilateralUpsampling(_post_processed_cloud,_post_processed_cloud,3,5,0.2); // pcl::io::savePCDFile("/home/thso/upsampled_model.pcd",*_post_processed_cloud); // EstimateNormals(_post_processed_cloud, _normals); // Concatenate the XYZRGBA and normal fields* // pcl::copyPointCloud (*_post_processed_cloud, *_normals); // pcl::io::savePCDFile("/home/thso/before_shadow_filter.pcd",*_normals); // pcl::PointIndices::Ptr point_ind (new pcl::PointIndices); // reconstruct->ShadowFilter(_normals, _normals,0.005,point_ind); // pcl::io::savePCDFile("/home/thso/after_shadow_filter.pcd",*_normals); /* reconstruct->poisson(_normals,_mesh,8,8,8,4.0f); //8,12,8,4.0f) reconstruct->saveToVTK("/home/thso/poisson_mesh.vtk", _mesh); */ // pcl::PolygonMesh gpt_mesh; // reconstruct->GreedyProjectionTriangulation(_normals,gpt_mesh, 0.005); // reconstruct->saveToVTK("/home/thso/greedy_mesh.vtk", gpt_mesh); // pcl::PolygonMesh mc_mesh; // reconstruct->MarchingCubes(_normals,mc_mesh,35,0.8,50); // reconstruct->saveToVTK("/home/thso/mc_mesh.vtk", mc_mesh); // pcl::PolygonMesh gp_mesh; // reconstruct->GridProjection(_normals,gp_mesh,0.001); // reconstruct->saveToVTK("/home/thso/gp_mesh.vtk", gp_mesh); Q_EMIT solidModelCreated(); // doSolidModel = true; } void ObjectModeller::alignGTModelAndSceneModel(PointCloudT src, PointCloudT tar) { // _raw_model = src.makeShared(); // _tar = tar.makeShared(); // doModelAlignment = true; } void ObjectModeller::run(){ std::cout << "Object modeller thread: " << QThread::currentThreadId() << std::endl; // reconstruct = new ReconstructPointCloud(); if(doModel) { std::cout << "doModel" << std::endl; // EstimateNormals(clusters[0], _normals); // Concatenate the XYZRGBA and normal fields* // pcl::copyPointCloud (*clusters[0], *_normals); // pcl::PolygonMesh mesh; // reconstruct->poisson(_normals,mesh,8,6,32,4.0f); //8,12,8,4.0f) // mesh = reconstruct->GreedyProjectionTriangulation(_new, 0.05); //pcl::PolygonMesh mesh = reconstruct->MarchingCubes(_normals); //reconstruct->saveToObj("mesh.obj", mesh); //reconstruct->saveToVTK("mesh.vtk", mesh); // views.push_back(clusters[0]); /* if(views.size() > 1) { Eigen::Matrix4f initial_transformation, final_transformation; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr src = views[0]; pcl::PointCloud<pcl::PointXYZRGBA>::Ptr tar = views[1]; initial_alignment(src, tar,initial_transformation,true); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr new_source(new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr output(new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::transformPointCloud (*src, *new_source, initial_transformation); pcl::io::savePCDFile("ia0.pcd",*new_source); pcl::io::savePCDFile("ia1.pcd",*tar); std::cout << "running ICP!!" << std::cout; pairAlign(new_source,tar,output,final_transformation,true); pcl::io::savePCDFile("registred_model.pcd",*output); }else { */ // _sharedData->setFlagTurnModel(); // Q_EMIT modelCreated(); // emit modelCreated(*clusters[0]); // } // } doModel = false; } if(doSolidModel) { doSolidModel = false; } if(doModelAlignment) { //Aligning GT_model and scene model to compute variance in coordinate system /* Eigen::Matrix4f initial_transformation, final_transformation; initial_alignment(_raw_model, _tar,initial_transformation,true); PointCloudNT::Ptr new_source(new PointCloudNT); PointCloudNT::Ptr output(new PointCloudNT); pcl::transformPointCloudWithNormals<PointNT> (*_raw_model, *new_source, initial_transformation); pcl::io::savePCDFile("gt_align0.pcd",*new_source); pcl::io::savePCDFile("gt_align1.pcd",*_tar); std::cout << "running ICP!!" << std::cout; pairAlign(new_source,_tar,output,final_transformation,true); pcl::io::savePCDFile("gt_registred_model.pcd",*output); doModelAlignment = false; */ } std::cout << "Runnable ended" << std::endl; } void ObjectModeller::initial_alignment(PointCloudNT::Ptr src_cloud, PointCloudNT::Ptr target_cloud, Eigen::Matrix4f &final_transform, bool downsample, bool source_has_normals, bool target_has_normals ){ using namespace pcl; float max_correspondence_distance_ = 1.0; int nr_iterations_ = 100; float min_sample_distance_ = leaf_size_; pcl::console::print_highlight("Source cloud contains %d data points\n", src_cloud->size ()); pcl::console::print_highlight("Target cloud contains %d data points\n", target_cloud->size ()); pcl::console::print_highlight("leaf size = %f\n", leaf_size_); pcl::VoxelGrid<PointNT> grid; if (downsample){ grid.setLeafSize (leaf_size_, leaf_size_, leaf_size_); grid.setInputCloud (target_cloud); grid.filter (*target_cloud); grid.setInputCloud (src_cloud); grid.filter (*src_cloud); pcl::console::print_highlight("Filtered model cloud contains %d data points\n", src_cloud->size ()); pcl::console::print_highlight("Filtered scene cloud contains %d data points\n", target_cloud->size ()); } NormalEstimationOMP<PointNT, PointNT> ne; search::KdTree<PointNT>::Ptr search_tree (new search::KdTree<PointNT>); ne.setSearchMethod (search_tree); ne.setRadiusSearch (1.5f * leaf_size_); if(!target_has_normals){ pcl::console::print_highlight("Estimating scene normals...."); ne.setInputCloud (target_cloud); ne.compute (*target_cloud); pcl::console::print_highlight ("Finish...\n"); } if(!source_has_normals){ pcl::console::print_highlight("Estimating model normals...."); ne.setInputCloud (src_cloud); ne.compute (*src_cloud); pcl::console::print_highlight ("Finish...\n"); } pcl::console::print_highlight("FPFH - started\n"); FeatureEstimationT pfh_est_src; pcl::search::KdTree<PointNT>::Ptr tree_pfh (new pcl::search::KdTree<PointNT>()); pfh_est_src.setSearchMethod (tree_pfh); pfh_est_src.setRadiusSearch(3 * leaf_size_); // pfh_est_src.setSearchSurface (keypoints_src); pfh_est_src.setInputNormals (target_cloud); pfh_est_src.setInputCloud (target_cloud); pcl::PointCloud<FeatureT>::Ptr pfh_scene (new pcl::PointCloud<FeatureT>); pcl::console::print_highlight("FPFH - Compute scene features\n"); pfh_est_src.compute (*pfh_scene); pcl::console::print_highlight("FPFH - finished\n"); pfh_est_src.setInputNormals (src_cloud); pfh_est_src.setInputCloud (src_cloud); pcl::PointCloud<FeatureT>::Ptr pfh_model (new pcl::PointCloud<FeatureT>); pcl::console::print_highlight("FPFH - Compute model features\n"); pfh_est_src.compute (*pfh_model); pcl::console::print_highlight("FPFH - finished\n"); pcl::SampleConsensusInitialAlignment<PointNT, PointNT, FeatureT> sac_ia_; // Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm sac_ia_.setMinSampleDistance (min_sample_distance_); sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_); sac_ia_.setMaximumIterations (nr_iterations_); sac_ia_.setCorrespondenceRandomness(5); PointCloudNT::Ptr rotated_model (new PointCloudNT); copyPointCloud(*src_cloud, *rotated_model); std::vector<std::pair<float,Eigen::Matrix4f> > votes; Eigen::Matrix4f rotation; for(int i = 0; i<36;i++){ if(i < 4){ rotation = rotateZ(i* 1.57); }else if(i >= 4 && i < 8) { rotation = rotateY((i-4)* 1.57); }else if(i >= 8 && i < 12) { rotation = rotateX((i-8)* 1.57); }else if(i >= 12 && i < 16) { Eigen::Matrix4f temp = rotateY(1.57); Eigen::Matrix4f temp2 = rotateZ((i-12)* 1.57); rotation = temp * temp2; }else if(i >= 16 && i < 20) { Eigen::Matrix4f temp = rotateY(1.57); Eigen::Matrix4f temp2 = rotateX((i-16)* 1.57); rotation = temp * temp2; }else if(i >= 20 && i < 24) { Eigen::Matrix4f temp = rotateX(1.57); Eigen::Matrix4f temp2 = rotateZ((i-20)* 1.57); rotation = temp * temp2; }else if(i >= 24 && i < 28) { Eigen::Matrix4f temp = rotateX(1.57); Eigen::Matrix4f temp2 = rotateY((i-24)* 1.57); rotation = temp * temp2; }else if(i >= 28 && i < 32) { Eigen::Matrix4f temp = rotateZ(1.57); Eigen::Matrix4f temp2 = rotateY((i-28)* 1.57); rotation = temp * temp2; }else if(i >= 32 && i < 36) { Eigen::Matrix4f temp = rotateZ(1.57); Eigen::Matrix4f temp2 = rotateX((i-32)* 1.57); rotation = temp * temp2; } pcl::transformPointCloudWithNormals<PointNT>(*rotated_model, *rotated_model,rotation); sac_ia_.setInputSource(rotated_model);//setInputCloud (src); sac_ia_.setSourceFeatures (pfh_model); sac_ia_.setInputTarget (target_cloud); sac_ia_.setTargetFeatures (pfh_scene); pcl::console::print_highlight("Alignment %d started!\n", i); PointCloudNT registration_output; sac_ia_.align (registration_output); if (sac_ia_.hasConverged ()){ // Print results printf ("\n"); Eigen::Matrix4f transformation = sac_ia_.getFinalTransformation (); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (0,0), transformation (0,1), transformation (0,2)); pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", transformation (1,0), transformation (1,1), transformation (1,2)); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (2,0), transformation (2,1), transformation (2,2)); pcl::console::print_info ("\n"); pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", transformation (0,3), transformation (1,3), transformation (2,3)); pcl::console::print_info ("\n"); pcl::console::print_info ("SAC-ia Fitness Score: %f\n", sac_ia_.getFitnessScore()); std::pair<float,Eigen::Matrix4f> res(sac_ia_.getFitnessScore(), transformation); votes.push_back(res); }else{ pcl::console::print_highlight("Alignment failed!\n"); // return (1); } } //std::sort(votes.begin(),votes.end(),my_sort); std::sort(votes.begin(),votes.end(),boost::bind(&ObjectModeller::my_sort, this, _1, _2)); Eigen::Matrix4f best_transformation = votes.at(0).second; pcl::console::print_info ("Best Transformation:\n"); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", best_transformation (0,0), best_transformation (0,1), best_transformation (0,2)); pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", best_transformation (1,0), best_transformation (1,1), best_transformation (1,2)); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", best_transformation (2,0), best_transformation (2,1), best_transformation (2,2)); pcl::console::print_info ("\n"); pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", best_transformation (0,3), best_transformation (1,3), best_transformation (2,3)); pcl::console::print_info ("\n"); pcl::console::print_info ("Best Fitness Score: %f\n", votes.at(0).first); final_transform = best_transformation; // pcl::transformPointCloudWithNormals<PointNT>(*src_cloud, *src_cloud,best_transformation); // Downsample for consistency and speed // \note enable this for large datasets /* PointCloudT::Ptr src (new PointCloudT); PointCloudT::Ptr tgt (new PointCloudT); pcl::PointCloud<pcl::Normal>::Ptr src_normals (new pcl::PointCloud<pcl::Normal>); pcl::PointCloud<pcl::Normal>::Ptr tgt_normals (new pcl::PointCloud<pcl::Normal>); pcl::VoxelGrid<PointT> grid; if (downsample){ grid.setLeafSize (leaf_size_, leaf_size_, leaf_size_); grid.setInputCloud (src_cloud); grid.filter (*src); grid.setInputCloud (target_cloud); grid.filter (*tgt); pcl::console::print_highlight("Filtered source cloud contains %d data points\n", src->size ()); pcl::console::print_highlight("Filtered target cloud contains %d data points\n", tgt->size ()); }else{ src = src_cloud; tgt = target_cloud; } pcl::NormalEstimationOMP<PointT, pcl::Normal> ne; pcl::search::KdTree<PointT>::Ptr search_tree (new pcl::search::KdTree<PointT>); ne.setSearchMethod (search_tree); ne.setRadiusSearch (1.5f * leaf_size_); if(!target_has_normals){ pcl::console::print_highlight("Estimating target normals...."); ne.setInputCloud (tgt); ne.compute (*tgt_normals); pcl::console::print_highlight ("Finish...\n"); } if(!source_has_normals){ pcl::console::print_highlight("Estimating source normals...."); ne.setInputCloud (src); ne.compute (*src_normals); pcl::console::print_highlight ("Finish...\n"); } pcl::console::print_highlight("FPFH - started\n"); FeatureEstimationT pfh_est_src; pcl::search::KdTree<PointT>::Ptr tree_pfh (new pcl::search::KdTree<PointT>()); pfh_est_src.setSearchMethod (tree_pfh); pfh_est_src.setRadiusSearch(3 * leaf_size_); // pfh_est_src.setSearchSurface (keypoints_src); pfh_est_src.setInputNormals (tgt_normals); pfh_est_src.setInputCloud (tgt); pcl::PointCloud<FeatureT>::Ptr pfh_tgt (new pcl::PointCloud<FeatureT>); pcl::console::print_highlight("FPFH - Compute target features\n"); pfh_est_src.compute (*pfh_tgt); pcl::console::print_highlight("FPFH - finished\n"); pfh_est_src.setInputNormals (src_normals); pfh_est_src.setInputCloud (src); pcl::PointCloud<FeatureT>::Ptr pfh_src (new pcl::PointCloud<FeatureT>); pcl::console::print_highlight("FPFH - Compute source features\n"); pfh_est_src.compute (*pfh_src); pcl::console::print_highlight("FPFH - finished\n"); PointCloudNT::Ptr src_with_normals (new PointCloudNT); PointCloudNT::Ptr tgt_with_normals (new PointCloudNT); pcl::PointCloud<pcl::PointXYZ>::Ptr src_xyz (new pcl::PointCloud<pcl::PointXYZ>); pcl::copyPointCloud(*src, *src_xyz); pcl::PointCloud<pcl::PointXYZ>::Ptr tgt_xyz (new pcl::PointCloud<pcl::PointXYZ>); pcl::copyPointCloud(*tgt, *tgt_xyz); pcl::concatenateFields(*src_xyz, *src_normals, *src_with_normals); pcl::concatenateFields(*tgt_xyz, *tgt_normals, *tgt_with_normals); pcl::SampleConsensusInitialAlignment<PointNT, PointNT, FeatureT> sac_ia_; // Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm sac_ia_.setMinSampleDistance (min_sample_distance_); sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_); sac_ia_.setMaximumIterations (nr_iterations_); sac_ia_.setCorrespondenceRandomness(5); PointCloudNT::Ptr rotated_model (new PointCloudNT); pcl::copyPointCloud(*src_with_normals, *rotated_model); std::vector<std::pair<float,Eigen::Matrix4f> > votes; Eigen::Matrix4f rotation; for(int i = 0; i<12;i++){ if(i < 4){ rotation = rotateZ(i* 1.57); }else if(i >= 4 && i < 8) { rotation = rotateY(i* 1.57); }else if(i >= 8 && i < 12) { rotation = rotateX(i* 1.57); } pcl::transformPointCloudWithNormals<PointNT>(*rotated_model, *rotated_model,rotation); sac_ia_.setInputSource(rotated_model);//setInputCloud (src); sac_ia_.setSourceFeatures (pfh_src); sac_ia_.setInputTarget (tgt_with_normals); sac_ia_.setTargetFeatures (pfh_tgt); pcl::console::print_highlight("Alignment %d started!\n", i); PointCloudNT registration_output; sac_ia_.align (registration_output); if (sac_ia_.hasConverged ()){ // Print results printf ("\n"); Eigen::Matrix4f transformation = sac_ia_.getFinalTransformation (); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (0,0), transformation (0,1), transformation (0,2)); pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", transformation (1,0), transformation (1,1), transformation (1,2)); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (2,0), transformation (2,1), transformation (2,2)); pcl::console::print_info ("\n"); pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", transformation (0,3), transformation (1,3), transformation (2,3)); pcl::console::print_info ("\n"); pcl::console::print_info ("SAC-ia Fitness Score: %f\n", sac_ia_.getFitnessScore()); std::pair<float,Eigen::Matrix4f> res(sac_ia_.getFitnessScore(), transformation); votes.push_back(res); }else{ pcl::console::print_highlight("Alignment failed!\n"); // return (1); } } std::sort(votes.begin(),votes.end(),boost::bind(&ObjectModeller::my_sort, this, _1, _2)); Eigen::Matrix4f best_transformation = votes.at(0).second; pcl::console::print_info ("Best Transformation:\n"); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", best_transformation (0,0), best_transformation (0,1), best_transformation (0,2)); pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", best_transformation (1,0), best_transformation (1,1), best_transformation (1,2)); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", best_transformation (2,0), best_transformation (2,1), best_transformation (2,2)); pcl::console::print_info ("\n"); pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", best_transformation (0,3), best_transformation (1,3), best_transformation (2,3)); pcl::console::print_info ("\n"); pcl::console::print_info ("Best Fitness Score: %f\n", votes.at(0).first); final_transform = best_transformation; // pcl::transformPointCloudWithNormals<PointNT>(*src, *src,best_transformation); */ } //////////////////////////////////////////////////////////////////////////////// /** \brief Align a pair of PointCloud datasets and return the result * \param cloud_src the source PointCloud * \param cloud_tgt the target PointCloud * \param output the resultant aligned source PointCloud * \param final_transform the resultant transform between source and target */ bool ObjectModeller::pairAlign (PointCloudT::Ptr &src_cloud, PointCloudT::Ptr &target_cloud, PointCloudT::Ptr &output, Eigen::Matrix4f &final_transform, bool downsample = true){ bool result = true; // // Downsample for consistency and speed // \note enable this for large datasets PointCloudT::Ptr src (new PointCloudT); PointCloudT::Ptr tgt (new PointCloudT); pcl::VoxelGrid<PointT> grid; if (downsample) { grid.setLeafSize (0.001, 0.001, 0.001); grid.setInputCloud (src_cloud); grid.filter (*src); grid.setInputCloud (target_cloud); grid.filter (*tgt); std::cout << "Filtered cloud contains " << src->size () << " data points" << std::endl; } else { src = src_cloud; tgt = target_cloud; } // Compute surface normals and curvature PointCloudNT::Ptr points_with_normals_src (new PointCloudNT); PointCloudNT::Ptr points_with_normals_tgt (new PointCloudNT); pcl::NormalEstimationOMP<PointT, PointNT> norm_est; pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT> ()); norm_est.setSearchMethod (tree); norm_est.setKSearch (30); norm_est.setInputCloud (src); norm_est.compute (*points_with_normals_src); pcl::copyPointCloud (*src, *points_with_normals_src); norm_est.setInputCloud (tgt); norm_est.compute (*points_with_normals_tgt); pcl::copyPointCloud (*tgt, *points_with_normals_tgt); // // Instantiate our custom point representation (defined above) ... /* MyPointRepresentation point_representation; // ... and weight the 'curvature' dimension so that it is balanced against x, y, and z float alpha[4] = {1.0, 1.0, 1.0, 1.0}; point_representation.setRescaleValues (alpha); */ // // Align pcl::IterativeClosestPointNonLinear<PointNT, PointNT> reg; reg.setTransformationEpsilon (1e-9); reg.setEuclideanFitnessEpsilon(1e-9); // Set the maximum distance between two correspondences (src<->tgt) to 10cm // Note: adjust this based on the size of your datasets reg.setMaxCorrespondenceDistance (0.1); // Set the point representation //reg.setPointRepresentation (boost::make_shared<const MyPointRepresentation> (point_representation)); reg.setInputSource(points_with_normals_src);//setInputCloud (points_with_normals_src); reg.setInputTarget (points_with_normals_tgt); // Run the same optimization in a loop and visualize the results Eigen::Matrix4f Ti = Eigen::Matrix4f::Identity (), prev, targetToSource; pcl::PointCloud<PointNT>::Ptr reg_result = points_with_normals_src; reg.setMaximumIterations (10); double conv; for (int i = 0; i < 30; ++i) { PCL_INFO ("Iteration Nr. %d.\n", i); // save cloud for visualization purpose points_with_normals_src = reg_result; // Estimate reg.setInputSource(points_with_normals_src);//setInputCloud (points_with_normals_src); reg.align (*reg_result); //accumulate transformation between each Iteration Ti = reg.getFinalTransformation () * Ti; //if the difference between this transformation and the previous one //is smaller than the threshold, refine the process by reducing //the maximal correspondence distance float sum = (reg.getLastIncrementalTransformation () - prev).sum (); std::cout << "sum: " << sum << std::endl; if(sum == 0){ break; } if (fabs ((reg.getLastIncrementalTransformation () - prev).sum ()) < reg.getTransformationEpsilon ()) reg.setMaxCorrespondenceDistance (reg.getMaxCorrespondenceDistance () - 0.001); prev = reg.getLastIncrementalTransformation (); conv = reg.getFitnessScore(); std::cout << "Registration has converged: " << reg.hasConverged() << " with fitness score: " << reg.getFitnessScore() << std::endl; } if(conv > 0.0001) { PCL_ERROR("Registration Error!!"); //TODO: comment this in!! result = false; } // Get the transformation from target to source targetToSource = Ti.inverse(); // // Transform target back in source frame pcl::transformPointCloud(*target_cloud, *output, targetToSource); //add the source to the transformed target *output += *src_cloud; final_transform = targetToSource; return result; } void ObjectModeller::EstimateNormals(PointCloudT::Ptr &src_cloud,PointCloudNT::Ptr &target_cloud){ // Normal estimation* pcl::NormalEstimationOMP<PointT, PointNT> n; PointCloudNT::Ptr cloud_with_normals (new PointCloudNT); pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>); tree->setInputCloud (src_cloud); n.setInputCloud (src_cloud); n.setSearchMethod (tree); n.setRadiusSearch(1.5 * leaf_size_); //n.setKSearch (20); n.compute (*cloud_with_normals); PCL_INFO("Finish normal estimation for model. Size: %d\n", (int)cloud_with_normals->size()); pcl::copyPointCloud(*cloud_with_normals, *target_cloud); } void ObjectModeller::statisticalOutlierRemoval(PointCloudT::Ptr &src_cloud, PointCloudT::Ptr &target_cloud, int mean_num_pts){ PointCloudT::Ptr cloud_filtered (new PointCloudT); if(src_cloud->size() > 0) { try{ // Create the filtering object pcl::StatisticalOutlierRemoval<PointT> sor; sor.setInputCloud (src_cloud); sor.setMeanK (mean_num_pts); sor.setStddevMulThresh (1.0); sor.filter (*cloud_filtered); if(src_cloud->isOrganized()){ sor.setUserFilterValue(0.0); sor.setKeepOrganized(true); } pcl::copyPointCloud(*cloud_filtered, *target_cloud); }catch(...) { PCL_ERROR("Somthing went wrong in object_modeller::statisticalOutlierRemoval()"); } } } void ObjectModeller::radiusOutlierRemoval(PointCloudT::Ptr &src_cloud, PointCloudT::Ptr &target_cloud, double radius, int min_neighbpr_pts){ PointCloudT::Ptr cloud_filtered (new PointCloudT); if(src_cloud->size() > 0) { try{ // Create the filtering object pcl::RadiusOutlierRemoval<PointT> ror; ror.setInputCloud(src_cloud); ror.setRadiusSearch(radius); ror.setMinNeighborsInRadius(min_neighbpr_pts); ror.filter (*cloud_filtered); ror.setKeepOrganized(true); pcl::copyPointCloud(*cloud_filtered, *target_cloud); }catch(...) { PCL_ERROR("Somthing went wrong in object_modeller::radiusOutlierRemoval()"); } } } /* void ObjectModeller::removePlane(PointCloudT::Ptr &src_cloud, PointCloudT::Ptr &target_cloud, double dist_threads){ pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<PointNT> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (dist_threads); seg.setInputCloud (src_cloud); seg.segment (*inliers, *coefficients); if (inliers->indices.size () == 0) { PCL_ERROR ("Could not estimate a planar model for the given dataset."); //return (-1); } std::cerr << "Model coefficients: " << coefficients->values[0] << " " << coefficients->values[1] << " " << coefficients->values[2] << " " << coefficients->values[3] << std::endl; PointCloudT::Ptr cloud_f (new PointCloudT); PointCloudT::Ptr cloud_p (new PointCloudT); // Create the filtering object pcl::ExtractIndices<PointNT> extract; // Extract the inliers extract.setInputCloud (src_cloud); extract.setIndices(inliers); extract.setNegative (false); extract.filter (*cloud_p); std::cerr << "PointCloud representing the planar component: " << cloud_p->width * cloud_p->height << " data points." << std::endl; // Create the filtering object extract.setNegative (true); extract.filter (*cloud_f); pcl::copyPointCloud(*cloud_f, *target_cloud); } */ /* void ObjectModeller::CropBox(PointCloudT::Ptr &src_cloud, PointCloudT::Ptr &target_cloud,float rx, float ry, float minz, float maxz, Eigen::Vector3f boxTranslatation, Eigen::Vector3f boxRotation){ PointCloudT::Ptr filtered (new PointCloudT); pcl::CropBox<PointNT> cropFilter; cropFilter.setInputCloud (src_cloud); cropFilter.setMin(Eigen::Vector4f(-rx, -ry, minz, 1.0f)); cropFilter.setMax(Eigen::Vector4f(rx, ry, maxz, 1.0f)); cropFilter.setTranslation(boxTranslatation); cropFilter.setRotation(boxRotation); cropFilter.setKeepOrganized(true); cropFilter.filter (*filtered); pcl::copyPointCloud(*filtered, *target_cloud); } */ /* bool ObjectModeller::extractClusters(PointCloudT::Ptr &src_cloud, std::vector<CloudT::Ptr, Eigen::aligned_allocator_indirection<CloudT::Ptr> > &clusters){ pcl::search::KdTree<PointNT>::Ptr tree (new pcl::search::KdTree<PointNT>); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<PointT> ec; ec.setClusterTolerance (0.02); // 2cm ec.setMinClusterSize (100); ec.setMaxClusterSize (50000); ec.setSearchMethod (tree); ec.setInputCloud(src_cloud); ec.extract (cluster_indices); std::cout<<"Found " << cluster_indices.size() << " clusters" << std::endl; if ( cluster_indices.size() < 1) return false; PointCloudT::Ptr model (new PointCloudT); for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it) { PointCloudT::Ptr cloud_cluster (new PointCloudT); for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); pit++) cloud_cluster->points.push_back (src_cloud->points[*pit]); // if(cloud_cluster->points.size () > 500) { cloud_cluster->width = cloud_cluster->points.size (); cloud_cluster->height = 1; cloud_cluster->is_dense = true; Eigen::Vector4f centroid; pcl::compute3DCentroid(*cloud_cluster,centroid); pcl::PCA<PointT> _pca; PointT projected; PointT reconstructed; CloudT cloudi = *cloud_cluster; CloudT finalCloud; try{ //Do PCA for each point to preserve color information //Add point cloud to force PCL to init_compute else a exception is thrown!!!HACK _pca.setInputCloud(cloud_cluster); for(int i = 0; i < (int)cloud_cluster->size(); i++) { _pca.project(cloudi[i],projected); _pca.reconstruct (projected, reconstructed); //assign colors projected.r = cloudi[i].r; projected.g = cloudi[i].g; projected.b = cloudi[i].b; //add point to cloud finalCloud.push_back(projected); } }catch(pcl::InitFailedException &e) { PCL_ERROR(e.what()); } std::cout << "PointCloud representing the Cluster: " << cloud_cluster->points.size () << " data points." << std::endl; clusters.push_back(finalCloud.makeShared()); } pcl::copyPointCloud(*cloud_cluster, *model); } return true; } */ Eigen::Matrix4f ObjectModeller::rotateX(float radians) { float Sin = sinf(radians); float Cos = cosf(radians); Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() ); rotationMatrix(1, 1) = Cos; rotationMatrix(1, 2) = Sin; rotationMatrix(2, 1) = -Sin; rotationMatrix(2, 2) = Cos; return rotationMatrix; } Eigen::Matrix4f ObjectModeller::rotateY(float radians) { float Sin = sinf(radians); float Cos = cosf(radians); Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() ); rotationMatrix(0, 0) = Cos; rotationMatrix(0, 2) = Sin; rotationMatrix(2, 0) = -Sin; rotationMatrix(2, 2) = Cos; return rotationMatrix; } Eigen::Matrix4f ObjectModeller::rotateZ(float radians) { float Sin = sinf(radians); float Cos = cosf(radians); Eigen::Matrix4f rotationMatrix( Eigen::Matrix4f::Identity() ); rotationMatrix(0, 0) = Cos; rotationMatrix(0, 1) = Sin; rotationMatrix(1, 0) = -Sin; rotationMatrix(1, 1) = Cos; return rotationMatrix; } void ObjectModeller::getRawModel(PointCloudT::Ptr &model){ QMutexLocker lock(&_mutexCloud); model = _raw_model; } void ObjectModeller::getPostProcessedModel(PointCloudT::Ptr &model){ QMutexLocker lock(&_mutexCloud); model = _post_processed_cloud; } void ObjectModeller::getMeshModel(pcl::PolygonMesh &mesh){ QMutexLocker lock(&_mutexMesh); mesh = _mesh; } } } // namespace object_modeller_gui
36.321244
177
0.677261
[ "mesh", "object", "vector", "model", "transform", "solid" ]
a17ae1cc39a5071fa94fed52bd28894a585215e1
15,040
cpp
C++
filterwindow.cpp
LucaAngioloni/Organizer
7d853166bcf4913645e3b14543004f7a9b9d105d
[ "Apache-2.0" ]
6
2016-09-02T14:39:43.000Z
2020-09-29T23:54:30.000Z
filterwindow.cpp
LucaAngioloni/Organizer
7d853166bcf4913645e3b14543004f7a9b9d105d
[ "Apache-2.0" ]
null
null
null
filterwindow.cpp
LucaAngioloni/Organizer
7d853166bcf4913645e3b14543004f7a9b9d105d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Luca Angioloni Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "filterwindow.h" #include "ui_filterwindow.h" FilterWindow::FilterWindow(QWidget *parent) : QDialog(parent), ui(new Ui::FilterWindow) { ui->setupUi(this); addOrMod = 0; ui->extensionEditLine->setPlaceholderText("Extension"); ui->extensionEditLine->setDisabled(true); ui->wordsTable->setColumnWidth(0,370); ui->minSlider->setMinimum(0); ui->minSlider->setMaximum(13); ui->maxSlider->setMinimum(0); ui->maxSlider->setMaximum(13); dirCompleter = new QCompleter(this); QDirModel *model = new QDirModel(dirCompleter); model->setFilter(QDir::Dirs); dirCompleter->setModel(model); dirCompleter->setCaseSensitivity(Qt::CaseInsensitive); ui->pathText->setCompleter(dirCompleter); caseSens = false; ui->caseSensitivityBox->setChecked(caseSens); } FilterWindow::~FilterWindow() { delete ui; } void FilterWindow::setDatabase(FilterDatabase *data){ database = data; } void FilterWindow::fillInfo(QString filterName){ addOrMod = 1; currentFilter = filterName; ui->extensionEditLine->clear(); ui->nameText->setText(database->getElement(currentFilter).getName()); ui->pathText->setText(database->getElement(currentFilter).getPath()); setMinDimensionFromMB(database->getElement(currentFilter).getMinDimension()); setMaxDimensionFromMB(database->getElement(currentFilter).getMaxDimension()); updateMBLabel(); if(database->getElement(currentFilter).getExtension() != "%Any%" && database->getElement(currentFilter).getExtension() != "%Image%" && database->getElement(currentFilter).getExtension() != "%Video%" && database->getElement(currentFilter).getExtension() != "%Music%" && database->getElement(currentFilter).getExtension() != "%Document%" && database->getElement(currentFilter).getExtension() != "%Book%" && database->getElement(currentFilter).getExtension() != "%Compressed%") { ui->extensionEditLine->setEnabled(true); ext = database->getElement(currentFilter).getExtension(); ui->extensionEditLine->setText(ext); ui->extensionBox->setCurrentText("Other"); } else{ ext = database->getElement(currentFilter).getExtension(); QString tmpE = ext; ui->extensionBox->setCurrentText(tmpE.remove("%")); } ui->wordsTable->clear(); ui->wordsTable->setRowCount(0); for(int i = 0; i< database->getElement(currentFilter).complexity(); i++){ ui->wordsTable->insertRow(i); ui->wordsTable->setItem(i, 0, new QTableWidgetItem(database->getElement(currentFilter).getWordAtIndex(i))); } Qt::SortOrder order = Qt::AscendingOrder; ui->wordsTable->sortItems ( 0, order ); caseSens = database->getElement(currentFilter).getCaseSensitivity(); ui->caseSensitivityBox->setChecked(caseSens); } void FilterWindow::setDefault(){ addOrMod = 0; currentFilter.clear(); ui->nameText->clear(); ui->pathText->clear(); ui->extensionEditLine->clear(); ui->extensionEditLine->setDisabled(true); ui->extensionBox->setCurrentIndex(0); ext = "%Any%"; ui->minSlider->setValue(0); ui->maxSlider->setValue(13); ui->wordsTable->clear(); ui->wordsTable->setRowCount(0); caseSens = false; ui->caseSensitivityBox->setChecked(caseSens); } void FilterWindow::on_browseButton_clicked() { QString filePath; filePath = QFileDialog::getExistingDirectory(this, tr("Choose Path"), "/Users/"); ui->pathText->setText(filePath); } void FilterWindow::newFilter(){ Filter newFilter(ui->nameText->text(), ui->pathText->text(), caseSens, getMinDimensionMB(), getMaxDimensionMB(), getExt()); for(int i = 0; i<ui->wordsTable->rowCount(); i++){ if(ui->wordsTable->item(i,0)){ newFilter.addWord(ui->wordsTable->item(i,0)->text()); } } //check if path is an actual directory. (forse rompe le scatole ed è superfluo). // QFileInfo temp(ui->pathText->text()); // if(!temp.isDir()){ // QMessageBox msgBox; // msgBox.setText("Path error"); // msgBox.setInformativeText("The path is not a folder. Please choose a new one"); // msgBox.setStandardButtons(QMessageBox::Ok); // msgBox.setDefaultButton(QMessageBox::Ok); // msgBox.exec(); // } // else{ if(!database->addFilter(newFilter)){ QMessageBox msgBox; msgBox.setText("Name error"); msgBox.setInformativeText("This name has already been used for an other filter or is empty. Please choose a new one"); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); } else { this->hide(); emit filterDone(); } // } } void FilterWindow::modFilter(){ if (ui->nameText->text() == "" || ((database->nameIsOccupied(ui->nameText->text()) && ui->nameText->text() != currentFilter))){ QMessageBox msgBox; msgBox.setText("Name error"); msgBox.setInformativeText("This name has already been used for an other filter or is empty. Please choose a new one"); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); } else{ //check if path is an actual directory. (forse rompe le scatole ed è superfluo). // QFileInfo temp(ui->pathText->text()); // if(!temp.isDir()){ // QMessageBox msgBox; // msgBox.setText("Path error"); // msgBox.setInformativeText("The path is not correct or is empty. Please choose a new one"); // msgBox.setStandardButtons(QMessageBox::Ok); // msgBox.setDefaultButton(QMessageBox::Ok); // msgBox.exec(); // } // else{ database->getElement(currentFilter).setPath(ui->pathText->text()); database->getElement(currentFilter).setMinDimension(getMinDimensionMB()); if(getMaxDimensionMB() == -1){ database->getElement(currentFilter).setMaxDimension(-1, true); } else { database->getElement(currentFilter).setMaxDimension(getMaxDimensionMB()); } database->getElement(currentFilter).setExtension(getExt()); database->getElement(currentFilter).clearWords(); for(int i = 0; i<ui->wordsTable->rowCount(); i++){ if(ui->wordsTable->item(i,0)){ database->getElement(currentFilter).addWord(ui->wordsTable->item(i,0)->text()); } } database->getElement(currentFilter).setCaseSensitivity(caseSens); database->getElement(currentFilter).setName(ui->nameText->text()); //name goes last otherwise getElement returns empty this->hide(); emit filterDone(); // } } } void FilterWindow::on_cancelButton_clicked() { this->hide(); } void FilterWindow::on_okButton_clicked() { if(addOrMod){ modFilter(); } else{ newFilter(); } } //methods to convert the value of sliders in usable MB values int FilterWindow::getMinDimensionMB(){ int minDim; switch (ui->minSlider->value()){ case 0 : minDim = 0; break; case 1 : minDim = 1; break; case 2 : minDim = 2; break; case 3: minDim = 10; break; case 4 : minDim = 30; break; case 5 : minDim = 50; break; case 6 : minDim = 100; break; case 7 : minDim = 500; break; case 8 : minDim = 1024; break; case 9 : minDim = 2048; break; case 10 : minDim = 5120; break; case 11 : minDim = 10240; break; case 12 : minDim = 51200; break; case 13 : minDim = 102400; break; } return minDim; } int FilterWindow::getMaxDimensionMB(){ int maxDim; switch (ui->maxSlider->value()){ case 0 : maxDim = 1; break; case 1 : maxDim = 2; break; case 2 : maxDim = 10; break; case 3: maxDim = 30; break; case 4 : maxDim = 50; break; case 5 : maxDim = 100; break; case 6 : maxDim = 500; break; case 7 : maxDim = 1024; break; case 8 : maxDim = 2048; break; case 9 : maxDim = 5120; break; case 10 : maxDim = 10240; break; case 11 : maxDim = 51200; break; case 12 : maxDim = 102400; break; case 13 : maxDim = -1; break; } return maxDim; } QString FilterWindow::getExt(){ if(ext == "%Other%"){ QString tmpExt = ui->extensionEditLine->text(); tmpExt.remove(" "); return tmpExt; } else{ return ext; } } void FilterWindow::setMinDimensionFromMB(int minMB){ switch (minMB){ case 0 : ui->minSlider->setValue(0); break; case 1 : ui->minSlider->setValue(1); break; case 2 : ui->minSlider->setValue(2); break; case 10 : ui->minSlider->setValue(3); break; case 30 : ui->minSlider->setValue(4); break; case 50 : ui->minSlider->setValue(5); break; case 100 : ui->minSlider->setValue(6); break; case 500 : ui->minSlider->setValue(7); break; case 1024 : ui->minSlider->setValue(8); break; case 2048 : ui->minSlider->setValue(9); break; case 5120 : ui->minSlider->setValue(10); break; case 10240 : ui->minSlider->setValue(11); break; case 51200 : ui->minSlider->setValue(12); break; case 102400 : ui->minSlider->setValue(13); break; } } void FilterWindow::setMaxDimensionFromMB(int maxMB){ if(maxMB == -1){ ui->maxSlider->setValue(13); } else{ switch (maxMB){ case 1 : ui->maxSlider->setValue(0); break; case 2 : ui->maxSlider->setValue(1); break; case 10 : ui->maxSlider->setValue(2); break; case 30 : ui->maxSlider->setValue(3); break; case 50 : ui->maxSlider->setValue(4); break; case 100 : ui->maxSlider->setValue(5); break; case 500 : ui->maxSlider->setValue(6); break; case 1024 : ui->maxSlider->setValue(7); break; case 2048 : ui->maxSlider->setValue(8); break; case 5120 : ui->maxSlider->setValue(9); break; case 10240 : ui->maxSlider->setValue(10); break; case 51200 : ui->maxSlider->setValue(11); break; case 102400 : ui->maxSlider->setValue(12); break; } } } void FilterWindow::on_extensionBox_currentIndexChanged(const QString &arg1) { if (arg1 != "Other"){ ui->extensionEditLine->setDisabled(true); QPalette pal = ui->extensionEditLine->palette(); pal.setColor(QPalette::Background, Qt::gray); ui->extensionEditLine->setPalette(pal); ui->extensionEditLine->setAutoFillBackground(true); } else{ ui->extensionEditLine->setEnabled(true); } ext = "%" + arg1 + "%"; } void FilterWindow::on_minSlider_valueChanged(int value) { if(value > ui->maxSlider->value()){ ui->maxSlider->setValue(value); } updateMBLabel(); } void FilterWindow::on_maxSlider_valueChanged(int value) { if(value < ui->minSlider->value()){ ui->minSlider->setValue(value); } updateMBLabel(); } void FilterWindow::updateMBLabel(){ QString MBValue; switch (ui->minSlider->value()){ case 0 : MBValue = "0 MB"; break; case 1 : MBValue = "1 MB"; break; case 2 : MBValue = "2 MB"; break; case 3: MBValue = "10 MB"; break; case 4 : MBValue = "30 MB"; break; case 5 : MBValue = "50 MB"; break; case 6 : MBValue = "100 MB"; break; case 7 : MBValue = "500 MB"; break; case 8 : MBValue = "1 GB"; break; case 9 : MBValue = "2 GB"; break; case 10 : MBValue = "5 GB"; break; case 11 : MBValue = "10 GB"; break; case 12 : MBValue = "50 GB"; break; case 13 : MBValue = "100 GB"; break; } ui->minMBLabel->setText(MBValue); switch (ui->maxSlider->value()){ case 0 : MBValue = "1 MB"; break; case 1 : MBValue = "2 MB"; break; case 2 : MBValue = "10 MB"; break; case 3: MBValue = "30 MB"; break; case 4 : MBValue = "50 MB"; break; case 5 : MBValue = "100 MB"; break; case 6 : MBValue = "500 MB"; break; case 7 : MBValue = "1 GB"; break; case 8 : MBValue = "2 GB"; break; case 9 : MBValue = "5 GB"; break; case 10 : MBValue = "10 GB"; break; case 11 : MBValue = "50 GB"; break; case 12 : MBValue = "100 GB"; break; case 13 : MBValue = "∞"; break; } ui->maxMBLabel->setText(MBValue); } void FilterWindow::on_plusButton_clicked() { int i = ui->wordsTable->rowCount(); if(ui->wordsTable->item(i-1,0) || i == 0){ ui->wordsTable->insertRow(i); ui->wordsTable->selectRow(i); } } void FilterWindow::on_minusButton_clicked() { QList <QTableWidgetItem *> selected = ui->wordsTable->selectedItems(); for(int j = 0; j < selected.size(); j++){ ui->wordsTable->removeRow(selected.at(j)->row()); } } void FilterWindow::on_caseSensitivityBox_clicked(bool checked) { caseSens = checked; }
26.619469
143
0.560971
[ "model" ]
a17b17d350ce54e185220ff8785ceb1a46c6d972
10,754
cpp
C++
tst/OpcUaStackCore/EventType/BaseEventType_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
tst/OpcUaStackCore/EventType/BaseEventType_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
tst/OpcUaStackCore/EventType/BaseEventType_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
#include "unittest.h" #include "OpcUaStackCore/StandardEventType/BaseEventType.h" using namespace OpcUaStackCore; BOOST_AUTO_TEST_SUITE(BaseEventType_) BOOST_AUTO_TEST_CASE(BaseEventType_) { std::cout << "BaseEventType_t" << std::endl; } BOOST_AUTO_TEST_CASE(BaseEventType_construct_destruct) { BaseEventType baseEventType; } BOOST_AUTO_TEST_CASE(BaseEventType_setter_error) { OpcUaVariant::SPtr value; BaseEventType baseEventType; // invalid type value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaString("String")); BOOST_REQUIRE(baseEventType.eventId(value) == false); } BOOST_AUTO_TEST_CASE(BaseEventType_setter_ok) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaByteString("ByteString")); BOOST_REQUIRE(baseEventType.eventId(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaNodeId(1)); BOOST_REQUIRE(baseEventType.eventType(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaString("String")); BOOST_REQUIRE(baseEventType.sourceName(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.localTime(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaLocalizedText("de", "text")); BOOST_REQUIRE(baseEventType.message(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.receiveTime(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue((OpcUaUInt16)1); BOOST_REQUIRE(baseEventType.severity(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaNodeId(2)); BOOST_REQUIRE(baseEventType.sourceNode(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.time(value) == true); } BOOST_AUTO_TEST_CASE(BaseEventType_getter_ok) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaByteString("ByteString")); BOOST_REQUIRE(baseEventType.eventId(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaNodeId(1)); BOOST_REQUIRE(baseEventType.eventType(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaString("String")); BOOST_REQUIRE(baseEventType.sourceName(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.localTime(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaLocalizedText("de", "text")); BOOST_REQUIRE(baseEventType.message(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.receiveTime(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue((OpcUaUInt16)1); BOOST_REQUIRE(baseEventType.severity(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaNodeId(2)); BOOST_REQUIRE(baseEventType.sourceNode(value) == true); value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaDateTime(now)); BOOST_REQUIRE(baseEventType.time(value) == true); // // getter // value = baseEventType.eventId(); OpcUaByteString eventId; BOOST_REQUIRE(value->getValue(eventId) == true); BOOST_REQUIRE(eventId == OpcUaByteString("ByteString")); value = baseEventType.eventType(); OpcUaNodeId eventType; BOOST_REQUIRE(value->getValue(eventType) == true); BOOST_REQUIRE(eventType == OpcUaNodeId(1)); value = baseEventType.sourceName(); OpcUaString sourceName; BOOST_REQUIRE(value->getValue(sourceName) == true); BOOST_REQUIRE(sourceName == OpcUaString("String")); value = baseEventType.localTime(); OpcUaDateTime localTime; BOOST_REQUIRE(value->getValue(localTime) == true); BOOST_REQUIRE(localTime == OpcUaDateTime(now)); value = baseEventType.message(); OpcUaLocalizedText message; BOOST_REQUIRE(value->getValue(message) == true); BOOST_REQUIRE(message == OpcUaLocalizedText("de", "text")); value = baseEventType.receiveTime(); OpcUaDateTime receiveTime; BOOST_REQUIRE(value->getValue(receiveTime) == true); BOOST_REQUIRE(receiveTime == OpcUaDateTime(now)); value = baseEventType.severity(); OpcUaUInt16 severity; BOOST_REQUIRE(value->getValue(severity) == true); BOOST_REQUIRE(severity == (OpcUaUInt16)1); value = baseEventType.sourceNode(); OpcUaNodeId sourceNode; BOOST_REQUIRE(value->getValue(sourceNode) == true); BOOST_REQUIRE(sourceNode == OpcUaNodeId(2)); value = baseEventType.time(); OpcUaDateTime time; BOOST_REQUIRE(value->getValue(time) == true); BOOST_REQUIRE(time == OpcUaDateTime(now)); } BOOST_AUTO_TEST_CASE(BaseEventType_namespace_index) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); } BOOST_AUTO_TEST_CASE(BaseEventType_broeseNameList_empty) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); // get event type OpcUaNodeId eventType("Unknown"); bool eventFound = false; std::list<OpcUaQualifiedName::SPtr> browseNameList; OpcUaVariant::SPtr variant; //BOOST_REQUIRE(eventBase->get(eventType, browseNameList, variant) == EventResult::BadBrowseNameListEmpty); //BOOST_REQUIRE(variant.get() == nullptr); } BOOST_AUTO_TEST_CASE(BaseEventType_typeId_unknwon) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); // get event type OpcUaNodeId eventType("Unknown"); bool eventFound = false; std::list<OpcUaQualifiedName::SPtr> browseNameList; browseNameList.push_back(constructSPtr<OpcUaQualifiedName>("Unknown")); bool error = false; OpcUaVariant::SPtr variant; BOOST_REQUIRE(eventBase->get(eventType, browseNameList, variant) == EventResult::BadEventTypeNotExist); BOOST_REQUIRE(variant.get() == nullptr); } BOOST_AUTO_TEST_CASE(BaseEventType_browsName_unknwon) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); // get event type OpcUaNodeId eventType((OpcUaUInt32)2041); bool eventFound = false; std::list<OpcUaQualifiedName::SPtr> browseNameList; browseNameList.push_back(constructSPtr<OpcUaQualifiedName>("Unknown")); bool error = false; OpcUaVariant::SPtr variant; BOOST_REQUIRE(eventBase->get(eventType, browseNameList, variant) == EventResult::BadValueNotExist); BOOST_REQUIRE(variant.get() == nullptr); } BOOST_AUTO_TEST_CASE(BaseEventType_variant_not_exist) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); // get event type OpcUaNodeId eventType((OpcUaUInt32)2041); bool eventFound = false; std::list<OpcUaQualifiedName::SPtr> browseNameList; browseNameList.push_back(constructSPtr<OpcUaQualifiedName>("EventId")); bool error = false; OpcUaVariant::SPtr variant; BOOST_REQUIRE(eventBase->get(eventType, browseNameList, variant) == EventResult::BadValueNotExist); BOOST_REQUIRE(variant.get() == nullptr); } BOOST_AUTO_TEST_CASE(BaseEventType_variant_success) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); OpcUaVariant::SPtr value; BaseEventType baseEventType; // // set event id // value = constructSPtr<OpcUaVariant>(); value->setValue(OpcUaByteString("ByteString")); BOOST_REQUIRE(baseEventType.eventId(value) == true); // // map namespace uri to namespace index // EventBase* eventBase = &baseEventType; std::vector<std::string> namespaceVec; namespaceVec.push_back(""); eventBase->namespaceArray(&namespaceVec); OpcUaNodeId typeNodeId; baseEventType.eventType()->getValue(typeNodeId); BOOST_REQUIRE(typeNodeId == OpcUaNodeId((OpcUaUInt32)2041)); // // get event type // OpcUaNodeId eventType((OpcUaUInt32)2041); bool eventFound = false; std::list<OpcUaQualifiedName::SPtr> browseNameList; browseNameList.push_back(constructSPtr<OpcUaQualifiedName>("EventId")); bool error = false; OpcUaVariant::SPtr variant; BOOST_REQUIRE(eventBase->get(eventType, browseNameList, variant) == EventResult::Success); BOOST_REQUIRE(variant.get() != nullptr); OpcUaByteString byteString; BOOST_REQUIRE(variant->getValue(byteString) == true); BOOST_REQUIRE(byteString == OpcUaByteString("ByteString")); } BOOST_AUTO_TEST_SUITE_END()
31.722714
109
0.74642
[ "vector" ]
a17d35ff663904cb4402d7ae738231297f66c965
11,770
hpp
C++
include/UnityEngine/Rendering/ScriptableRenderContext.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/Rendering/ScriptableRenderContext.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/Rendering/ScriptableRenderContext.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.IEquatable`1 #include "System/IEquatable_1.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Camera class Camera; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppObject; // Completed il2cpp-utils forward declares // Type namespace: UnityEngine.Rendering namespace UnityEngine::Rendering { // Forward declaring type: ScriptableRenderContext struct ScriptableRenderContext; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Rendering::ScriptableRenderContext, "UnityEngine.Rendering", "ScriptableRenderContext"); // Type namespace: UnityEngine.Rendering namespace UnityEngine::Rendering { // Size: 0x8 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Rendering.ScriptableRenderContext // [TokenAttribute] Offset: FFFFFFFF // [NativeHeaderAttribute] Offset: 11C2330 // [NativeTypeAttribute] Offset: 11C2330 // [NativeHeaderAttribute] Offset: 11C2330 // [NativeHeaderAttribute] Offset: 11C2330 // [NativeHeaderAttribute] Offset: 11C2330 // [NativeHeaderAttribute] Offset: 11C2330 struct ScriptableRenderContext/*, public ::System::ValueType, public ::System::IEquatable_1<::UnityEngine::Rendering::ScriptableRenderContext>*/ { public: public: // private System.IntPtr m_Ptr // Size: 0x8 // Offset: 0x0 ::System::IntPtr m_Ptr; // Field size check static_assert(sizeof(::System::IntPtr) == 0x8); public: // Creating value type constructor for type: ScriptableRenderContext constexpr ScriptableRenderContext(::System::IntPtr m_Ptr_ = {}) noexcept : m_Ptr{m_Ptr_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating interface conversion operator: operator ::System::IEquatable_1<::UnityEngine::Rendering::ScriptableRenderContext> operator ::System::IEquatable_1<::UnityEngine::Rendering::ScriptableRenderContext>() noexcept { return *reinterpret_cast<::System::IEquatable_1<::UnityEngine::Rendering::ScriptableRenderContext>*>(this); } // Creating conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept { return m_Ptr; } // Get instance field reference: private System.IntPtr m_Ptr ::System::IntPtr& dyn_m_Ptr(); // System.Void .ctor(System.IntPtr ptr) // Offset: 0x20CD304 // ABORTED: conflicts with another method. ScriptableRenderContext(::System::IntPtr ptr); // private System.Int32 GetNumberOfCameras_Internal() // Offset: 0x20CD9AC int GetNumberOfCameras_Internal(); // private UnityEngine.Camera GetCamera_Internal(System.Int32 index) // Offset: 0x20CDA2C ::UnityEngine::Camera* GetCamera_Internal(int index); // System.Int32 GetNumberOfCameras() // Offset: 0x20CD0F4 int GetNumberOfCameras(); // UnityEngine.Camera GetCamera(System.Int32 index) // Offset: 0x20CD134 ::UnityEngine::Camera* GetCamera(int index); // public System.Boolean Equals(UnityEngine.Rendering.ScriptableRenderContext other) // Offset: 0x20CDACC bool Equals(::UnityEngine::Rendering::ScriptableRenderContext other); // static private System.Int32 GetNumberOfCameras_Internal_Injected(ref UnityEngine.Rendering.ScriptableRenderContext _unity_self) // Offset: 0x20CD9EC static int GetNumberOfCameras_Internal_Injected(ByRef<::UnityEngine::Rendering::ScriptableRenderContext> _unity_self); // static private UnityEngine.Camera GetCamera_Internal_Injected(ref UnityEngine.Rendering.ScriptableRenderContext _unity_self, System.Int32 index) // Offset: 0x20CDA7C static ::UnityEngine::Camera* GetCamera_Internal_Injected(ByRef<::UnityEngine::Rendering::ScriptableRenderContext> _unity_self, int index); // public override System.Boolean Equals(System.Object obj) // Offset: 0x20CDB44 // Implemented from: System.ValueType // Base method: System.Boolean ValueType::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0x20CDBD0 // Implemented from: System.ValueType // Base method: System.Int32 ValueType::GetHashCode() int GetHashCode(); }; // UnityEngine.Rendering.ScriptableRenderContext #pragma pack(pop) static check_size<sizeof(ScriptableRenderContext), 0 + sizeof(::System::IntPtr)> __UnityEngine_Rendering_ScriptableRenderContextSizeCheck; static_assert(sizeof(ScriptableRenderContext) == 0x8); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::ScriptableRenderContext // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras_Internal // Il2CppName: GetNumberOfCameras_Internal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (UnityEngine::Rendering::ScriptableRenderContext::*)()>(&UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras_Internal)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetNumberOfCameras_Internal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetCamera_Internal // Il2CppName: GetCamera_Internal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Camera* (UnityEngine::Rendering::ScriptableRenderContext::*)(int)>(&UnityEngine::Rendering::ScriptableRenderContext::GetCamera_Internal)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetCamera_Internal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras // Il2CppName: GetNumberOfCameras template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (UnityEngine::Rendering::ScriptableRenderContext::*)()>(&UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetNumberOfCameras", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetCamera // Il2CppName: GetCamera template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Camera* (UnityEngine::Rendering::ScriptableRenderContext::*)(int)>(&UnityEngine::Rendering::ScriptableRenderContext::GetCamera)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetCamera", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::Rendering::ScriptableRenderContext::*)(::UnityEngine::Rendering::ScriptableRenderContext)>(&UnityEngine::Rendering::ScriptableRenderContext::Equals)> { static const MethodInfo* get() { static auto* other = &::il2cpp_utils::GetClassFromName("UnityEngine.Rendering", "ScriptableRenderContext")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras_Internal_Injected // Il2CppName: GetNumberOfCameras_Internal_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(ByRef<::UnityEngine::Rendering::ScriptableRenderContext>)>(&UnityEngine::Rendering::ScriptableRenderContext::GetNumberOfCameras_Internal_Injected)> { static const MethodInfo* get() { static auto* _unity_self = &::il2cpp_utils::GetClassFromName("UnityEngine.Rendering", "ScriptableRenderContext")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetNumberOfCameras_Internal_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{_unity_self}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetCamera_Internal_Injected // Il2CppName: GetCamera_Internal_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Camera* (*)(ByRef<::UnityEngine::Rendering::ScriptableRenderContext>, int)>(&UnityEngine::Rendering::ScriptableRenderContext::GetCamera_Internal_Injected)> { static const MethodInfo* get() { static auto* _unity_self = &::il2cpp_utils::GetClassFromName("UnityEngine.Rendering", "ScriptableRenderContext")->this_arg; static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetCamera_Internal_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{_unity_self, index}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::Rendering::ScriptableRenderContext::*)(::Il2CppObject*)>(&UnityEngine::Rendering::ScriptableRenderContext::Equals)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: UnityEngine::Rendering::ScriptableRenderContext::GetHashCode // Il2CppName: GetHashCode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (UnityEngine::Rendering::ScriptableRenderContext::*)()>(&UnityEngine::Rendering::ScriptableRenderContext::GetHashCode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::Rendering::ScriptableRenderContext), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
60.984456
242
0.754885
[ "object", "vector" ]
a17eea42352d6c59dbf9c1e29c52694c2e81c003
1,050
hpp
C++
examples/lookat/dinheiro.hpp
juniormaniusis/dino_wants_money-cg3
3c7807f762a159d5440c67c051f9033fffb922d1
[ "MIT" ]
null
null
null
examples/lookat/dinheiro.hpp
juniormaniusis/dino_wants_money-cg3
3c7807f762a159d5440c67c051f9033fffb922d1
[ "MIT" ]
null
null
null
examples/lookat/dinheiro.hpp
juniormaniusis/dino_wants_money-cg3
3c7807f762a159d5440c67c051f9033fffb922d1
[ "MIT" ]
null
null
null
#ifndef Dinheiro_HPP_ #define Dinheiro_HPP_ #include <random> #include <vector> #include "abcg.hpp" #include "camera.hpp" #include "gamedata.hpp" #include "model.hpp" typedef struct DinheiroUnidade { bool ativo{0}; float valor{100.0}; glm::vec3 posicao{0}; } DinheiroUnidade; class OpenGLWindow; class Dinheiro { public: ~Dinheiro(); void initializeGL(GLuint program, std::string assetsPath); void paintGL(GLuint program, glm::mat4 cameraViewMatrix); void terminateGL(); void computeModelMatrix(int positionIndex); std::vector<DinheiroUnidade*> gerarDinheiros(); void update(float deltaTime, glm::vec3 pacmanPosition, float* score); private: friend OpenGLWindow; Model m_model; glm::mat4 m_modelMatrix{0}; std::default_random_engine m_randomEngine; DinheiroUnidade* criaDinheiroUnidade(float valor, glm::vec3 posicao); bool checkColision(glm::vec3 dinheiroPosition, glm::vec3 pacmanPosition); std::vector<DinheiroUnidade*> m_dinheiros{}; glm::vec3 m_rotacao{-90, 0, 0}; float m_escala{0.005f}; }; #endif
25
75
0.749524
[ "vector", "model" ]
a180f5fed2a9372ba1aec310e0ec4d2c6f97efb8
11,622
cpp
C++
src/Game.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
2
2017-05-16T22:39:14.000Z
2021-03-16T13:56:55.000Z
src/Game.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
null
null
null
src/Game.cpp
TmCrafz/ArenaSFML
a112330816b1e76564194ead9aff99e28ff9b454
[ "MIT" ]
1
2017-12-05T05:34:20.000Z
2017-12-05T05:34:20.000Z
#include "Game.hpp" #include "Screens/CreditsScreen.hpp" #include "Screens/Screen.hpp" #include "Screens/MainGameScreen.hpp" #include "Screens/MainMenuScreen.hpp" #include "Screens/PauseScreen.hpp" #include "Screens/SettingsScreen.hpp" #include "Screens/TwoPlayerSelectionScreen.hpp" #include "Level/Level.hpp" #include "Helpers.hpp" #include <iostream> #include <memory> #include <cmath> Game::Game() : m_config("assets/config.ini") , m_screenHeight{ static_cast<unsigned int>( m_config.getInt("screen_width", 1024)) } , m_screenWidth{ static_cast<unsigned int>( m_config.getInt("screen_height", 768)) } , m_showStats{ m_config.getBool("show_stats", false) } , m_isInDebug{ m_config.getBool("debug_mode", false) } , m_referenceWorldWidth{ 800 } , m_referenceWorldHeight{ 480 } , m_background{ sf::Vector2f{ 10000.f, 10000.f} } , m_currentBgColorStep{ 0 } , m_totalBgStepTime{ 5.f } , m_currentBgStepTime{ 0.f } , m_window{ sf::VideoMode{ m_screenHeight, m_screenWidth} , "ARENA" } , m_music{ } , m_sound{ } , m_context{ &m_config, &m_window, &m_fontHolder, &m_textureHolder, &m_shaderHolder, &m_spriteSheetMapHolder, &m_levelHolder, &m_music, &m_sound, &m_background } , m_isRunning{ true } , m_isPaused{ false } , m_renderManager{ &m_sceneGraph } , m_dt{ 0 } , m_fps{ 0 } , m_averageFpsTime{ 0.f } , m_fpsInSec{ 0.f } , m_fpsCnt{ 0 } , m_averageFpsPerSec{ 0 } , m_timePoint1{ CLOCK::now() } , m_inputHandler{ &m_window } , m_screenStack{ m_context } { if (m_config.getBool("fullscreen", false)) { m_window.create(sf::VideoMode(m_screenHeight, m_screenWidth), "ArenaSFML", sf::Style::Fullscreen); } if (m_config.getBool("framerate_limit", true)) { m_window.setFramerateLimit(60); } if (m_config.getBool("vertical_sync", false)) { m_window.setVerticalSyncEnabled(true); } if (!m_config.getBool("show_mouse", false)) { m_window.setMouseCursorVisible(false); } int musicLevel{ m_config.getInt("music_level", 10) }; m_music.setVolume(musicLevel * 10); if (!m_config.getBool("music_on", true)) { m_music.setVolume(0.f); } int soundLevel{ m_config.getInt("sound_level", 10) }; m_sound.setVolume(soundLevel * 10); if (!m_config.getBool("sound_on", true)) { m_sound.setVolume(0.f); } //std::unique_ptr<Screen> actualScreen = { std::make_unique<MainGameScreen>(isInDebug, this, &m_window, m_fontHolder, m_textureHolder, m_spriteSheetMapHolder) }; //m_actualScreen = std::move(actualScreen); m_context.guiView = m_window.getView(); m_context.gameView = m_window.getView(); adjustShownWorldToWindowSize(m_window.getSize().x, m_window.getSize().y); loadFonts(); loadTextures(); loadShaders(); loadLevels(); loadMusic(); loadSounds(); buildScene(); // Register screens m_screenStack.registerScreen<MainMenuScreen>(ScreenID::MAINMENU); m_screenStack.registerScreen<TwoPlayerSelectionScreen> (ScreenID::TWOPLAYERSELECTION); m_screenStack.registerScreen<SettingsScreen>(ScreenID::SETTINGS); m_screenStack.registerScreen<CreditsScreen>(ScreenID::CREDITS); m_screenStack.registerScreen<PauseScreen>(ScreenID::PAUSE); m_screenStack.pushScreen(ScreenID::MAINMENU); } Game::~Game() { } void Game::adjustShownWorldToWindowSize(unsigned int windowWidth, unsigned int windowHeight) { // gameView zooms float scaleWidth = static_cast<float>(m_referenceWorldWidth) / static_cast<float>(windowWidth); float scaleHeight = static_cast<float>(m_referenceWorldHeight) / static_cast<float>(windowHeight); // We have to choose one scale so the shown area from game is approximately the // same (depending on the aspect ratio), but without distort the drawn world. float scale = std::min(scaleWidth, scaleHeight); sf::FloatRect visibleArea(0, 0, windowWidth * scale, windowHeight * scale); sf::View gameView(visibleArea); m_context.gameView = gameView; m_window.setView(m_context.gameView); // gui view (No zoom, only the size of the window) sf::View guiView(sf::FloatRect(0, 0, windowWidth, windowHeight)); m_context.guiView = guiView; } void Game::loadFonts() { //m_fontHolder.load("default", "assets/fonts/UbuntuMono-R.ttf"); m_fontHolder.load("default", "assets/fonts/cave-story/Cave-Story.ttf"); } void Game::loadTextures() { m_textureHolder.load( "knight", "assets/sprites/warriors/knight.png"); m_spriteSheetMapHolder.load( "knight", "assets/sprites/warriors/knight.txt"); m_textureHolder.load( "runner", "assets/sprites/warriors/runner.png"); m_spriteSheetMapHolder.load( "runner", "assets/sprites/warriors/runner.txt"); m_textureHolder.load( "wizard", "assets/sprites/warriors/wizard.png"); m_spriteSheetMapHolder.load( "wizard", "assets/sprites/warriors/wizard.txt"); m_textureHolder.load( "fireball", "assets/sprites/attacks/fireball.png"); m_spriteSheetMapHolder.load( "fireball", "assets/sprites/attacks/fireball.txt"); m_textureHolder.load( "level", "assets/sprites/tiles/level.png"); m_spriteSheetMapHolder.load( "level", "assets/sprites/tiles/level.txt"); } void Game::loadShaders() { // Dont load shaders, if there are not supportet if (!sf::Shader::isAvailable()) { std::cerr << "Shaders not supported" << std::endl; return; } m_shaderHolder.load<sf::Shader::Type>("grayscale", "assets/shaders/grayscale.frag", sf::Shader::Fragment); } void Game::loadLevels() { m_levelHolder.load("assets/level/level1.lvl"); m_levelHolder.load("assets/level/level2.lvl"); } void Game::loadMusic() { m_music.add("gametheme01", "assets/sounds/themes/S31-City_on_Speed.ogg"); m_music.add("gametheme02", "assets/sounds/themes/S31-Sentry.ogg"); m_music.add("menutheme01", "assets/sounds/themes/S31-200_Production.ogg"); } void Game::loadSounds() { m_sound.load("swoosh1", "assets/sounds/fx/swoosh1/swoosh1.wav"); m_sound.load("sword-clash", "assets/sounds/fx/sword-clash/sword-clash.wav"); m_sound.load("swoosh-long", "assets/sounds/fx/swoosh-long/swoosh-long.wav"); m_sound.load("slashkut", "assets/sounds/fx/slashkut/slashkut.wav"); m_sound.load("fireball", "assets/sounds/fx/fireball/fireball.wav"); m_sound.load("dodge", "assets/sounds/fx/dodge/dodge.wav"); } void Game::buildScene() { m_txtStatFPS.setFont(m_fontHolder.get("default")); m_txtStatFPS.setCharacterSize(12); m_txtStatFPS.setFillColor(sf::Color::White); // Background m_background.setOrigin(m_background.getSize().x / 2.f, m_background.getSize().y / 2.f); // The colors std::vector<sf::Color> colors { sf::Color(170, 255, 1, 255), // Green sf::Color(255, 170, 1, 255), // Orange sf::Color(255, 0, 170, 255), // Red sf::Color(170, 0, 255, 255), // Violet //sf::Color(0, 170, 255, 255) // Blue sf::Color(12, 39, 146, 255) // Blue }; // The colors from which to which is interpoled m_bgColorSteps = { { colors[0] , colors[1] }, // Green -> Orange { colors[1] , colors[2] }, // Orange -> Red { colors[2] , colors[3] }, // Red -> Violet { colors[3] , colors[4] }, // Violet -> Blue { colors[4] , colors[0] }, // Blue -> Green }; } void Game::run() { while (m_window.isOpen() && m_isRunning) { determineDeltaTime(); handleInput(); update(); render(); } } void Game::determineDeltaTime() { CLOCK::time_point timePoint2 = { CLOCK::now() }; std::chrono::duration<float> timeSpan = { timePoint2 - m_timePoint1 }; m_timePoint1 = CLOCK::now(); // Get deltaTime as float in seconds m_dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>> (timeSpan).count(); m_fps = 1.f / m_dt; m_averageFpsTime += m_dt; m_fpsInSec += m_fps; m_fpsCnt++; if (m_averageFpsTime >= 1.f) { m_averageFpsPerSec = m_fpsInSec / m_fpsCnt + 0.5f; m_averageFpsTime = 0.f; m_fpsInSec = 0.f; m_fpsCnt = 0; } m_txtStatFPS.setString("FPS: " + std::to_string(m_averageFpsPerSec) + " (" + std::to_string(m_fps) + ")"); } void Game::handleInput() { std::queue<sf::Event> eventQueue; m_inputHandler.handleInput(eventQueue, m_inputQueue); while(!m_inputQueue.isEmpty()) { Input input{ m_inputQueue.pop() }; switch (input.getInputType()) { case InputTypes::WINDOW_RESIZED : adjustShownWorldToWindowSize( m_window.getSize().x, m_window.getSize().y); m_screenStack.windowSizeChanged(); break; case InputTypes::LOST_FOCUS : m_isPaused = true; break; case InputTypes::GAINED_FOCUS : m_isPaused = false; break; default: break; } if (m_isInDebug) { switch (input.getInputType()) { case InputTypes::D1 : break; case InputTypes::D2 : // Show /hide statistics m_showStats = !m_showStats; break; case InputTypes::D3 : break; case InputTypes::D4 : break; default: break; } } // Let world class translate the input to commands, but only when the game // is not paused if (!m_isPaused) { //m_world.translateInput(input, m_dt); //m_actualScreen->handleInput(input, m_dt); m_screenStack.handleInput(input, m_dt); } } while(!eventQueue.empty()) { sf::Event event{ eventQueue.front() }; eventQueue.pop(); m_screenStack.handleEvent(event, m_dt); } } void Game::update() { updateBackground(m_dt); if (!m_isPaused) { //m_actualScreen->update(m_dt); m_screenStack.update(m_dt); /* m_world.safeSceneNodeTrasform(); //m_world.controlWorldEntities(); m_world.handleCommands(m_dt); m_world.update(m_dt); m_world.handleCollision(m_dt); */ m_sceneGraph.removeDestroyed(); m_sceneGraph.update(m_dt); } m_sound.removeStoppedSounds(); } void Game::updateBackground(float dt) { m_currentBgStepTime += dt; float colPos{ m_currentBgStepTime / m_totalBgStepTime }; // Go next step when current step is completed if (m_currentBgStepTime > m_totalBgStepTime) { colPos = 0.f; m_currentBgStepTime = 0.f; m_currentBgColorStep++; if (m_currentBgColorStep > m_bgColorSteps.size() - 1) { m_currentBgColorStep = 0; } } sf::Color curCol = Helpers::lerbRGBColor( m_bgColorSteps[m_currentBgColorStep][0], m_bgColorSteps[m_currentBgColorStep][1], colPos); m_background.setFillColor(curCol); } void Game::render() { m_window.clear(); //m_world.render(); //m_actualScreen->render(); m_screenStack.render(); sf::View oldView{ m_window.getView() }; m_window.setView(m_context.guiView); m_window.draw(m_renderManager); if (m_showStats) { m_window.draw(m_txtStatFPS); } m_window.setView(oldView); m_window.display(); }
30.344648
165
0.633196
[ "render", "vector" ]
a188c36a8b00fe35f5f79e01591f05f69b7dfe90
8,005
hpp
C++
include/fastdds/rtps/common/LocatorList.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
548
2020-06-02T11:59:31.000Z
2022-03-30T00:59:33.000Z
include/fastdds/rtps/common/LocatorList.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
1,068
2020-06-01T12:36:33.000Z
2022-03-31T09:57:34.000Z
include/fastdds/rtps/common/LocatorList.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
230
2020-06-04T02:46:23.000Z
2022-03-30T01:35:58.000Z
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file LocatorList.hpp */ #ifndef _FASTDDS_RTPS_COMMON_LOCATORLIST_HPP_ #define _FASTDDS_RTPS_COMMON_LOCATORLIST_HPP_ #include <fastrtps/fastrtps_dll.h> #include <fastdds/rtps/common/Locator.h> #include <fastdds/rtps/common/LocatorsIterator.hpp> #include <vector> #include <cstdint> #include <cstring> #include <iomanip> #include <algorithm> namespace eprosima { namespace fastdds { namespace rtps { typedef std::vector<Locator>::iterator LocatorListIterator; typedef std::vector<Locator>::const_iterator LocatorListConstIterator; /** * Adapter class that provides a LocatorsIterator interface from a LocatorListConstIterator */ class Locators : public LocatorsIterator { public: Locators( const LocatorListConstIterator& it) : it_(it) { } Locators( const Locators& other) : it_(other.it_) { } LocatorsIterator& operator ++() { ++it_; return *this; } bool operator ==( const LocatorsIterator& other) const { return it_ == static_cast<const Locators&>(other).it_; } bool operator !=( const LocatorsIterator& other) const { return it_ != static_cast<const Locators&>(other).it_; } const Locator& operator *() const { return (*it_); } private: LocatorListConstIterator it_; }; /** * Class LocatorList, a Locator vector that doesn't avoid duplicates. * @ingroup COMMON_MODULE */ class LocatorList { public: RTPS_DllAPI LocatorList() { } RTPS_DllAPI ~LocatorList() { } RTPS_DllAPI LocatorList( const LocatorList& list) : m_locators(list.m_locators) { } RTPS_DllAPI LocatorList( LocatorList&& list) : m_locators(std::move(list.m_locators)) { } RTPS_DllAPI LocatorList& operator =( const LocatorList& list) { m_locators = list.m_locators; return *this; } RTPS_DllAPI LocatorList& operator =( LocatorList&& list) { m_locators = std::move(list.m_locators); return *this; } RTPS_DllAPI bool operator ==( const LocatorList& locator_list) const { if (locator_list.m_locators.size() == m_locators.size()) { bool returnedValue = true; for (auto it = locator_list.m_locators.begin(); returnedValue && it != locator_list.m_locators.end(); ++it) { returnedValue = false; for (auto it2 = m_locators.begin(); !returnedValue && it2 != m_locators.end(); ++it2) { if (*it == *it2) { returnedValue = true; } } } return returnedValue; } return false; } RTPS_DllAPI LocatorListIterator begin() { return m_locators.begin(); } RTPS_DllAPI LocatorListIterator end() { return m_locators.end(); } RTPS_DllAPI LocatorListConstIterator begin() const { return m_locators.begin(); } RTPS_DllAPI LocatorListConstIterator end() const { return m_locators.end(); } RTPS_DllAPI size_t size() const { return m_locators.size(); } RTPS_DllAPI LocatorList& assign( const LocatorList& list) { if (!(*this == list)) { m_locators = list.m_locators; } return *this; } RTPS_DllAPI void clear() { return m_locators.clear(); } RTPS_DllAPI void reserve( size_t num) { return m_locators.reserve(num); } RTPS_DllAPI void resize( size_t num) { return m_locators.resize(num); } RTPS_DllAPI void push_back( const Locator& loc) { bool already = false; for (LocatorListIterator it = this->begin(); it != this->end(); ++it) { if (loc == *it) { already = true; break; } } if (!already) { m_locators.push_back(loc); } } RTPS_DllAPI void push_back( const LocatorList& locList) { for (auto it = locList.m_locators.begin(); it != locList.m_locators.end(); ++it) { this->push_back(*it); } } RTPS_DllAPI bool empty() const { return m_locators.empty(); } RTPS_DllAPI void erase( const Locator& loc) { auto it = std::find(m_locators.begin(), m_locators.end(), loc); if (it != m_locators.end()) { m_locators.erase(it); } } FASTDDS_DEPRECATED_UNTIL(3, "eprosima::fastrtps::rtps::LocatorList::contains(const Locator&)", "Unused method.") RTPS_DllAPI bool contains( const Locator& loc) { for (LocatorListIterator it = this->begin(); it != this->end(); ++it) { if (IsAddressDefined(*it)) { if (loc == *it) { return true; } } else { if (loc.kind == (*it).kind && loc.port == (*it).port) { return true; } } } return false; } RTPS_DllAPI bool isValid() const { for (LocatorListConstIterator it = this->begin(); it != this->end(); ++it) { if (!IsLocatorValid(*it)) { return false; } } return true; } RTPS_DllAPI void swap( LocatorList& locatorList) { this->m_locators.swap(locatorList.m_locators); } private: std::vector<Locator> m_locators; }; inline std::ostream& operator <<( std::ostream& output, const LocatorList& locList) { output << "["; if (!locList.empty()) { output << *(locList.begin()); for (auto it = locList.begin() + 1; it != locList.end(); ++it) { output << "," << *it; } } else { output << "_"; } output << "]"; return output; } inline std::istream& operator >>( std::istream& input, LocatorList& locList) { std::istream::sentry s(input); locList = LocatorList(); if (s) { char punct; Locator loc; std::ios_base::iostate excp_mask = input.exceptions(); try { input.exceptions(excp_mask | std::ios_base::failbit | std::ios_base::badbit); // Get [ input >> punct; while (punct != ']') { input >> loc >> punct; if (loc.kind != LOCATOR_KIND_INVALID) { locList.push_back(loc); } } } catch (std::ios_base::failure& ) { locList.clear(); logWarning(LOCATOR_LIST, "Error deserializing LocatorList"); } input.exceptions(excp_mask); } return input; } } // namespace rtps } // namespace fastdds } // namespace eprosima #endif /* _FASTDDS_RTPS_COMMON_LOCATORLIST_HPP_ */
21.871585
101
0.535415
[ "vector" ]
a18ac346ddea34c4fed371e025c86a8869db921d
11,190
hpp
C++
core/src/Morpheus_DiaMatrix.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
1
2021-12-18T01:18:49.000Z
2021-12-18T01:18:49.000Z
core/src/Morpheus_DiaMatrix.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
5
2021-10-05T15:12:02.000Z
2022-01-21T23:26:41.000Z
core/src/Morpheus_DiaMatrix.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
null
null
null
/** * Morpheus_DiaMatrix.hpp * * EPCC, The University of Edinburgh * * (c) 2021 - 2022 The University of Edinburgh * * Contributing Authors: * Christodoulos Stylianou (c.stylianou@ed.ac.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MORPHEUS_DIAMATRIX_HPP #define MORPHEUS_DIAMATRIX_HPP #include <Morpheus_Exceptions.hpp> #include <Morpheus_FormatTags.hpp> #include <Morpheus_DenseVector.hpp> #include <Morpheus_DenseMatrix.hpp> #include <Morpheus_DynamicMatrix.hpp> #include <impl/Morpheus_MatrixBase.hpp> #include <impl/Morpheus_Utils.hpp> namespace Morpheus { template <class ValueType, class... Properties> class DiaMatrix : public Impl::MatrixBase<DiaMatrix, ValueType, Properties...> { public: using traits = Impl::ContainerTraits<DiaMatrix, ValueType, Properties...>; using type = typename traits::type; using base = Impl::MatrixBase<DiaMatrix, ValueType, Properties...>; using tag = typename MatrixFormatTag<DiaTag>::tag; using value_type = typename traits::value_type; using non_const_value_type = typename traits::non_const_value_type; using index_type = typename traits::index_type; using non_const_index_type = typename traits::non_const_index_type; using array_layout = typename traits::array_layout; using memory_space = typename traits::memory_space; using execution_space = typename traits::execution_space; using device_type = typename traits::device_type; using memory_traits = typename traits::memory_traits; using HostMirror = typename traits::HostMirror; using pointer = typename traits::pointer; using const_pointer = typename traits::const_pointer; using reference = typename traits::reference; using const_reference = typename traits::const_reference; using index_array_type = Morpheus::DenseVector<index_type, index_type, array_layout, execution_space, memory_traits>; using const_index_array_type = const index_array_type; using index_array_pointer = typename index_array_type::value_array_pointer; using index_array_reference = typename index_array_type::value_array_reference; using const_index_array_reference = const index_array_reference; using value_array_type = Morpheus::DenseMatrix<value_type, index_type, array_layout, execution_space, memory_traits>; using const_value_array_type = const value_array_type; using value_array_pointer = typename value_array_type::value_array_pointer; using value_array_reference = typename value_array_type::value_array_reference; using const_value_array_reference = const value_array_reference; ~DiaMatrix() = default; DiaMatrix(const DiaMatrix &) = default; DiaMatrix(DiaMatrix &&) = default; DiaMatrix &operator=(const DiaMatrix &) = default; DiaMatrix &operator=(DiaMatrix &&) = default; // Construct an empty DiaMatrix inline DiaMatrix() : base(), _ndiags(0), _alignment(0), _diagonal_offsets(), _values() {} // Construct a DiaMatrix with: // a specific shape // number of non-zero entries // number of occupied diagonals // amount of padding used to align the data (default=32) inline DiaMatrix(const index_type num_rows, const index_type num_cols, const index_type num_entries, const index_type num_diagonals, const index_type alignment = 32) : base(num_rows, num_cols, num_entries), _ndiags(num_diagonals), _alignment(alignment), _diagonal_offsets(num_diagonals) { _values.resize(Impl::get_pad_size<index_type>(num_rows, alignment), num_diagonals); } inline DiaMatrix(const index_type num_rows, const index_type num_cols, const index_type num_entries, const index_array_type &diag_offsets, const value_array_type &vals) : base(num_rows, num_cols, num_entries), _diagonal_offsets(diag_offsets), _values(vals) { _ndiags = _diagonal_offsets.size(); _alignment = _values.nrows(); } template <typename ValuePtr, typename IndexPtr> explicit inline DiaMatrix( const index_type num_rows, const index_type num_cols, const index_type num_entries, IndexPtr diag_offsets_ptr, ValuePtr vals_ptr, const index_type num_diagonals, const index_type alignment = 32, typename std::enable_if<std::is_pointer<ValuePtr>::value && std::is_pointer<IndexPtr>::value>::type * = nullptr) : base(num_rows, num_cols, num_entries), _diagonal_offsets(num_diagonals, diag_offsets_ptr), _values(Impl::get_pad_size<index_type>(num_rows, alignment), num_diagonals, vals_ptr) {} // Construct from another matrix type (Shallow) template <class VR, class... PR> DiaMatrix(const DiaMatrix<VR, PR...> &src, typename std::enable_if<is_compatible_type< DiaMatrix, typename DiaMatrix<VR, PR...>::type>::value>::type * = nullptr) : base(src.nrows(), src.ncols(), src.nnnz()), _ndiags(src.ndiags()), _alignment(src.alignment()), _diagonal_offsets(src.cdiagonal_offsets()), _values(src.cvalues()) {} // Assignment from another matrix type (Shallow) template <class VR, class... PR> typename std::enable_if< is_compatible_type<DiaMatrix, typename DiaMatrix<VR, PR...>::type>::value, DiaMatrix &>::type operator=(const DiaMatrix<VR, PR...> &src) { this->set_nrows(src.nrows()); this->set_ncols(src.ncols()); this->set_nnnz(src.nnnz()); _ndiags = src.ndiags(); _alignment = src.alignment(); _diagonal_offsets = src.cdiagonal_offsets(); _values = src.cvalues(); return *this; } // Construct from a compatible dynamic matrix type (Shallow) // Throws when active type of dynamic matrix not same to concrete type template <class VR, class... PR> DiaMatrix( const DynamicMatrix<VR, PR...> &src, typename std::enable_if<is_compatible_container< DiaMatrix, typename DynamicMatrix<VR, PR...>::type>::value>::type * = nullptr) : base(src.nrows(), src.ncols(), src.nnnz()) { auto f = std::bind(Impl::any_type_assign(), std::placeholders::_1, std::ref(*this)); std::visit(f, src.const_formats()); } // Assignment from a compatible dynamic matrix type (Shallow) // Throws when active type of dynamic matrix not same to concrete type template <class VR, class... PR> typename std::enable_if< is_compatible_container<DiaMatrix, typename DynamicMatrix<VR, PR...>::type>::value, DiaMatrix &>::type operator=(const DynamicMatrix<VR, PR...> &src) { auto f = std::bind(Impl::any_type_assign(), std::placeholders::_1, std::ref(*this)); std::visit(f, src.const_formats()); return *this; } // Construct from another matrix type template <typename MatrixType> DiaMatrix(const MatrixType &src) = delete; // Assignment from another matrix type template <typename MatrixType> reference operator=(const MatrixType &src) = delete; // Resize matrix dimensions and underlying storage inline void resize(const index_type num_rows, const index_type num_cols, const index_type num_entries, const index_type num_diagonals, const index_type alignment = 32) { base::resize(num_rows, num_cols, num_entries); _ndiags = num_diagonals; _alignment = alignment; if (this->exceeds_tolerance(num_rows, num_entries, _ndiags)) { throw Morpheus::FormatConversionException( "DiaMatrix fill-in would exceed maximum tolerance"); } _diagonal_offsets.resize(num_diagonals); _values.resize(Impl::get_pad_size<index_type>(num_rows, alignment), num_diagonals); } template <class VR, class... PR> inline void resize(const DiaMatrix<VR, PR...> &src) { resize(src.nrows(), src.ncols(), src.nnnz(), src.ndiags(), src.alignment()); } template <class VR, class... PR> inline DiaMatrix &allocate(const DiaMatrix<VR, PR...> &src) { resize(src.nrows(), src.ncols(), src.nnnz(), src.ndiags(), src.alignment()); return *this; } formats_e format_enum() const { return _id; } int format_index() const { return static_cast<int>(_id); } bool exceeds_tolerance(const index_type num_rows, const index_type num_entries, const index_type num_diagonals) { const float max_fill = 10.0; const float threshold = 10e9; // 100M entries const float size = float(num_diagonals) * float(num_rows); const float fill_ratio = size / std::max(1.0f, float(num_entries)); if (max_fill < fill_ratio && size > threshold) { return true; } else { return false; } } MORPHEUS_FORCEINLINE_FUNCTION index_array_reference diagonal_offsets(index_type n) { return _diagonal_offsets(n); } MORPHEUS_FORCEINLINE_FUNCTION value_array_reference values(index_type i, index_type j) { return _values(i, j); } MORPHEUS_FORCEINLINE_FUNCTION const_index_array_reference cdiagonal_offsets(index_type n) const { return _diagonal_offsets(n); } MORPHEUS_FORCEINLINE_FUNCTION const_value_array_reference cvalues(index_type i, index_type j) const { return _values(i, j); } MORPHEUS_FORCEINLINE_FUNCTION index_array_type &diagonal_offsets() { return _diagonal_offsets; } MORPHEUS_FORCEINLINE_FUNCTION value_array_type &values() { return _values; } MORPHEUS_FORCEINLINE_FUNCTION const_index_array_type &cdiagonal_offsets() const { return _diagonal_offsets; } MORPHEUS_FORCEINLINE_FUNCTION const_value_array_type &cvalues() const { return _values; } MORPHEUS_FORCEINLINE_FUNCTION index_type ndiags() const { return _ndiags; } MORPHEUS_FORCEINLINE_FUNCTION index_type alignment() const { return _alignment; } MORPHEUS_FORCEINLINE_FUNCTION void set_ndiags( const index_type num_diagonals) { _ndiags = num_diagonals; } MORPHEUS_FORCEINLINE_FUNCTION void set_alignment(const index_type alignment) { _alignment = alignment; } private: index_type _ndiags, _alignment; index_array_type _diagonal_offsets; value_array_type _values; static constexpr formats_e _id = Morpheus::DIA_FORMAT; }; } // namespace Morpheus #endif // MORPHEUS_DIAMATRIX_HPP
36.449511
80
0.687846
[ "shape" ]
a18b569472836c339d4c70c7b92d6ad8734ff546
3,811
cpp
C++
TAO/tests/Bug_1670_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_1670_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_1670_Regression/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
/** * @file server.cpp * * $Id: server.cpp 95464 2012-01-20 19:01:49Z johnnyw $ * * @author Carlos O'Ryan <coryan@atdesk.com> */ #include "TestS.h" #include "tao/corba.h" #include "tao/ORB_Core.h" #include "ace/Get_Opt.h" #include "ace/Reactor.h" /** * @class Simple_C * * @brief A simple implementation of the 'C' object. * */ class Simple_C : public virtual POA_Baz::AMH_C { public: Simple_C (CORBA::ORB_ptr orb); void op1 (Foo::Bar::AMH_AResponseHandler_ptr _tao_rh); void op2 (Foo::Bar::AMH_AResponseHandler_ptr _tao_rh); void op3 (Foo::Bar::AMH_BResponseHandler_ptr _tao_rh); void op4 (Baz::AMH_CResponseHandler_ptr _tao_rh); void shutdown (Baz::AMH_CResponseHandler_ptr); protected: CORBA::ORB_var orb_; }; /***************************/ /*** Servant Definition ***/ Simple_C::Simple_C (CORBA::ORB_ptr orb) : orb_ (CORBA::ORB::_duplicate (orb)) { } void Simple_C::op1(Foo::Bar::AMH_AResponseHandler_ptr _tao_rh) { _tao_rh->op1(1); } void Simple_C::op2(Foo::Bar::AMH_AResponseHandler_ptr _tao_rh) { _tao_rh->op2(2); } void Simple_C::op3(Foo::Bar::AMH_BResponseHandler_ptr _tao_rh) { _tao_rh->op3(3); } void Simple_C::op4(Baz::AMH_CResponseHandler_ptr _tao_rh) { _tao_rh->op4(4); } void Simple_C::shutdown (Baz::AMH_CResponseHandler_ptr) { this->orb_->shutdown (); } // **************************************************************** const ACE_TCHAR *ior_output_file = ACE_TEXT("test.ior"); int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("o:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'o': ior_output_file = get_opts.opt_arg (); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-o <iorfile>" "\n", argv [0]), -1); } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); if (CORBA::is_nil (root_poa.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Panic: nil RootPOA\n"), 1); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); if (parse_args (argc, argv) != 0) return 1; PortableServer::Servant_var<Simple_C> simple_c_impl( new Simple_C(orb.in())); PortableServer::ObjectId_var id = root_poa->activate_object (simple_c_impl.in ()); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); Baz::C_var simple_c = Baz::C::_narrow (object.in ()); CORBA::String_var ior = orb->object_to_string (simple_c.in ()); // Output the IOR to the <ior_output_file> FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); poa_manager->activate (); orb->run (); ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n")); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
22.028902
73
0.574128
[ "object" ]
a19030dba9e098763d17fd7f6e9dedd2531808ea
15,112
cpp
C++
ANode/parser/test/TestSingleDefsFile.cpp
ecmwf/ecflow
2498d0401d3d1133613d600d5c0e0a8a30b7b8eb
[ "Apache-2.0" ]
11
2020-08-07T14:42:45.000Z
2021-10-21T01:59:59.000Z
ANode/parser/test/TestSingleDefsFile.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
10
2020-08-07T14:36:27.000Z
2022-02-22T06:51:24.000Z
ANode/parser/test/TestSingleDefsFile.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
6
2020-08-07T14:34:38.000Z
2022-01-10T12:06:27.000Z
#define BOOST_TEST_MODULE TestParser //============================================================================ // Name : // Author : Avi // Revision : $Revision$ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : //============================================================================ #include <string> #include <iostream> #include <fstream> #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include <boost/timer/timer.hpp> #include <boost/chrono.hpp> #include "boost/date_time/posix_time/posix_time_types.hpp" #include <boost/test/unit_test.hpp> #include "DefsStructureParser.hpp" #include "Defs.hpp" #include "NodeContainer.hpp" #include "Suite.hpp" #include "Task.hpp" #include "Family.hpp" #include "PrintStyle.hpp" #include "PersistHelper.hpp" #include "JobsParam.hpp" #include "Jobs.hpp" #include "Log.hpp" #include "System.hpp" #include "File.hpp" #include "Str.hpp" namespace fs = boost::filesystem; using namespace std; using namespace ecf; using namespace boost::posix_time; BOOST_AUTO_TEST_SUITE( ParserTestSuite ) // This test is used to find a task given a path of the form: // suite/family/task // suite/family/family/task void test_find_task_using_path( NodeContainer* f,const Defs& defs ) { BOOST_CHECK_MESSAGE(f == defs.findAbsNode(f->absNodePath()).get(), "Could not find path " << f->absNodePath() << "\n"); for(node_ptr t: f->nodeVec()) { BOOST_CHECK_MESSAGE(t.get() == defs.findAbsNode(t->absNodePath()).get(), "Could not find path " << t->absNodePath() << "\n"); Family* family = t->isFamily(); if (family) { test_find_task_using_path(family, defs); } } } // Create derived class, so that we can time the parse only // i.e ignore expression build/checking and limit checking class TestDefsStructureParser : public DefsStructureParser { public: TestDefsStructureParser(Defs* defsfile, const std::string& file_name) : DefsStructureParser(defsfile,file_name) {} bool do_parse_file(std::string& errorMsg) { return DefsStructureParser::do_parse_file(errorMsg); } }; double get_seconds( const boost::timer::nanosecond_type& elapsed ) { return static_cast<double>( boost::chrono::nanoseconds( elapsed ).count() ) * boost::chrono::nanoseconds::period::num / boost::chrono::nanoseconds::period::den; } BOOST_AUTO_TEST_CASE( test_single_defs ) { boost::timer::auto_cpu_timer auto_cpu_timer; std::string path = File::test_data("ANode/parser/test/data/single_defs/mega.def","parser"); size_t mega_file_size = fs::file_size(path); cout << "AParser:: ...test_single_defs " << path << " file_size(" << mega_file_size << ")\n"; // Time parse/resolve dependencies: This will need to be #defined depending on the platform // Change for file_iterator to plain string halved the time taken to load operation suite boost::timer::cpu_timer timer; #ifdef DEBUG #if defined(HPUX) || defined(_AIX) double expectedTimeForParse = 15.0; double expectedTimeForParseOnly = 10.0; double expectedTimeForResolveDependencies = 3.5; // this is time for 10 job submissions double checkExprAndLimits = 1.0; double expectedTimeForFindAllPaths = 7.2; double expectedTimeForDefsPersistOnly = 6 ; double expectedTimeForDefsPersistAndReload = 24; double expectedTimeForCheckPtPersistAndReload = 27; #else double expectedTimeForParse = 4.5; double expectedTimeForParseOnly = 2.0; double expectedTimeForResolveDependencies = 0.5 ; // this is time for 10 job submissions double checkExprAndLimits = 0.5; double expectedTimeForFindAllPaths = 1.2; double expectedTimeForDefsPersistOnly = 2 ; double expectedTimeForDefsPersistAndReload = 4.5; double expectedTimeForCheckPtPersistAndReload = 8.0; #endif #else #if defined(HPUX) || defined(_AIX) double expectedTimeForParse = 7.8; double expectedTimeForParseOnly = 5.0; double expectedTimeForResolveDependencies = 3.5; // this is time for 10 job submissions double checkExprAndLimits = 1.0; double expectedTimeForFindAllPaths = 4.5; double expectedTimeForDefsPersistOnly = 3.5 ; double expectedTimeForDefsPersistAndReload = 9.5; double expectedTimeForCheckPtPersistAndReload = 11.5; #else double expectedTimeForParse = 1.2; double expectedTimeForParseOnly = 0.6; double expectedTimeForResolveDependencies = 0.2 ; // this is time for 10 job submissions double checkExprAndLimits = 0.1; double expectedTimeForFindAllPaths = 0.58; double expectedTimeForDefsPersistOnly = 0.4 ; double expectedTimeForDefsPersistAndReload = 1.4; double expectedTimeForCheckPtPersistAndReload = 1.6; #endif #endif // **************************************************************************************** // Please note: that for Parsing: that the predominate time is taken in creating the AST/ and checking /// If this is moved below, we get some caching affect, with the persist and reload timing Defs defs; { timer.start(); std::string errorMsg,warningMsg; BOOST_REQUIRE_MESSAGE(defs.restore(path,errorMsg,warningMsg),errorMsg); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForParse,"Performance regression, expected < " << expectedTimeForParse << " seconds for parse/node tree creation but found " << timer.format(3,Str::cpu_timer_format())); cout << " Parsing Node tree and AST creation time = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForParse << ")" << endl; } { Defs local_defs; timer.start(); TestDefsStructureParser checkPtParser( &local_defs, path); std::string errorMsg; BOOST_REQUIRE_MESSAGE(checkPtParser.do_parse_file(errorMsg),errorMsg); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForParse,"Performance regression, expected < " << expectedTimeForParseOnly << " seconds for parse/node tree creation but found " << timer.format(3,Str::cpu_timer_format())); cout << " Parsing Node tree *only* time = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForParseOnly << ")" << endl; } { timer.start(); for(suite_ptr s: defs.suiteVec()) { test_find_task_using_path(s.get(),defs); } BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForFindAllPaths,"Performance regression, expected < " << expectedTimeForFindAllPaths << " seconds to find all paths, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Test all paths can be found. time taken = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForFindAllPaths << ")" << endl; } { // Test time for persisting to defs file only #ifdef DEBUG std::string tmpFilename = "tmp_d.def"; #else std::string tmpFilename = "tmp.def"; #endif timer.start(); PrintStyle style(PrintStyle::DEFS); std::ofstream ofs( tmpFilename.c_str() ); ofs << defs; BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForDefsPersistOnly,"Performance regression, expected < " << expectedTimeForDefsPersistOnly << " to persist defs file, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Persist only, time taken = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForDefsPersistOnly << ")" << endl; std::remove(tmpFilename.c_str()); } { // may need to comment out output for large differences. Will double the time. timer.start(); PersistHelper helper; BOOST_CHECK_MESSAGE( helper.test_persist_and_reload(defs,PrintStyle::DEFS), helper.errorMsg()); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForDefsPersistAndReload,"Performance regression, expected < " << expectedTimeForDefsPersistAndReload << " seconds to persist and reload, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Persist and reload(DEFS) and compare, time taken = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForDefsPersistAndReload << ")" << " file_size(" << helper.file_size() << ")" << endl; } { timer.start(); PersistHelper helper; BOOST_CHECK_MESSAGE( helper.test_persist_and_reload(defs,PrintStyle::STATE), helper.errorMsg()); cout << " Persist and reload(STATE) and compare, time taken = " << timer.format(3,Str::cpu_timer_format()) << " file_size(" << helper.file_size() << ")" << endl; } { timer.start(); PersistHelper helper; BOOST_CHECK_MESSAGE( helper.test_persist_and_reload(defs,PrintStyle::MIGRATE), helper.errorMsg()); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForDefsPersistAndReload,"Performance regression, expected < " << expectedTimeForDefsPersistAndReload << " seconds to persist and reload *state*, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Persist and reload(MIGRATE) and compare, time taken = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForDefsPersistAndReload << ")" << " file_size(" << helper.file_size() << ")" << endl; // each platform will have a slightly different size, since the server environment variables // will be different, i.e host, pid, i.e check point etc, encompasses the host name, which will be different BOOST_CHECK_MESSAGE(helper.file_size() <= 6679000 ,"File size regression expected <= 6679000 but found " << helper.file_size()); } { timer.start(); PersistHelper helper; BOOST_CHECK_MESSAGE( helper.test_persist_and_reload(defs,PrintStyle::NET), helper.errorMsg()); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForDefsPersistAndReload,"Performance regression, expected < " << expectedTimeForDefsPersistAndReload << " seconds to persist and reload *state*, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Persist and reload(NET) and compare, time taken = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForDefsPersistAndReload << ")" << " file_size(" << helper.file_size() << ")" << endl; // each platform will have a slightly different size, since the server environment variables // will be different, i.e host, pid, i.e check point etc, encompasses the host name, which will be different BOOST_CHECK_MESSAGE(helper.file_size() <= 6679000 ,"File size regression expected <= 6679000 but found " << helper.file_size()); } { timer.start(); PersistHelper helper; BOOST_CHECK_MESSAGE( helper.test_cereal_checkpt_and_reload(defs,true), helper.errorMsg()); BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForCheckPtPersistAndReload,"Performance regression, expected < " << expectedTimeForCheckPtPersistAndReload << " seconds to persist and reload, but found " << timer.format(3,Str::cpu_timer_format())); cout << " Checkpt(CEREAL) and reload and compare, time taken = "; cout << timer.format(3,Str::cpu_timer_format()) << " < limit(" << expectedTimeForCheckPtPersistAndReload << ")" << " file_size(" << helper.file_size() << ")" << endl; } { // Time how long it takes for job submission. Must call begin on all suites first. timer.start(); defs.beginAll(); int count = 10; JobsParam jobsParam; // default is *not* to create jobs, and *not* to spawn jobs, hence only used in testing Jobs jobs(&defs); for (int i = 0; i < count; i++) {jobs.generate(jobsParam);} cout << " " << count << " jobSubmissions = " << timer.format(3,Str::cpu_timer_format()) << "s jobs:" << jobsParam.submitted().size() << " < limit(" << expectedTimeForResolveDependencies << ")" << endl; BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < expectedTimeForResolveDependencies, "jobSubmission Performance regression, expected < " << expectedTimeForResolveDependencies << " seconds for resolving dependencies but found " << timer.format(3,Str::cpu_timer_format()) ); } { // Time how long it takes for post process timer.start(); string errorMsg,warningMsg; BOOST_CHECK(defs.check(errorMsg,warningMsg)); cout << " Defs::check (inlimit resolution) = " << timer.format(3,Str::cpu_timer_format()) << " < limit(" << checkExprAndLimits << ")" << endl; BOOST_CHECK_MESSAGE(get_seconds(timer.elapsed().user) < checkExprAndLimits, "Defs::check Performance regression, expected < " << checkExprAndLimits << " seconds for resolving dependencies but found " << timer.format(3,Str::cpu_timer_format()) ); } { // Time how long it takes to delete all nodes/ references. Delete all tasks and then suites/families. timer.start(); std::vector<Task*> tasks; defs.getAllTasks(tasks); BOOST_CHECK_MESSAGE( tasks.size() > 0,"Expected > 0 tasks but found " << tasks.size()); for(Task* t: tasks) { BOOST_REQUIRE_MESSAGE(defs.deleteChild(t)," Failed to delete task"); } tasks.clear(); defs.getAllTasks(tasks); BOOST_REQUIRE_MESSAGE( tasks.empty(),"Expected all tasks to be deleted but found " << tasks.size()); std::vector<suite_ptr> vec = defs.suiteVec(); // make a copy, to avoid invalidating iterators BOOST_CHECK_MESSAGE( vec.size() > 0,"Expected > 0 Suites but found " << vec.size()); for(suite_ptr s: vec) { std::vector<node_ptr> familyVec = s->nodeVec(); // make a copy, to avoid invalidating iterators for(node_ptr f: familyVec) { BOOST_REQUIRE_MESSAGE(defs.deleteChild(f.get())," Failed to delete family"); } BOOST_REQUIRE_MESSAGE( s->nodeVec().empty(),"Expected all Families to be deleted but found " << s->nodeVec().size()); BOOST_REQUIRE_MESSAGE(defs.deleteChild(s.get())," Failed to delete suite"); } BOOST_REQUIRE_MESSAGE( defs.suiteVec().empty(),"Expected all Suites to be deleted but found " << defs.suiteVec().size()); cout << " time for deleting all nodes = " << timer.format(3,Str::cpu_timer_format()) << endl; } // Explicitly destroy, To keep valgrind happy Log::destroy(); System::destroy(); // cout << "Printing Defs \n"; // PrintStyle style(PrintStyle::DEFS); // std::cout << defs; } BOOST_AUTO_TEST_SUITE_END()
50.711409
275
0.670461
[ "vector" ]
a19069aeae054e418101be383e74d495fc434824
2,150
cpp
C++
atcoder/abc029/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
atcoder/abc029/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
atcoder/abc029/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
// atcoder/abc029/D/main.cpp // author: @___Johniel // github: https://github.com/johniel/ #include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } // void fn(string s) // { // const int N = 10 + 2; // const int M = 10; // const int K = 2; // static int dp[N][M][K]; // fill(&dp[0][0][0], &dp[N - 1][M - 1][K - 1] + 1, -(1 << 29)); // dp[0][0][false] = 0; // for (int i = 0; i < s.size(); ++i) { // for (int j = 0; j <= 9; ++j) { // for (int k = false; k <= true; ++k) { // if (dp[i][j][k] < 0) continue; // for (int x = 0; x <= (k ? 9 : s[i] - '0'); ++x) { // int& y = dp[i + 1][x][k || (x < s[i] - '0')]; // setmax(y, 0); // y += dp[i][j][k] + (x == 1); // } // } // } // } // lli sum = 0; // for (int i = 0; i <= 9; ++i) { // sum += max(0, dp[s.size()][i][false]); // sum += max(0, dp[s.size()][i][true]); // } // cout << sum << endl; // } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); lli n; while (cin >> n) { lli sum = 0; lli w = 10; for (int _ = 0; _ < 12; ++_) { sum += (n / w) * (w / 10); lli x = (n % w) - (w / 10) + 1; if (0 <= x) { sum += min(w / 10, x); } w *= 10; } cout << sum << endl; } return 0; }
29.054054
144
0.471628
[ "vector" ]
08489c1143f025cbe293d835cd66eb327fff5e8e
10,852
cpp
C++
src/rs-camProcess.cpp
TebogoNakampe/OpenGesture-HandTracking
870c93ec0bb4d7fa873f2c30c520dc64ffe38f36
[ "BSD-3-Clause" ]
4
2019-07-05T15:56:11.000Z
2021-01-24T07:13:39.000Z
src/rs-camProcess.cpp
TebogoNakampe/OpenGesture
870c93ec0bb4d7fa873f2c30c520dc64ffe38f36
[ "BSD-3-Clause" ]
null
null
null
src/rs-camProcess.cpp
TebogoNakampe/OpenGesture
870c93ec0bb4d7fa873f2c30c520dc64ffe38f36
[ "BSD-3-Clause" ]
1
2019-06-27T16:32:06.000Z
2019-06-27T16:32:06.000Z
#include "global.h" #include "kernels.h" #include "rs-camProcess.h" #include <math.h> cvCamCapture::cvCamCapture(QObject* parent) : QObject(parent) { m_videoCapture = new cv::VideoCapture(3); m_videoCapture->open(3); m_videoCapture->set(CV_CAP_PROP_FRAME_WIDTH, CAM_WIDTH); m_videoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, CAM_HEIGHT); if(!m_videoCapture->isOpened()) qDebug() << "CANNOT OPEN CAMERA"; } cvCamCapture::~cvCamCapture() { delete m_videoCapture; } void cvCamCapture::getFrame() { cv::Mat frame; m_videoCapture->read(frame); emit frameReady(frame); } cvProcessFrame::cvProcessFrame(QObject* parent) : QObject(parent) { // MATs pre-allocation (save time later) m_bgr.create(CAM_HEIGHT, CAM_WIDTH, CV_8UC3); m_hsv.create(CAM_HEIGHT, CAM_WIDTH, CV_8UC3); m_oneChannel.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_blended.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_channelSplit[0].create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_channelSplit[1].create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_channelSplit[2].create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_deltaH_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_deltaS_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_delta_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_temp0_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_temp1_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_temp0_32F.create(CAM_HEIGHT, CAM_WIDTH, CV_32F); m_temp0_64F.create(CAM_HEIGHT, CAM_WIDTH, CV_64F); m_temp1_64F.create(CAM_HEIGHT, CAM_WIDTH, CV_64F); m_temp2_64F.create(CAM_HEIGHT, CAM_WIDTH, CV_64F); m_floodFill_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_distance_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_distanceMasked_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); m_splitScreen_8U.create(CAM_HEIGHT, CAM_WIDTH, CV_8U); // vector pre allocation m_thetaVector.fill(0, 360); m_thetaConv.fill(0, 360); m_convKernel << GAUSSIAN_9; m_peaks.fill(0, 5); // init kalman filter initTracker(0.5f); for(int i=0; i<parametersTable.size(); i++) m_parameters.insert(parametersTable.at(i).m_id, parametersTable.at(i).m_default); updateParameters(); } cvProcessFrame::~cvProcessFrame() { delete m_tracker; } void cvProcessFrame::updateParameters() { m_mirror = m_parameters.value("mirror"); m_output = m_parameters.value("output"); m_channel = m_parameters.value("channel"); m_blend = m_parameters.value("blend")/100.0; m_sigma = 1.f/(2.f*std::pow((double)m_parameters.value("sigma"), 2)); m_huePicker = m_parameters.value("huePicker"); m_satPicker = m_parameters.value("satPicker"); m_median = m_parameters.value("median"); m_threshold = m_parameters.value("threshold"); } void cvProcessFrame::getParameters(const QString& _parameterId, const int& _value) { m_parameters.insert(_parameterId, _value); updateParameters(); } void cvProcessFrame::processFrame(const cv::Mat& _frame) { _frame.copyTo(m_hsv); //actually this is BGR! if(m_mirror == 1) cv::flip(m_hsv, m_bgr, 1); // bgr version stored on m_bgr (mirrored if m_mirror is true) cv::cvtColor(m_bgr, m_hsv, CV_BGR2HSV); // hsv channels on m_hsv MAT cv::split(m_hsv, m_channelSplit); m_oneChannel = m_channelSplit[m_channel]; // 3 MATs array // find the distance from the skin picker tone in HS space for each pixel m_channelSplit[0].convertTo(m_temp1_64F, CV_64F); //hue channel cv::threshold(m_temp1_64F, m_temp2_64F, 90.f, 180.f, cv::THRESH_BINARY); // circular shift on range (values 90 to 180 become -90 to 0) m_temp0_64F = m_temp1_64F - m_temp2_64F; m_temp1_64F = 0.5*(m_temp0_64F - (double)m_huePicker); m_channelSplit[1].convertTo(m_temp0_64F, CV_64F); //saturation channel m_temp2_64F = 0.1*(m_temp0_64F - (double)m_satPicker); // apply a gaussian curve for each pixel cv::pow(m_temp1_64F, 2, m_temp0_64F); m_temp0_64F.convertTo(m_deltaH_8U, CV_8U); //delta^2 in Cb image cv::pow(m_temp2_64F, 2, m_temp1_64F); m_temp1_64F.convertTo(m_deltaS_8U, CV_8U); //delta^2 in Cr image m_temp2_64F = m_temp0_64F + m_temp1_64F; m_temp0_64F = -(m_temp2_64F * m_sigma); //gaussian curve 1/2 cv::exp(m_temp0_64F, m_temp1_64F); //gaussian curve 2/2 m_temp2_64F = m_temp1_64F * 255.f; //normalize to 0-255 before converting to 8bit m_temp2_64F.convertTo(m_temp0_8U, CV_8U); // median filtering cv::medianBlur(m_temp0_8U, m_delta_8U, (m_median/2)*2+1); // extract hand shape m_delta_8U.copyTo(m_temp0_8U); cv::threshold(m_temp0_8U, m_floodFill_8U, m_threshold, 255, cv::THRESH_BINARY); // compute distance transform cv::distanceTransform(m_floodFill_8U, m_temp0_32F, cv::DIST_L2, cv::DIST_MASK_PRECISE); m_temp0_32F.convertTo(m_temp0_64F, CV_64F); m_temp0_64F.convertTo(m_distance_8U, CV_8U); // find max of distance transform (center of the hand) double max; cv::Point maxDistance = cv::Point(); cv::minMaxLoc(m_temp0_64F, 0, &max, 0, &maxDistance); // apply kalman filtering on the center and radius of the hand trackCenter(maxDistance, max); // apply a circular mask around the hand center m_temp0_8U = cv::Scalar(0); cv::circle(m_temp0_8U, maxDistance, max*3.f, cv::Scalar(255), -1); cv::circle(m_temp0_8U, maxDistance, max*1.75f, cv::Scalar(0), -1); m_temp0_64F.copyTo(m_temp1_64F, m_temp0_8U); m_temp1_64F.convertTo(m_distanceMasked_8U, CV_8U); // convert to polar coordinates (origin = center of the hand) and find distance transform intensities for each theta on the polar coordinates space const double* index; m_thetaVector.fill(0); int theta; for(int i = 0; i < m_temp1_64F.rows; i++) { index = m_temp1_64F.ptr<double>(i); for(int j = 0; j < m_temp1_64F.cols; j++) { if (index[j] > 5) { theta = std::floor(std::atan2((double)j - maxDistance.x, maxDistance.y - (double)i)*180/3.14f) + 180; if (theta < 300 && theta > 60) m_thetaVector[theta] = m_thetaVector.at(theta) + index[j]; } } } // smooth the theta densities vector (convolution with a gaussian kernel) int len = m_convKernel.size(); for(int i = len-1; i < 360; i++) { m_thetaConv[i] = 0; for(int j = 0; j < len; j++) m_thetaConv[i] += m_thetaVector.at(i - j) * m_convKernel.at(j); } // find peaks of the theta vector (fingers) int k = 0; m_peaks.fill(0); for(int i = 2; i < 358; i++) { if(m_thetaConv.at(i) > m_thetaConv.at(i-1) && m_thetaConv.at(i) > m_thetaConv.at(i-2) && m_thetaConv.at(i) > m_thetaConv.at(i+1) && m_thetaConv.at(i) > m_thetaConv.at(i+2) && m_thetaConv.at(i) > 0.15) m_peaks[k++] = i; if(k >= 5) break; } // create splitscreen output cv::Size sz; sz.height = CAM_HEIGHT/2; sz.width = CAM_WIDTH/2; cv::Mat topLeft(m_splitScreen_8U, cv::Rect(0, 0, CAM_WIDTH/2, CAM_HEIGHT/2)); // copy constructor cv::Mat topRight(m_splitScreen_8U, cv::Rect(CAM_WIDTH/2, 0, CAM_WIDTH/2, CAM_HEIGHT/2)); cv::Mat bottomLeft(m_splitScreen_8U, cv::Rect(0, CAM_HEIGHT/2, CAM_WIDTH/2, CAM_HEIGHT/2)); cv::Mat bottomRigth(m_splitScreen_8U, cv::Rect(CAM_WIDTH/2, CAM_HEIGHT/2, CAM_WIDTH/2, CAM_HEIGHT/2)); cv::resize(m_oneChannel, topLeft, sz); cv::resize(m_delta_8U, topRight, sz); cv::resize(m_floodFill_8U, bottomLeft, sz); cv::resize(m_distance_8U * 3, bottomRigth, sz); // output selector if(m_output == 0) m_temp1_8U = m_deltaH_8U; else if(m_output == 1) m_temp1_8U = m_deltaS_8U; else if(m_output == 2) m_temp1_8U = m_delta_8U; else if(m_output == 3) m_temp1_8U = m_floodFill_8U; else if(m_output == 4) m_temp1_8U = m_distance_8U * 2; else if(m_output == 5) m_temp1_8U = m_distanceMasked_8U * 2; else if(m_output == 6) m_temp1_8U = m_splitScreen_8U; else m_temp1_8U = m_oneChannel; // blend processed frame with original if(m_output != 6) cv::addWeighted(m_oneChannel, 1-m_blend, m_temp1_8U, m_blend, 0.0, m_blended); else m_blended = m_temp1_8U; // load MAT on a QByteArray to be sent to the UI thread QByteArray array = QByteArray((char*)m_blended.data, CAM_WIDTH*CAM_HEIGHT); emit imageReady(array); if(m_output != 6) // if splitscreen is not selected { emit sendCenterPosition(maxDistance.x, maxDistance.y, max); emit sendFingers(m_peaks); } else //when in splitscreen hand tracker graphics are not shown { emit sendCenterPosition(0, 0, 0); } emit sendVector(THETA_VECTOR, m_thetaConv); } void cvProcessFrame::getSamplePosition(const int &_x, const int &_y) { // show on the console the H S V value of the clicked pixel float a = (float)(m_channelSplit[0].at<uchar>(_y, _x)); float b = (float)(m_channelSplit[1].at<uchar>(_y, _x)); float c = (float)(m_channelSplit[2].at<uchar>(_y, _x)); qDebug() << a << "" << b << "" << c; } void cvProcessFrame::trackCenter(cv::Point& _point, double& _radius) { m_trackerMeasurement.at<float>(0, 0) = (float)_point.x; m_trackerMeasurement.at<float>(1, 0) = (float)_point.y; m_trackerMeasurement.at<float>(2, 0) = (float)_radius; double precTick = m_trackerTicks; m_trackerTicks = (double) cv::getTickCount(); double dT = (m_trackerTicks - precTick) / cv::getTickFrequency(); //seconds m_tracker->transitionMatrix.at<float>(0, 2) = dT; m_tracker->transitionMatrix.at<float>(1, 3) = dT; m_trackerPrediction = m_tracker->predict(); cv::Mat estimate = m_tracker->correct(m_trackerMeasurement); m_trackerMeasurement.at<float>(0, 0) = estimate.at<float>(0, 0); m_trackerMeasurement.at<float>(1, 0) = estimate.at<float>(1, 0); m_trackerMeasurement.at<float>(2, 0) = estimate.at<float>(4, 0); _point.x = (int)m_trackerPrediction.at<float>(0, 0); _point.y = (int)m_trackerPrediction.at<float>(1, 0); _radius = (double)m_trackerPrediction.at<float>(4, 0); } void cvProcessFrame::initTracker(double _noiseCov) { m_trackerTicks = 0; m_trackerMeasurement.create(3, 1, CV_32F); m_trackerPrediction.create(5, 1, CV_32F); m_tracker = new cv::KalmanFilter(5, 3, 0); cv::setIdentity(m_tracker->transitionMatrix); m_tracker->statePre.at<float>(0) = (float)CAM_WIDTH/2.f; m_tracker->statePre.at<float>(1) = (float)CAM_HEIGHT/2.f; m_tracker->statePre.at<float>(2) = 0.f; m_tracker->statePre.at<float>(3) = 0.f; m_tracker->statePre.at<float>(4) = 100.f; cv::setIdentity(m_tracker->measurementMatrix); m_tracker->measurementMatrix = cv::Mat::zeros(3, 5, CV_32F); m_tracker->measurementMatrix.at<float>(0, 0) = 1.0f; m_tracker->measurementMatrix.at<float>(1, 1) = 1.0f; m_tracker->measurementMatrix.at<float>(2, 4) = 1.0f; m_tracker->processNoiseCov.at<float>(0, 0) = 0.1f; m_tracker->processNoiseCov.at<float>(1, 1) = 0.1f; m_tracker->processNoiseCov.at<float>(2, 2) = 2.f; m_tracker->processNoiseCov.at<float>(3, 3) = 2.f; m_tracker->processNoiseCov.at<float>(4, 4) = 0.1f; cv::setIdentity(m_tracker->measurementNoiseCov, cv::Scalar::all(_noiseCov)); }
35.233766
149
0.705308
[ "shape", "vector", "transform" ]
084abba7a985fae6258190dcb32b27aaf0383741
3,645
cpp
C++
src/external_plugins/term_input_handler/input_handler_key.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
12
2017-11-23T16:02:41.000Z
2019-12-29T08:36:36.000Z
src/external_plugins/term_input_handler/input_handler_key.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
9
2017-12-04T15:55:51.000Z
2019-11-01T13:08:21.000Z
src/external_plugins/term_input_handler/input_handler_key.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
5
2018-09-02T07:35:13.000Z
2019-12-29T08:36:37.000Z
#include <iostream> #ifndef _WIN32 #include <unistd.h> #endif #include <vector> #include <string.h> #include "key_code_map.h" #include "plugin_manager.h" #include "plugin.h" #include "term_network.h" #include "term_data_handler.h" #include "term_context.h" #include "term_window.h" #include "input.h" #include "plugin_base.h" #include "app_config_impl.h" #include <locale> #include <codecvt> #include <functional> #include "base64.h" #include "input_handler_plugin.h" #include "network_utils.h" static std::wstring_convert<std::codecvt_utf8<wchar_t #if defined(_WIN32) && defined(__GNUC__) , 0x10ffff, std::little_endian #endif >, wchar_t> wcharconv; bool DefaultInputHandler::ProcessKey(InputHandler::KeyCodeEnum key, InputHandler::ModifierEnum mods, bool down) { (void)down; TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext()); if (!context) return false; TermNetworkPtr network = context->GetTermNetwork(); TermWindowPtr window = context->GetTermWindow(); std::vector<unsigned char> data; bool paste_data = (mods == InputHandler::MOD_SHIFT_V && key == InputHandler::KEY_INSERT) #ifdef __APPLE__ || (mods == InputHandler::MOD_SUPER_V && key == InputHandler::KEY_V) #endif ; if (paste_data) { //paste from clipboard auto clipboard_data = window->GetSelectionData(); if (clipboard_data.size() > 0) { std::string decoded {}; if (Base64::Decode(clipboard_data, &decoded)) { std::copy(decoded.begin(), decoded.end(), std::back_inserter(data)); send_data(network, data); } } return true; } if (mods & InputHandler::MOD_ALT_V){ data.push_back('\x1B'); } if (key != InputHandler::KEY_UNKNOWN && (mods & InputHandler::MOD_CONTROL_V)) { if (key >= 'a' && key <= 'z') data.push_back((char)(key - 'a' + 1)); if (key >= 'A' && key <= 'Z') data.push_back((char)(key - 'A' + 1)); else if (key>= '[' && key <= ']') data.push_back((char)(key - '[' + 27)); else if (key == '6') data.push_back((char)('^' - '[' + 27)); else if (key == '-') data.push_back((char)('_' - '[' + 27)); } if (mods == 0) { const char * c = get_mapped_key_code(key); if (c) { for(size_t i=0;i<strlen(c);i++) data.push_back(c[i]); } } //add char when there only ALT pressed if (data.size() == 1 && data[0] == '\x1B' && key >= 0 && key <0x80) { if (!(mods & InputHandler::MOD_SHIFT_V) && (key >= 'A' && key <= 'Z')) { key = (InputHandler::KeyCodeEnum)(key - 'A' + 'a'); } data.push_back((char)key); } if (data.size() == 0) return false; send_data(network, data); return true; } bool DefaultInputHandler::ProcessCharInput(int32_t codepoint, InputHandler::ModifierEnum modifier) { (void)codepoint; (void)modifier; TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext()); if (!context) return false; TermNetworkPtr network = context->GetTermNetwork(); std::vector<unsigned char> data; std::string bytes = wcharconv.to_bytes((wchar_t)codepoint); for(std::string::size_type i=0; i < bytes.length(); i++) { data.push_back(bytes[i]); } send_data(network, data); return true; }
27
113
0.571742
[ "vector" ]
084fb8b65d97a17fd73a0f1f21857c1cd23fa283
4,029
cc
C++
code/render/renderutil/drawfullscreenquad.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
377
2018-10-24T08:34:21.000Z
2022-03-31T23:37:49.000Z
code/render/renderutil/drawfullscreenquad.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
11
2020-01-22T13:34:46.000Z
2022-03-07T10:07:34.000Z
code/render/renderutil/drawfullscreenquad.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
23
2019-07-13T16:28:32.000Z
2022-03-20T09:00:59.000Z
//------------------------------------------------------------------------------ // drawfullscreenquad.cc // (C) 2009 Radon Labs GmbH // (C) 2013-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "renderutil/drawfullscreenquad.h" #include "coregraphics/graphicsdevice.h" namespace RenderUtil { using namespace Util; using namespace CoreGraphics; using namespace Resources; CoreGraphics::BufferId DrawFullScreenQuad::vertexBuffer = CoreGraphics::InvalidBufferId; CoreGraphics::VertexLayoutId DrawFullScreenQuad::vertexLayout = CoreGraphics::InvalidVertexLayoutId; CoreGraphics::PrimitiveGroup DrawFullScreenQuad::primGroup; bool DrawFullScreenQuad::isValid = false; //------------------------------------------------------------------------------ /** */ void DrawFullScreenQuad::Setup() { n_assert(!DrawFullScreenQuad::IsValid()); DrawFullScreenQuad::isValid = true; if (DrawFullScreenQuad::vertexBuffer == CoreGraphics::InvalidBufferId) { // setup vertex components Array<VertexComponent> vertexComponents; vertexComponents.Append(VertexComponent(VertexComponent::Position, 0, VertexComponent::Float3)); vertexComponents.Append(VertexComponent(VertexComponent::TexCoord1, 0, VertexComponent::Float2)); // create corners and uvs float left = -1.0f; float right = +3.0f; float top = +3.0f; float bottom = -1.0f; float u0 = 0.0f; float u1 = 2.0f; float v0 = 0.0f; float v1 = 2.0f; // setup a vertex buffer with 2 triangles float v[3][5]; #if (__VULKAN__ || __DX12__) // first triangle v[0][0] = left; v[0][1] = bottom; v[0][2] = 0.0f; v[0][3] = u0; v[0][4] = v0; v[1][0] = left; v[1][1] = top; v[1][2] = 0.0f; v[1][3] = u0; v[1][4] = v1; v[2][0] = right; v[2][1] = bottom; v[2][2] = 0.0f; v[2][3] = u1; v[2][4] = v0; #else // first triangle v[0][0] = left; v[0][1] = top; v[0][2] = 0.0f; v[0][3] = u0; v[0][4] = v0; v[1][0] = left; v[1][1] = bottom; v[1][2] = 0.0f; v[1][3] = u0; v[1][4] = v1; v[2][0] = right; v[2][1] = top; v[2][2] = 0.0f; v[2][3] = u1; v[2][4] = v0; #endif DrawFullScreenQuad::vertexLayout = CoreGraphics::CreateVertexLayout({ vertexComponents }); // load vertex buffer BufferCreateInfo info; info.name = "FullScreen Quad VBO"_atm; info.size = 3; info.elementSize = CoreGraphics::VertexLayoutGetSize(DrawFullScreenQuad::vertexLayout); info.mode = CoreGraphics::DeviceLocal; info.usageFlags = CoreGraphics::VertexBuffer; info.data = v; info.dataSize = sizeof(v); DrawFullScreenQuad::vertexBuffer = CreateBuffer(info); // setup a primitive group object DrawFullScreenQuad::primGroup.SetBaseVertex(0); DrawFullScreenQuad::primGroup.SetNumVertices(3); DrawFullScreenQuad::primGroup.SetBaseIndex(0); DrawFullScreenQuad::primGroup.SetNumIndices(0); } } //------------------------------------------------------------------------------ /** */ void DrawFullScreenQuad::Discard() { n_assert(DrawFullScreenQuad::IsValid()); DrawFullScreenQuad::isValid = false; DestroyBuffer(DrawFullScreenQuad::vertexBuffer); DestroyVertexLayout(DrawFullScreenQuad::vertexLayout); } //------------------------------------------------------------------------------ /** */ void DrawFullScreenQuad::ApplyMesh() { // setup pipeline CoreGraphics::SetVertexLayout(DrawFullScreenQuad::vertexLayout); CoreGraphics::SetPrimitiveTopology(PrimitiveTopology::TriangleList); CoreGraphics::SetGraphicsPipeline(); // setup input data CoreGraphics::SetStreamVertexBuffer(0, DrawFullScreenQuad::vertexBuffer, 0); CoreGraphics::SetPrimitiveGroup(DrawFullScreenQuad::primGroup); } } // namespace RenderUtil
35.654867
105
0.586001
[ "render", "object" ]
085068c241ab496f912eafd385071686044430f0
3,548
cpp
C++
engine/src/engine/opengl/mesh.cpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
engine/src/engine/opengl/mesh.cpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
engine/src/engine/opengl/mesh.cpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
// header #include "engine/opengl/mesh.hpp" // other library headers #include <gl/glew.h> #include <glm/glm.hpp> // c++ libs #include <iostream> namespace engine { // clang-format off static float vertexPlane[40] = { -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f,-1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }; static float vertexCube[] = { -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // bottom 1.0f,-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f,-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f,1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // left -1.0f, 1.0f,-1.0f,1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f,1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f,-1.0f,1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f,1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // right 1.0f, 1.0f,-1.0f,1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f,1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f,1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // front 1.0f, 1.0f, -1.0f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 1.0f,1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // back 1.0f, -1.0f, -1.0f,1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f,1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f,1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, }; static unsigned short indexPlane[6] { 0+0, 0+2, 0+1, 0+0, 0+1, 0+3 }; // clang-format on Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices) { this->verts = vertices; this->indices = indices; setup_mesh(); } void Mesh::setup_mesh() { // initialize object IDs glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glGenBuffers(1, &ebo); glBindVertexArray(vao); // load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(Vertex), &verts[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // vertex positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(0); // vertex normals glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); glEnableVertexAttribArray(1); // vertex texture coords glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, tex_coords)); glEnableVertexAttribArray(2); // unbind glBindVertexArray(0); } void Mesh::draw(Shader& shader) { // bind vao glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); } } // namespace engine
31.678571
108
0.585682
[ "mesh", "object", "vector" ]
08598a8a13fc6a5e5f85828ed1ed529f95afd9fb
5,199
cpp
C++
src/converters/jsonconverter.cpp
Amf1k/CognitiveMapCreator
8e812d664a0a5b508b58bb00ef323a0c5f31a4ad
[ "MIT" ]
null
null
null
src/converters/jsonconverter.cpp
Amf1k/CognitiveMapCreator
8e812d664a0a5b508b58bb00ef323a0c5f31a4ad
[ "MIT" ]
null
null
null
src/converters/jsonconverter.cpp
Amf1k/CognitiveMapCreator
8e812d664a0a5b508b58bb00ef323a0c5f31a4ad
[ "MIT" ]
null
null
null
#include "jsonconverter.hpp" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QUuid> #include "domain/node.hpp" #include "domain/relationship.hpp" cognitive::converters::JsonConverter::JsonConverter(QObject* parent) : IConverter(parent) {} QByteArray cognitive::converters::JsonConverter::convertTo( QList<QSharedPointer<cognitive::domain::Node>> nodes, QList<QSharedPointer<cognitive::domain::Relationship>> relationships) { QJsonArray nodesArray; for (auto&& node : nodes) { nodesArray.append(QJsonObject{{"id", node->id()}, {"text", node->text()}, {"x", node->x()}, {"y", node->y()}, {"height", node->height()}, {"width", node->width()}}); } QJsonArray relationshipsArray; for (auto&& relationship : relationships) { relationshipsArray.append(QJsonObject{ {"id", relationship->id()}, {"from", relationship->from()->id()}, {"relativeFromPointX", relationship->relativeFromPoint().x()}, {"relativeFromPointY", relationship->relativeFromPoint().y()}, {"to", relationship->to()->id()}, {"relativeToPointX", relationship->relativeToPoint().x()}, {"relativeToPointY", relationship->relativeToPoint().y()}, {"weight", relationship->weight()}}); } return QJsonDocument{ QJsonObject{{"nodes", nodesArray}, {"relationships", relationshipsArray}}} .toJson(QJsonDocument::Indented); } QPair<QList<QSharedPointer<cognitive::domain::Node>>, QList<QSharedPointer<cognitive::domain::Relationship>>> cognitive::converters::JsonConverter::convertFrom(const QByteArray& data) { QHash<QUuid, QSharedPointer<cognitive::domain::Node>> resultNodes{}; QList<QSharedPointer<cognitive::domain::Relationship>> resultRelationships{}; QJsonParseError error; auto doc = QJsonDocument::fromJson(data, &error); if (error.error != QJsonParseError::NoError) { qWarning() << "failed parse json with error" << error.errorString(); return qMakePair(resultNodes.values(), resultRelationships); } if (!doc.isObject() || doc.isEmpty() || doc.isNull()) { qWarning() << "failed parse json - json is not object or empty"; return qMakePair(resultNodes.values(), resultRelationships); } auto obj = doc.object(); if (!(obj.contains("nodes") && obj["nodes"].isArray()) || !(obj.contains("relationships") || obj["relationships"].isArray())) { qWarning() << "failed parse json - json is broken nodes or relationships" << obj; return qMakePair(resultNodes.values(), resultRelationships); } auto jsonNodes = obj["nodes"].toArray(); for (auto&& jsonNode : jsonNodes) { auto objNode = jsonNode.toObject(); if (!objNode.contains("id") || !objNode.contains("text") || !objNode.contains("x") || !objNode.contains("y") || !objNode.contains("height") || !objNode.contains("width")) { qWarning() << "failed parse json node - invalid object" << objNode; continue; } auto id = QUuid(objNode["id"].toString()); auto pNode = QSharedPointer<domain::Node>::create( id, objNode["text"].toString(), objNode["x"].toDouble(0.0), objNode["y"].toDouble(0.0), objNode["width"].toDouble(0.0), objNode["height"].toDouble(0.0)); resultNodes.insert(id, pNode); } auto jsonRelationships = obj["relationships"].toArray(); for (auto&& jsonRelationship : jsonRelationships) { auto objRelationship = jsonRelationship.toObject(); if (!objRelationship.contains("id") || !objRelationship.contains("from") || !objRelationship.contains("relativeFromPointX") || !objRelationship.contains("relativeFromPointY") || !objRelationship.contains("to") || !objRelationship.contains("relativeToPointX") || !objRelationship.contains("relativeToPointY") || !objRelationship.contains("weight")) { qWarning() << "failed parse json relationship - invalid object" << objRelationship; continue; } auto id = QUuid(objRelationship["id"].toString()); auto fromId = QUuid(objRelationship["from"].toString()); auto toId = QUuid(objRelationship["to"].toString()); if (!resultNodes.contains(fromId) || !resultNodes.contains(toId)) { qWarning() << "failed parse json relationship - not found from node or to node" << objRelationship; continue; } auto from = resultNodes.value(fromId); auto to = resultNodes.value(toId); auto pRelationship = QSharedPointer<domain::Relationship>::create( id, from, QPointF(objRelationship["relativeFromPointX"].toDouble(0.0), objRelationship["relativeFromPointY"].toDouble(0.0)), to, QPointF(objRelationship["relativeToPointX"].toDouble(0.0), objRelationship["relativeToPointY"].toDouble(0.0)), objRelationship["weight"].toInt()); resultRelationships.append(pRelationship); } return qMakePair(resultNodes.values(), resultRelationships); }
40.302326
80
0.639738
[ "object" ]
086391b65b49ae0f0c1774efe536d09320cfde36
6,149
cpp
C++
src/Result.cpp
shift-left-test/sentinel
64f401ead35ad564badedfd0956414a6d148077e
[ "MIT-0", "MIT" ]
null
null
null
src/Result.cpp
shift-left-test/sentinel
64f401ead35ad564badedfd0956414a6d148077e
[ "MIT-0", "MIT" ]
null
null
null
src/Result.cpp
shift-left-test/sentinel
64f401ead35ad564badedfd0956414a6d148077e
[ "MIT-0", "MIT" ]
null
null
null
/* * Copyright (c) 2020 LG Electronics Inc. * SPDX-License-Identifier: MIT */ #include <fmt/core.h> #include <tinyxml2/tinyxml2.h> #include <experimental/filesystem> #include <algorithm> #include <vector> #include <string> #include "sentinel/Logger.hpp" #include "sentinel/Result.hpp" namespace fs = std::experimental::filesystem; namespace sentinel { Result::Result(const std::string& path) : mLogger(Logger::getLogger("Result")) { std::vector<std::string> nonGtestFiles; std::string logFormat = "This file doesn't follow googletest result format: {}"; // gtest result format for (const auto& dirent : fs::recursive_directory_iterator(path)) { const auto& curPath = dirent.path(); std::string curExt = curPath.extension().string(); std::transform(curExt.begin(), curExt.end(), curExt.begin(), [](unsigned char c) { return std::tolower(c); }); if (fs::is_regular_file(curPath) && curExt == ".xml") { const auto& xmlPath = curPath.string(); nonGtestFiles.push_back(xmlPath); std::vector<std::string> tmpPassedTC; std::vector<std::string> tmpFailedTC; tinyxml2::XMLDocument doc; auto errcode = doc.LoadFile(xmlPath.c_str()); if (errcode != 0) { mLogger->debug(fmt::format("{}: {}", tinyxml2::XMLDocument::ErrorIDToName(errcode), xmlPath)); continue; } tinyxml2::XMLElement *pRoot = doc.FirstChildElement("testsuites"); if (pRoot == nullptr) { mLogger->debug(fmt::format(logFormat, xmlPath)); continue; } tinyxml2::XMLElement *p = pRoot->FirstChildElement("testsuite"); if (p == nullptr) { mLogger->debug(fmt::format(logFormat, xmlPath)); continue; } bool allParsed = true; for ( ; p != nullptr && allParsed ; p = p->NextSiblingElement("testsuite")) { tinyxml2::XMLElement *q = p->FirstChildElement("testcase"); if (q == nullptr) { mLogger->debug(fmt::format(logFormat, xmlPath)); allParsed = false; break; } for ( ; q != nullptr ; q = q->NextSiblingElement("testcase")) { const char* pStatus = q->Attribute("status"); if (pStatus == nullptr) { mLogger->debug(fmt::format(logFormat, xmlPath)); allParsed = false; break; } if (std::string(pStatus) == std::string("run")) { const char* pClassName = q->Attribute("classname"); const char* pName = q->Attribute("name"); if (pClassName == nullptr || pName == nullptr) { mLogger->debug(fmt::format(logFormat, xmlPath)); allParsed = false; break; } auto savedName = fmt::format("{0}.{1}", pClassName, pName); if (q->FirstChildElement("failure") == nullptr) { tmpPassedTC.push_back(savedName); } else { tmpFailedTC.push_back(savedName); } } } } if (allParsed) { mPassedTC.insert( mPassedTC.end(), tmpPassedTC.begin(), tmpPassedTC.end()); mFailedTC.insert( mFailedTC.end(), tmpFailedTC.begin(), tmpFailedTC.end()); } else { nonGtestFiles.pop_back(); } } } logFormat = "This file doesn't follow QtTest result format: {}"; // QtTest result format for (const std::string& xmlPath : nonGtestFiles) { std::vector<std::string> tmpPassedTC; std::vector<std::string> tmpFailedTC; tinyxml2::XMLDocument doc; doc.LoadFile(xmlPath.c_str()); tinyxml2::XMLElement *p = doc.FirstChildElement("testsuite"); if (p == nullptr) { mLogger->debug(fmt::format(logFormat + "1", xmlPath)); continue; } tinyxml2::XMLElement *q = p->FirstChildElement("testcase"); if (q == nullptr) { mLogger->debug(fmt::format(logFormat + "1", xmlPath)); continue; } bool allParsed = true; for ( ; q != nullptr ; q = q->NextSiblingElement("testcase")) { const char* pResult = q->Attribute("result"); if (pResult == nullptr) { mLogger->debug(fmt::format(logFormat + "2", xmlPath)); allParsed = false; break; } const char* pClassName = p->Attribute("name"); const char* pName = q->Attribute("name"); if (pClassName == nullptr || pName == nullptr) { mLogger->debug(fmt::format(logFormat + "3", xmlPath)); allParsed = false; break; } auto savedName = fmt::format("{0}.{1}", pClassName, pName); if (std::string(pResult) == std::string("pass")) { tmpPassedTC.push_back(savedName); } else if (std::string(pResult) == std::string("fail")) { tmpFailedTC.push_back(savedName); } } if (allParsed) { mPassedTC.insert(mPassedTC.end(), tmpPassedTC.begin(), tmpPassedTC.end()); mFailedTC.insert( mFailedTC.end(), tmpFailedTC.begin(), tmpFailedTC.end()); } } if (!mPassedTC.empty()) { std::sort(mPassedTC.begin(), mPassedTC.end()); std::sort(mFailedTC.begin(), mFailedTC.end()); } } bool Result::checkPassedTCEmpty() { return mPassedTC.empty(); } MutationState Result::compare(const Result& original, const Result& mutated, std::string* killingTest, std::string* errorTest) { killingTest->clear(); errorTest->clear(); for (const std::string &tc : original.mPassedTC) { if (std::find(mutated.mPassedTC.begin(), mutated.mPassedTC.end(), tc) == mutated.mPassedTC.end()) { if (std::find(mutated.mFailedTC.begin(), mutated.mFailedTC.end(), tc) == mutated.mFailedTC.end()) { if (!errorTest->empty()) { errorTest->append(", "); } errorTest->append(tc); } else { if (!killingTest->empty()) { killingTest->append(", "); } killingTest->append(tc); } } } if (!errorTest->empty()) { return MutationState::RUNTIME_ERROR; } if (!killingTest->empty()) { return MutationState::KILLED; } return MutationState::SURVIVED; } } // namespace sentinel
31.372449
80
0.585786
[ "vector", "transform" ]
0864fc6d2702731b33804cab836518f421113ef2
16,638
cc
C++
caffe2/opt/bound_shape_inferencer.cc
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
1
2019-07-23T11:20:58.000Z
2019-07-23T11:20:58.000Z
caffe2/opt/bound_shape_inferencer.cc
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
caffe2/opt/bound_shape_inferencer.cc
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
#include "bound_shape_inferencer.h" #include "caffe2/core/operator_schema.h" #include "caffe2/core/tensor_impl.h" #include "caffe2/utils/proto_utils.h" #include "caffe2/utils/string_utils.h" namespace caffe2 { namespace { std::vector<int64_t> ConvertToVec( const ::google::protobuf::RepeatedField<::google::protobuf::int64>& in) { std::vector<int64_t> out; out.reserve(in.size()); for (const auto d : in) { out.push_back(d); } return out; } int64_t SizeFromDim(const TensorShape& shape, int axis) { int64_t r = 1; for (int i = axis; i < shape.dims_size(); ++i) { r *= shape.dims(i); } return r; } int64_t SizeToDim(const TensorShape& shape, int axis) { CAFFE_ENFORCE_LE(axis, shape.dims_size()); int64_t r = 1; for (int i = 0; i < axis; ++i) { r *= shape.dims(i); } return r; } void EnsureShapeNames(std::unordered_map<std::string, ShapeInfo>* info) { for (auto& kv : *info) { kv.second.shape.set_name(kv.first); } } } // namespace void BoundShapeInferencer::InferBoundShapeAndType( const NetDef& net, const std::unordered_map<std::string, ShapeInfo>& info) { const static std::unordered_set<std::string> unsupported{"Tile"}; shape_info_ = info; for (const auto& op : net.op()) { VLOG(1) << op.type(); if (unsupported.count(op.type())) { continue; } if (op.type() == "SparseLengthsSum" || op.type() == "SparseLengthsSumFused8BitRowwise" || op.type() == "SparseLengthsWeightedSum" || op.type() == "SparseLengthsWeightedSumFused8BitRowwise") { InferSparseLengthsSum(op); } else if (op.type() == "FC" || op.type() == "FCTransposed") { InferFC(op); } else if (op.type() == "Concat") { InferConcat(op); } else if (op.type() == "Reshape") { InferReshape(op); } else if (op.type() == "LengthsRangeFill") { InferLengthsRangeFill(op); } else if ( (caffe2::StartsWith(op.type(), "GivenTensor") && caffe2::EndsWith(op.type(), "Fill")) || op.type() == "ConstantFill" || op.type() == "Int8GivenTensorFill" || op.type() == "Int8GivenIntTensorFill") { InferGivenTensorFill(op); } else if (op.type() == "Shape") { InferShape(op); } else { InferCommonOp(op); } } // Doing a reverse pass to infer the input shapes if applicable for (int i = net.op_size() - 1; i >= 0; --i) { const auto& op = net.op(i); if (op.type() == "Concat") { InferConcatInputs(op); } } // Make sure shape has name EnsureShapeNames(&shape_info_); } TensorShape& BoundShapeInferencer::CheckAndSetTensorShapeAndType( const std::string& name, ShapeInfo::DimType t, std::vector<int64_t> bound_dims, TensorProto::DataType type, bool is_quantized) { auto rt = shape_info_.emplace(name, ShapeInfo()); ShapeInfo& shape_info = rt.first->second; TensorShape& shape = shape_info.shape; if (is_quantized) { shape_info.is_quantized = true; shape_info.q_info.scale = 1; shape_info.q_info.offset = 0; } if (!rt.second) { // Check shape consistency CAFFE_ENFORCE_EQ(shape.dims_size(), bound_dims.size()); // For shapes that was provided as a hint at the input of the net, fix the // batch size first. if (shape.dims_size() > 0 && shape_info.dim_type == ShapeInfo::DimType::UNKNOWN && t > ShapeInfo::DimType::CONSTANT) { shape_info.dim_type = t; shape.set_dims(0, bound_dims.front()); } for (int i = 0; i < shape.dims_size(); ++i) { CAFFE_ENFORCE_EQ( shape.dims(i), bound_dims[i], "Shape inconsistency found in tensor ", name, " on dim ", i, " (", shape.dims(i), " vs ", bound_dims[i], ")"); } return shape; } shape_info.dim_type = t; shape.mutable_dims()->Clear(); for (const auto d : bound_dims) { shape.add_dims(d); } shape.set_data_type(type); return shape; } std::vector<TensorShape> InferOutput( const OperatorDef& op, const std::vector<TensorShape>& input_shapes) { const OpSchema* schema = OpSchemaRegistry::Schema(op.type()); CAFFE_ENFORCE(schema); return schema->InferTensor(op, input_shapes); } void BoundShapeInferencer::InferGivenTensorFill(const OperatorDef& op) { CAFFE_ENFORCE_EQ(op.output_size(), 1, op.type(), " must have 1 output"); InferCommonOp(op); auto it = shape_info_.find(op.output(0)); if (it != shape_info_.end()) { it->second.dim_type = ShapeInfo::DimType::CONSTANT; } } void BoundShapeInferencer::InferLengthsRangeFill(const OperatorDef& op) { CAFFE_ENFORCE_EQ(op.input_size(), 1, "LengthsRangeFill must have 1 input"); CAFFE_ENFORCE_EQ(op.output_size(), 1, "LengthsRangeFill must have 1 output"); // Both input and ouptut of LengthsRangeFill is int32: // https://fburl.com/fhwb5666 CheckAndSetTensorShapeAndType( op.input(0), ShapeInfo::DimType::BATCH, {spec_.max_batch_size}, TensorProto_DataType_INT32, false); CheckAndSetTensorShapeAndType( op.output(0), ShapeInfo::DimType::SEQ, {spec_.max_seq_size}, TensorProto_DataType_INT32, false); current_dim_type_ = ShapeInfo::DimType::SEQ; } void BoundShapeInferencer::InferSparseLengthsSum(const OperatorDef& op) { CAFFE_ENFORCE_GE( op.input_size(), 3, op.type(), " must have at least 3 inputs"); const auto it = shape_info_.find(op.input(0)); CAFFE_ENFORCE( it != shape_info_.end(), "Shape of DATA input of SparseLengthsSum ", op.input(0), " needs to be presented"); CAFFE_ENFORCE_EQ( it->second.shape.dims().size(), 2, "DATA input ", op.input(0), "needs to be 2D"); int weight = (op.type() == "SparseLengthsWeightedSum" || op.type() == "SparseLengthsWeightedSumFused8BitRowwise") ? 1 : 0; if (weight) { CAFFE_ENFORCE_EQ( op.input_size(), 4, "SparseLengthsWeightedSum must have 4 inputs"); CheckAndSetTensorShapeAndType( op.input(weight), ShapeInfo::DimType::SEQ, {spec_.max_seq_size}, TensorProto_DataType_FLOAT, false); } // Bound inputs CheckAndSetTensorShapeAndType( op.input(1 + weight), ShapeInfo::DimType::SEQ, {spec_.max_seq_size}, TensorProto_DataType_INT64, false); CheckAndSetTensorShapeAndType( op.input(2 + weight), ShapeInfo::DimType::BATCH, {spec_.max_batch_size}, TensorProto_DataType_INT32, false); // Infer output CAFFE_ENFORCE_EQ(it->second.shape.dims_size(), 2); current_dim_type_ = ShapeInfo::DimType::BATCH; current_max_batch_size_ = spec_.max_batch_size; auto output_dim1 = it->second.shape.dims(1); // If the op is SparseLengthsSumFused8BitRowwise, we need to extract 4 for // scale and 4 byte for bias (https://fburl.com/t6dp9tsc) if (op.type() == "SparseLengthsSumFused8BitRowwise" || op.type() == "SparseLengthsWeightedSumFused8BitRowwise") { output_dim1 -= 8; } CheckAndSetTensorShapeAndType( op.output(0), ShapeInfo::DimType::BATCH, {spec_.max_batch_size, output_dim1}, TensorProto_DataType_FLOAT, false); } void BoundShapeInferencer::InferShape(const OperatorDef& op) { InferCommonOp(op); // old_shape should be a constant if (op.output_size() > 0 && shape_info_.count(op.output(0))) { shape_info_[op.output(0)].dim_type = ShapeInfo::DimType::CONSTANT; } } void BoundShapeInferencer::InferReshape(const OperatorDef& op) { InferCommonOp(op); // old_shape should be a constant if (op.output_size() > 1 && shape_info_.count(op.output(1))) { shape_info_[op.output(1)].dim_type = ShapeInfo::DimType::CONSTANT; } } void BoundShapeInferencer::InferConcatInputs(const OperatorDef& op) { ArgumentHelper helper(op); const auto add_axis = helper.GetSingleArgument<int32_t>("add_axis", 0); if (add_axis) { return; } else if (op.output_size() == 0 || !shape_info_.count(op.output(0))) { return; } const auto axis = helper.HasArgument("axis") ? helper.GetSingleArgument<int32_t>("axis", -1) : GetDimFromOrderString( helper.GetSingleArgument<string>("order", "NCHW")); const auto& shape_info = shape_info_.at(op.output(0)); int output_channel = shape_info.shape.dims(axis); int missing_shape_infos = 0; int channel_acc = 0; std::string input_to_infer; for (const auto& i : op.input()) { const auto it = shape_info_.find(i); if (it != shape_info_.end()) { const auto& current_input_shape = it->second; if (axis < current_input_shape.shape.dims_size()) { channel_acc += current_input_shape.shape.dims(axis); } else { LOG(INFO) << "Mismatched input dim along axis " << axis << ". We cannot infer missing input shape for Concat"; return; } } else if (missing_shape_infos) { LOG(INFO) << "More than one missing shapes, previous one: " << input_to_infer; // We can only infer one missing input shape info return; } else { ++missing_shape_infos; input_to_infer = i; } } if (missing_shape_infos && !input_to_infer.empty()) { auto input_shape_info = shape_info; input_shape_info.shape.set_dims(axis, output_channel - channel_acc); shape_info_.emplace(input_to_infer, std::move(input_shape_info)); // Infer the shape of the second output of Concat InferCommonOp(op); if (op.output_size() > 1 && shape_info_.count(op.output(1))) { shape_info_[op.output(1)].dim_type = ShapeInfo::DimType::CONSTANT; } } } // For concat net, if some inputs are missing and we have add_axis argument, it // means that all the inputs should be of the same dimension. In this case, we // can infer the shape of the missing inputs void BoundShapeInferencer::InferConcat(const OperatorDef& op) { ArgumentHelper helper(op); auto add_axis = helper.GetSingleArgument<int32_t>("add_axis", 0); if (add_axis) { ShapeInfo* ref_input_shape = nullptr; std::string ref_name; std::unordered_set<std::string> missing_shape_inputs; for (const auto& i : op.input()) { const auto it = shape_info_.find(i); if (it != shape_info_.end()) { const auto& current_input_shape = it->second; if (ref_input_shape) { CAFFE_ENFORCE_EQ( ref_input_shape->shape.dims_size(), current_input_shape.shape.dims_size(), ref_name, " vs ", i); for (int j = 0; j < ref_input_shape->shape.dims_size(); ++j) { CAFFE_ENFORCE_EQ( ref_input_shape->shape.dims(j), current_input_shape.shape.dims(j), "Mismatched size on dim ", j, " between ", ref_name, " and ", i, " (", ref_input_shape->shape.dims(j), " vs ", current_input_shape.shape.dims(j), ")"); } } else { ref_input_shape = &it->second; ref_name = i; } } else { missing_shape_inputs.emplace(i); } } if (ref_input_shape) { current_dim_type_ = ref_input_shape->dim_type; for (const auto& i : missing_shape_inputs) { shape_info_.emplace(i, *ref_input_shape); } } } InferCommonOp(op); // split_info should be a constant if (op.output_size() > 1 && shape_info_.count(op.output(1))) { shape_info_[op.output(1)].dim_type = ShapeInfo::DimType::CONSTANT; } } void BoundShapeInferencer::InferFC(const OperatorDef& op) { CAFFE_ENFORCE_EQ(op.input_size(), 3, "FC has to have 3 inputs"); const auto w_it = shape_info_.find(op.input(1)); CAFFE_ENFORCE( w_it != shape_info_.end(), "Shape of WEIGHT input of FC ", op.input(1), " needs to be presented"); const ShapeInfo& w_shape_info = w_it->second; const auto b_it = shape_info_.find(op.input(2)); CAFFE_ENFORCE( w_it != shape_info_.end(), "Shape of BIAS input of FC ", op.input(2), " needs to be presented"); const ShapeInfo& b_shape_info = b_it->second; auto x_it = shape_info_.find(op.input(0)); if (x_it == shape_info_.end()) { // We don't have a hint at the x input we try to deduce it from weight shape ArgumentHelper helper(op); auto axis = helper.GetSingleArgument<int32_t>("axis", 1); auto axis_w = helper.GetSingleArgument<int32_t>("axis_w", 1); const TensorShape w_shape = w_shape_info.shape; bool transposed = (op.type() == "FC") ? false : true; const int canonical_axis_w = canonical_axis_index_(axis_w, w_shape.dims().size()); const int64_t K = transposed ? SizeToDim(w_shape, canonical_axis_w) : SizeFromDim(w_shape, canonical_axis_w); std::vector<int64_t> dims; for (int i = 0; i < axis - 1; ++i) { dims.push_back(1); } dims.push_back(spec_.max_batch_size); dims.push_back(K); current_dim_type_ = ShapeInfo::DimType::BATCH; current_max_batch_size_ = spec_.max_batch_size; CheckAndSetTensorShapeAndType( op.input(0), ShapeInfo::DimType::BATCH, dims, w_shape.data_type(), false); } else { ShapeInfo& x_shape_info = x_it->second; if (x_shape_info.dim_type != ShapeInfo::DimType::BATCH) { CAFFE_ENFORCE_GE(x_shape_info.shape.dims_size(), 1); x_shape_info.shape.set_dims(0, spec_.max_batch_size); x_shape_info.dim_type = ShapeInfo::DimType::BATCH; } } // Standard shape inference for outputs std::vector<TensorShape> input_shapes{ shape_info_[op.input(0)].shape, w_shape_info.shape, b_shape_info.shape}; std::vector<TensorShape> output_shapes = InferOutput(op, input_shapes); CAFFE_ENFORCE_EQ(output_shapes.size(), 1); CheckAndSetTensorShapeAndType( op.output(0), ShapeInfo::DimType::BATCH, ConvertToVec(output_shapes[0].dims()), output_shapes[0].data_type(), false); } void BoundShapeInferencer::InferCommonOp(const OperatorDef& op) { // First, we need to check that all the input shape/types are already // presented try { std::vector<TensorShape> input_shapes; for (const auto& input : op.input()) { const auto it = shape_info_.find(input); if (it == shape_info_.end()) { LOG(WARNING) << "Cannot find shape info for " << input << ". Skipping " << op.type(); return; } input_shapes.emplace_back(it->second.shape); } const OpSchema* schema = OpSchemaRegistry::Schema(op.type()); CAFFE_ENFORCE(schema); std::vector<TensorShape> output_shapes; output_shapes = schema->InferTensor(op, input_shapes); int i = 0; bool is_quantized = !(op.type().compare(0, 4, "Int8")) && (op.type() != "Int8Dequantize"); TensorProto::DataType infered_data_type = TensorProto::UNDEFINED; if (is_quantized) { const static std::map<std::string, int> type_info_from_input = { {"Int8Quantize", -1}, // Force this op's output to be uint8 {"Int8ConvRelu", 1}, {"Int8MaxPool", 0}, {"Int8AveragePool", 0}, {"Int8FC", 1}, {"Int8Conv", 1}, {"Int8SumRelu", 0}}; CAFFE_ENFORCE( type_info_from_input.find(op.type()) != type_info_from_input.end(), "Undefined quantized output data type, add it into type_info_from_input"); int target = type_info_from_input.find(op.type())->second; if (target == -1) { infered_data_type = TensorProto::UINT8; } else { CAFFE_ENFORCE(target < input_shapes.size()); infered_data_type = input_shapes[target].data_type(); } } else if (op.type() == "Int8Dequantize") { infered_data_type = TensorProto::FLOAT; } for (const auto& shape : output_shapes) { if (infered_data_type == TensorProto::UNDEFINED) { infered_data_type = shape.data_type(); } if (shape.unknown_shape()) { ++i; continue; } CheckAndSetTensorShapeAndType( op.output(i++), current_dim_type_, ConvertToVec(shape.dims()), infered_data_type, is_quantized); } } catch (const caffe2::EnforceNotMet& e) { LOG(ERROR) << "Enforce not met while inferring shapes for " << op.type() << ": " << e.msg(); } catch (const std::exception& e) { LOG(WARNING) << "Caught exception while inferring shapes for " << op.type() << ": " << e.what(); } } } // namespace caffe2
32.496094
82
0.633009
[ "shape", "vector" ]
0867648b6aef67c2cb47e6196bfb55483b782466
14,828
cpp
C++
Base/PLScene/src/Scene/SNSpotLight.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
1
2019-11-09T16:54:04.000Z
2019-11-09T16:54:04.000Z
Base/PLScene/src/Scene/SNSpotLight.cpp
naetherm/pixelligh
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLScene/src/Scene/SNSpotLight.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
null
null
null
/*********************************************************\ * File: SNSpotLight.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLRenderer/RendererContext.h> #include <PLRenderer/Renderer/DrawHelpers.h> #include <PLRenderer/Effect/EffectManager.h> #include "PLScene/Visibility/VisNode.h" #include "PLScene/Scene/SNSpotLight.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; using namespace PLMath; using namespace PLGraphics; using namespace PLRenderer; namespace PLScene { //[-------------------------------------------------------] //[ RTTI interface ] //[-------------------------------------------------------] pl_class_metadata(SNSpotLight, "PLScene", PLScene::SNPointLight, "Spot light scene node") // Constructors pl_constructor_0_metadata(DefaultConstructor, "Default constructor", "") // Attributes pl_attribute_metadata(OuterAngle, float, 45.0f, ReadWrite, "Outer cone angle in degree", "") pl_attribute_metadata(InnerAngle, float, 35.0f, ReadWrite, "Inner cone angle in degree (smaller than the outer angle)", "") pl_attribute_metadata(ZNear, float, 0.1f, ReadWrite, "Near clipping plane", "") pl_attribute_metadata(Aspect, float, 1.0f, ReadWrite, "Aspect factor (only used if 'NoCone'-flag is set!)", "") // Overwritten SceneNode attributes pl_attribute_metadata(Flags, pl_flag_type_def3(SNSpotLight, EFlags), 0, ReadWrite, "Flags", "") pl_attribute_metadata(DebugFlags, pl_flag_type_def3(SNSpotLight, EDebugFlags), 0, ReadWrite, "Debug flags", "") pl_class_metadata_end(SNSpotLight) //[-------------------------------------------------------] //[ Public RTTI get/set functions ] //[-------------------------------------------------------] void SNSpotLight::SetRange(float fValue) { // Clamp minimum range if (fValue < MinRange) fValue = MinRange; // Same value? if (GetRange() != fValue) { // Call base implementation SNPointLight::SetRange(fValue); // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateBoxPlaneSet; m_nInternalLightFlags |= RecalculateProjectionMatrix; m_nInternalLightFlags |= RecalculateFrustum; // We have to recalculate the current axis align bounding box in 'scene node space' DirtyAABoundingBox(); } } float SNSpotLight::GetOuterAngle() const { return m_fOuterAngle; } void SNSpotLight::SetOuterAngle(float fValue) { // Same value? if (m_fOuterAngle != fValue) { // Set new value m_fOuterAngle = fValue; // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateProjectionMatrix; m_nInternalLightFlags |= RecalculateFrustum; // We have to recalculate the current axis align bounding box in 'scene node space' DirtyAABoundingBox(); // The inner angle must be smaller than the outer angle if (m_fInnerAngle > m_fOuterAngle) m_fInnerAngle = m_fOuterAngle; } } float SNSpotLight::GetInnerAngle() const { return m_fInnerAngle; } void SNSpotLight::SetInnerAngle(float fValue) { // The inner angle must be smaller than the outer angle m_fInnerAngle = (fValue > m_fOuterAngle) ? m_fOuterAngle : fValue; } float SNSpotLight::GetZNear() const { return m_fZNear; } void SNSpotLight::SetZNear(float fValue) { // Same value? if (m_fZNear != fValue) { m_fZNear = fValue; // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateBoxPlaneSet; m_nInternalLightFlags |= RecalculateProjectionMatrix; m_nInternalLightFlags |= RecalculateFrustum; m_nInternalLightFlags |= RecalculateFrustumVertices; // We have to recalculate the current axis align bounding box in 'scene node space' DirtyAABoundingBox(); } } float SNSpotLight::GetAspect() const { return m_fAspect; } void SNSpotLight::SetAspect(float fValue) { // Same value? if (m_fAspect != fValue && ((GetFlags() & NoCone) || (!(GetFlags() & NoCone) && m_fAspect != 1.0f))) { m_fAspect = fValue; // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateBoxPlaneSet; m_nInternalLightFlags |= RecalculateProjectionMatrix; m_nInternalLightFlags |= RecalculateFrustum; m_nInternalLightFlags |= RecalculateFrustumVertices; // We have to recalculate the current axis align bounding box in 'scene node space' DirtyAABoundingBox(); } } //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Default constructor */ SNSpotLight::SNSpotLight() : OuterAngle(this), InnerAngle(this), ZNear(this), Aspect(this), Flags(this), DebugFlags(this), EventHandlerPositionRotation(&SNSpotLight::OnPositionRotation, this), m_fOuterAngle(45.0f), m_fInnerAngle(35.0f), m_fZNear(0.1f), m_fAspect(1.0f) { // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateProjectionMatrix; m_nInternalLightFlags |= RecalculateViewMatrix; m_nInternalLightFlags |= RecalculateFrustum; m_nInternalLightFlags |= RecalculateFrustumVertices; // Connect event handlers GetTransform().EventPosition.Connect(EventHandlerPositionRotation); GetTransform().EventRotation.Connect(EventHandlerPositionRotation); } /** * @brief * Destructor */ SNSpotLight::~SNSpotLight() { } /** * @brief * Returns the projection matrix */ const Matrix4x4 &SNSpotLight::GetProjectionMatrix() { // Calculate projection matrix if required if (m_nInternalLightFlags & RecalculateProjectionMatrix) { m_mProj.PerspectiveFov(static_cast<float>(m_fOuterAngle*Math::DegToRad), (GetFlags() & NoCone) ? m_fAspect : 1.0f, m_fZNear, GetRange()); // Recalculation done m_nInternalLightFlags &= ~RecalculateProjectionMatrix; } // Return the projection matrix return m_mProj; } /** * @brief * Returns the view matrix */ const Matrix3x4 &SNSpotLight::GetViewMatrix() { // Calculate view matrix if required if (m_nInternalLightFlags & RecalculateViewMatrix) { // Calculate view matrix m_mView.View(CalculateViewRotation(), GetTransform().GetPosition()); // Recalculation done m_nInternalLightFlags &= ~RecalculateViewMatrix; } // Return the view matrix return m_mView; } /** * @brief * Returns the spot light frustum plane set */ const Frustum &SNSpotLight::GetFrustum() { // Calculate frustum if required if (m_nInternalLightFlags & RecalculateFrustum) { // Concatenate (multiply) the view matrix and the projection matrix Matrix4x4 mViewProjection = GetProjectionMatrix(); mViewProjection *= GetViewMatrix(); // Calculate frustum m_cFrustum.CreateViewPlanes(mViewProjection, true); // Recalculation done m_nInternalLightFlags &= ~RecalculateFrustum; } // Return the frustum return m_cFrustum; } /** * @brief * Returns the 8 spot light frustum vertices */ const Array<Vector3> &SNSpotLight::GetFrustumVertices() { // Calculate frustum vertices if required if (m_nInternalLightFlags & RecalculateFrustumVertices) { // Set unit box m_cFrustumVertices.Resize(8); m_cFrustumVertices[0].SetXYZ(-1.0f, -1.0f, -1.0f); m_cFrustumVertices[1].SetXYZ(-1.0f, 1.0f, -1.0f); m_cFrustumVertices[2].SetXYZ( 1.0f, 1.0f, -1.0f); m_cFrustumVertices[3].SetXYZ( 1.0f, -1.0f, -1.0f); m_cFrustumVertices[4].SetXYZ(-1.0f, -1.0f, 1.0f); m_cFrustumVertices[5].SetXYZ(-1.0f, 1.0f, 1.0f); m_cFrustumVertices[6].SetXYZ( 1.0f, 1.0f, 1.0f); m_cFrustumVertices[7].SetXYZ( 1.0f, -1.0f, 1.0f); // Get world transform matrix Matrix4x4 mWorld; mWorld.FromQuatTrans(CalculateViewRotation(), GetTransform().GetPosition()); mWorld *= GetProjectionMatrix().GetInverted(); // Project the vertices for (uint8 i=0; i<m_cFrustumVertices.GetNumOfElements(); i++) m_cFrustumVertices[i] *= mWorld; // Recalculation done m_nInternalLightFlags &= ~RecalculateFrustumVertices; } // Return the frustum vertices return m_cFrustumVertices; } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Called when the scene node position or rotation changed */ void SNSpotLight::OnPositionRotation() { // We have to recalculate some stuff m_nInternalLightFlags |= RecalculateViewMatrix; m_nInternalLightFlags |= RecalculateFrustum; m_nInternalLightFlags |= RecalculateFrustumVertices; } /** * @brief * Calculates and returns the current view rotation */ Quaternion SNSpotLight::CalculateViewRotation() const { // Static constant 180 degree y view rotation offset quaternion static const Quaternion ViewRotationOffset(-4.3711388e-008f, 0.0f, 1.0f, 0.0f); // Calculate view rotation with a 180 degree y offset (see SNSpotLight class documentation) return GetTransform().GetRotation()*ViewRotationOffset; } //[-------------------------------------------------------] //[ Public virtual SNLight functions ] //[-------------------------------------------------------] bool SNSpotLight::IsSpotLight() const { return true; } //[-------------------------------------------------------] //[ Public virtual SceneNode functions ] //[-------------------------------------------------------] void SNSpotLight::DrawDebug(Renderer &cRenderer, const VisNode *pVisNode) { // Call base implementation SNPointLight::DrawDebug(cRenderer, pVisNode); // Draw anything? if (pVisNode && (!(GetDebugFlags() & DebugNoFrustum) || (GetDebugFlags() & DebugFrustumVertices))) { static const Color4 cColor(0.8f, 1.0f, 0.8f, 1.0f); // Setup render states cRenderer.GetRendererContext().GetEffectManager().Use(); cRenderer.SetRenderState(RenderState::ZEnable, GetDebugFlags() & DebugDepthTest); cRenderer.SetRenderState(RenderState::ZWriteEnable, GetDebugFlags() & DebugDepthTest); // Draw light frustum? if (!(GetDebugFlags() & DebugNoFrustum)) { // Get the view projection matrix const Matrix4x4 &mViewProjection = pVisNode->GetViewProjectionMatrix(); // Get world transform matrix Matrix4x4 mTransform; mTransform.FromQuatTrans(CalculateViewRotation(), GetTransform().GetPosition()); // Calculate the final render world space transform Matrix4x4 mWorld = pVisNode->GetParent()->GetWorldMatrix(); // Start within 'container space', this is our origin mWorld *= mTransform; // Apply the 'scene node space' to 'container space' transform mWorld *= GetProjectionMatrix().GetInverted(); // Apply projection, the box comes a truncated cone // Draw cRenderer.GetDrawHelpers().DrawBox(cColor, Vector3::NegativeOne, Vector3::One, mViewProjection*mWorld, 1.0f); // Draw inner cone light frustum? if (!(GetFlags() & NoCone)) { // Calculate the projection matrix Matrix4x4 mProj; mProj.PerspectiveFov(static_cast<float>(m_fInnerAngle*Math::DegToRad), 1.0f, m_fZNear, GetRange()); mProj.Invert(); // Calculate the world matrix mWorld = pVisNode->GetParent()->GetWorldMatrix(); // Start within 'container space', this is our origin mWorld *= mTransform; // Apply the 'scene node space' to 'container space' transform mWorld *= mProj; // Apply projection, the box comes a truncated cone // Draw cRenderer.GetDrawHelpers().DrawBox(Color4(0.5f, 1.0f, 0.5f, 1.0f), Vector3::NegativeOne, Vector3::One, mViewProjection*mWorld, 1.0f); } } // Draw the frustum vertices? (there are ALWAYS 8 of them!) if ((GetDebugFlags() & DebugFrustumVertices) && pVisNode->GetParent()) { // Draw them - this points are within the 'container space' const Array<Vector3> &lstV = GetFrustumVertices(); for (uint8 i=0; i<lstV.GetNumOfElements(); i++) cRenderer.GetDrawHelpers().DrawPoint(cColor, lstV[i], pVisNode->GetParent()->GetWorldViewProjectionMatrix(), 5.0f); } } } //[-------------------------------------------------------] //[ Protected virtual SceneNode functions ] //[-------------------------------------------------------] void SNSpotLight::UpdateAABoundingBox() { const Array<Vector3> &lstVertices = GetFrustumVertices(); if (lstVertices.GetNumOfElements()) { const Matrix4x4 &mInvWorld = GetTransform().GetInverseMatrix(); // Initialize AABoundingBox cBox = mInvWorld*lstVertices[0]; // Get axis aligned bounding box for (uint8 i=1; i<lstVertices.GetNumOfElements(); i++) cBox.AppendToCubicHull(mInvWorld*lstVertices[i]); // Set the final axis aligned bounding box SetAABoundingBox(cBox); } } void SNSpotLight::GetBoundingSphere(Sphere &cSphere) { // The sphere has always the 'range' as radius cSphere.SetRadius(GetRange()); // The sphere is always within the scene node origin cSphere.SetPos(GetTransform().GetPosition()); } void SNSpotLight::GetContainerBoundingSphere(Sphere &cSphere) { // The sphere has always the 'range' as radius cSphere.SetRadius(GetRange()); // The sphere is always within the scene node origin cSphere.SetPos(GetTransform().GetPosition()); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLScene
33.098214
137
0.650998
[ "render", "transform" ]
0867967f5cd4f1131ec92b8f3a14aeb05ad3dd9e
7,273
cpp
C++
MiscFunctions.cpp
aljawary/PZ_CSGO_CHEAT-master
f27ffdec8514df89d6d72b4b319d63933b114695
[ "MIT" ]
null
null
null
MiscFunctions.cpp
aljawary/PZ_CSGO_CHEAT-master
f27ffdec8514df89d6d72b4b319d63933b114695
[ "MIT" ]
null
null
null
MiscFunctions.cpp
aljawary/PZ_CSGO_CHEAT-master
f27ffdec8514df89d6d72b4b319d63933b114695
[ "MIT" ]
null
null
null
#include "MiscFunctions.h" #include "Autowall.h" #include "Render.h" char shit[16]; trace_t Trace; char shit2[16]; C_BaseEntity* entCopy; bool MiscFunctions::IsVisible(C_BaseEntity* pLocal, C_BaseEntity* pEntity) { entCopy = pEntity; if (!pLocal->IsValid()) return false; Vector vSrcOrigin = pLocal->GetEyePosition(); if (vSrcOrigin.IsZero() || !vSrcOrigin.IsValid()) return false; BYTE bHitBoxCheckVisible[19] = { Head, LeftHand, RightHand, LeftFoot, RightFoot, Chest, }; CTraceFilter filter; filter.pSkip = pLocal; for (int nHit = 0; nHit < 19; nHit++) { Vector vHitBox = GetHitboxPosition(pEntity,bHitBoxCheckVisible[nHit]); if (vHitBox.IsZero() || !vHitBox.IsValid()) continue; trace_t tr; Ray_t ray; ray.Init(vSrcOrigin, vHitBox); Interfaces::EngineTrace()->TraceRay(ray, PlayerVisibleMask, &filter, &tr); if (tr.m_pEnt == (C_BaseEntity*)entCopy && !tr.allsolid) return true; } return false; } bool MiscFunctions::IsKnife(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CKnife || pWeaponClass->m_ClassID == (int)ClassID::CC4 || pWeaponClass->m_ClassID == (int)ClassID::CKnifeGG) return true; else return false; } bool MiscFunctions::IsBomb(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CC4) return true; else return false; } bool MiscFunctions::IsPistol(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CWeaponElite || pWeaponClass->m_ClassID == (int)ClassID::CWeaponFiveSeven || pWeaponClass->m_ClassID == (int)ClassID::CWeaponGlock || pWeaponClass->m_ClassID == (int)ClassID::CWeaponHKP2000 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponP250 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponP228 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponTec9 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponUSP) return true; else return false; } bool MiscFunctions::IsRevolver(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CDEagle) return true; else return false; } bool MiscFunctions::IsSniper(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CWeaponAWP || pWeaponClass->m_ClassID == (int)ClassID::CWeaponSSG08 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponSCAR20 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponG3SG1) return true; else return false; } bool MiscFunctions::IsRifle(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CWeaponFamas || pWeaponClass->m_ClassID == (int)ClassID::CAK47 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponM4A1 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponGalil || pWeaponClass->m_ClassID == (int)ClassID::CWeaponGalilAR || pWeaponClass->m_ClassID == (int)ClassID::CWeaponAug || pWeaponClass->m_ClassID == (int)ClassID::CWeaponSG556) return true; else return false; } bool MiscFunctions::IsSmg(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CWeaponMP7 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponMP9 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponUMP45 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponP90 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponBizon || pWeaponClass->m_ClassID == (int)ClassID::CWeaponMAC10) return true; else return false; } bool MiscFunctions::IsHeavy(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CWeaponNegev || pWeaponClass->m_ClassID == (int)ClassID::CWeaponM249 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponXM1014 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponNOVA || pWeaponClass->m_ClassID == (int)ClassID::CWeaponMag7 || pWeaponClass->m_ClassID == (int)ClassID::CWeaponSawedoff) return true; else return false; } bool MiscFunctions::IsGrenade(void* weapon) { if (weapon == nullptr) return false; C_BaseEntity* weaponEnt = (C_BaseEntity*)weapon; ClientClass* pWeaponClass = weaponEnt->GetClientClass(); if (pWeaponClass->m_ClassID == (int)ClassID::CDecoyGrenade || pWeaponClass->m_ClassID == (int)ClassID::CHEGrenade || pWeaponClass->m_ClassID == (int)ClassID::CIncendiaryGrenade || pWeaponClass->m_ClassID == (int)ClassID::CMolotovGrenade || pWeaponClass->m_ClassID == (int)ClassID::CSensorGrenade || pWeaponClass->m_ClassID == (int)ClassID::CSmokeGrenade || pWeaponClass->m_ClassID == (int)ClassID::CFlashbang) return true; else return false; } void SayInChat(const char *text) { char buffer[250]; sprintf_s(buffer, "say \"%s\"", text); Interfaces::Engine()->ClientCmd_Unrestricted2(buffer); } float GenerateRandomFloat(float Min, float Max) { float randomized = (float)rand() / (float)RAND_MAX; return Min + randomized * (Max - Min); } Vector GetHitboxPosition(C_BaseEntity* pEntity, int Hitbox) { matrix3x4_t matrix[MAXSTUDIOBONES]; Vector vRet, vMin, vMax; vRet = Vector(0, 0, 0); studiohdr_t* hdr = Interfaces::ModelInfo()->GetStudiomodel(pEntity->GetModel()); mstudiohitboxset_t* set = hdr->GetHitboxSet(0); mstudiobbox_t* hitbox = set->GetHitbox(Hitbox); if (!hitbox || !pEntity->IsValid()) return vRet; if (!pEntity->SetupBones(matrix, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, pEntity->GetSimulationTime())) return vRet; if (!hitbox->bone || !hitbox->bbmin.IsValid() || !hitbox->bbmax.IsValid()) return vRet; VectorTransform(hitbox->bbmin, matrix[hitbox->bone], vMin); VectorTransform(hitbox->bbmax, matrix[hitbox->bone], vMax); vRet = (vMin + vMax) * 0.5f; return vRet; } Vector GetHitboxPositionFromMatrix(C_BaseEntity* pEntity, matrix3x4_t matrix[128], int Hitbox) { studiohdr_t* hdr = Interfaces::ModelInfo()->GetStudiomodel(pEntity->GetModel()); mstudiohitboxset_t* set = hdr->GetHitboxSet(0); mstudiobbox_t* hitbox = set->GetHitbox(Hitbox); if (!hitbox) return Vector(0, 0, 0); Vector vMin, vMax, vCenter, sCenter; VectorTransform(hitbox->bbmin, matrix[hitbox->bone], vMin); VectorTransform(hitbox->bbmax, matrix[hitbox->bone], vMax); vCenter = (vMin + vMax) *0.5f; return vCenter; }
19.291777
459
0.712086
[ "render", "vector" ]
086d5bf31758618921bcf52fe10ac1d0dcf9bfb0
8,684
cc
C++
daemon/protocol/mcbp/sasl_auth_command_context.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
104
2017-05-22T20:41:57.000Z
2022-03-24T00:18:34.000Z
daemon/protocol/mcbp/sasl_auth_command_context.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
3
2017-11-14T08:12:46.000Z
2022-03-03T11:14:17.000Z
daemon/protocol/mcbp/sasl_auth_command_context.cc
nawazish-couchbase/kv_engine
132f1bb04c9212bcac9e401d069aeee5f63ff1cd
[ "MIT", "BSD-3-Clause" ]
71
2017-05-22T20:41:59.000Z
2022-03-29T10:34:32.000Z
/* * Copyright 2017-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "sasl_auth_command_context.h" #include <daemon/buckets.h> #include <daemon/connection.h> #include <daemon/mcaudit.h> #include <daemon/memcached.h> #include <daemon/settings.h> #include <daemon/stats.h> #include <logger/logger.h> #include <utilities/logtags.h> std::string getMechanism(cb::const_byte_buffer k) { std::string mechanism; const auto key = std::string_view{reinterpret_cast<const char*>(k.data()), k.size()}; // Uppercase the requested mechanism so that we don't have to remember // to do case insensitive comparisons all over the code std::transform( key.begin(), key.end(), std::back_inserter(mechanism), toupper); return mechanism; } std::string getChallenge(cb::const_byte_buffer value) { return std::string{reinterpret_cast<const char*>(value.data()), value.size()}; } SaslAuthCommandContext::SaslAuthCommandContext(Cookie& cookie) : SteppableCommandContext(cookie), request(cookie.getRequest()), mechanism(getMechanism(request.getKey())), challenge(getChallenge(request.getValue())), state(State::Initial) { } cb::engine_errc SaslAuthCommandContext::tryHandleSaslOk( std::string_view payload) { auto& serverContext = *connection.getSaslServerContext(); std::pair<cb::rbac::PrivilegeContext, bool> context{ cb::rbac::PrivilegeContext{cb::sasl::Domain::Local}, false}; // Authentication successful, but it still has to be defined in // our system try { context = cb::rbac::createInitialContext(serverContext.getUser()); } catch (const cb::rbac::NoSuchUserException&) { LOG_WARNING( "{}: User [{}] is not defined as a user in Couchbase. " "Mechanism:[{}], UUID:[{}]", connection.getId(), cb::UserDataView(serverContext.getUser().name), mechanism, cookie.getEventId()); authFailure(cb::sasl::Error::NO_RBAC_PROFILE); return cb::engine_errc::success; } // Success connection.setAuthenticated(true, context.second, serverContext.getUser()); audit_auth_success(connection, &cookie); LOG_INFO("{}: Client {} authenticated as {}", connection.getId(), connection.getPeername(), cb::UserDataView(connection.getUser().name)); /* associate the connection with the appropriate bucket */ { const auto username = connection.getUser().name; if (mayAccessBucket(cookie, username)) { associate_bucket(cookie, username.c_str()); // Auth succeeded but the connection may not be valid for the // bucket if (connection.isCollectionsSupported() && !connection.getBucket().supports( cb::engine::Feature::Collections)) { // Move back to the "no bucket" as this is not valid associate_bucket(cookie, ""); } } else { // the user don't have access to that bucket, move the // connection to the "no bucket" associate_bucket(cookie, ""); } } cookie.sendResponse(cb::mcbp::Status::Success, {}, {}, payload, cb::mcbp::Datatype::Raw, 0); get_thread_stats(&connection)->auth_cmds++; state = State::Done; return cb::engine_errc::success; } cb::engine_errc SaslAuthCommandContext::doHandleSaslAuthTaskResult( cb::sasl::Error error, std::string_view payload) { // If CBSASL generated a UUID, we should continue to use that UUID auto& serverContext = *connection.getSaslServerContext(); if (serverContext.containsUuid()) { cookie.setEventId(serverContext.getUuid()); } // Perform the appropriate logging for each error code switch (error) { case cb::sasl::Error::OK: return tryHandleSaslOk(payload); case cb::sasl::Error::CONTINUE: LOG_DEBUG("{}: SASL CONTINUE", connection.getId()); return authContinue(payload); case cb::sasl::Error::BAD_PARAM: return authBadParameters(); case cb::sasl::Error::FAIL: case cb::sasl::Error::NO_MEM: return authFailure(error); case cb::sasl::Error::NO_MECH: cookie.setErrorContext("Requested mechanism \"" + mechanism + "\" is not supported"); return authFailure(error); case cb::sasl::Error::NO_USER: LOG_WARNING("{}: User [{}] not found. Mechanism:[{}], UUID:[{}]", connection.getId(), cb::UserDataView(connection.getUser().name), mechanism, cookie.getEventId()); audit_auth_failure( connection, serverContext.getUser(), "Unknown user", &cookie); return authFailure(error); case cb::sasl::Error::PASSWORD_ERROR: LOG_WARNING( "{}: Invalid password specified for [{}]. Mechanism:[{}], " "UUID:[{}]", connection.getId(), cb::UserDataView(connection.getUser().name), mechanism, cookie.getEventId()); audit_auth_failure(connection, serverContext.getUser(), "Incorrect password", &cookie); return authFailure(error); case cb::sasl::Error::NO_RBAC_PROFILE: LOG_WARNING( "{}: User [{}] is not defined as a user in Couchbase. " "Mechanism:[{}], UUID:[{}]", connection.getId(), cb::UserDataView(connection.getUser().name), mechanism, cookie.getEventId()); return authFailure(error); case cb::sasl::Error::AUTH_PROVIDER_DIED: LOG_WARNING("{}: Auth provider closed the connection. UUID:[{}]", connection.getId(), cookie.getEventId()); return authFailure(error); } throw std::logic_error( "SaslAuthCommandContext::handleSaslAuthTaskResult: Unknown sasl " "error"); } cb::engine_errc SaslAuthCommandContext::step() { auto ret = cb::engine_errc::success; do { switch (state) { case State::Initial: ret = initial(); break; case State::HandleSaslAuthTaskResult: ret = handleSaslAuthTaskResult(); break; case State::Done: // All done and we've sent a response to the client return cb::engine_errc::success; } } while (ret == cb::engine_errc::success); return ret; } cb::engine_errc SaslAuthCommandContext::authContinue( std::string_view challenge) { cookie.sendResponse(cb::mcbp::Status::AuthContinue, {}, {}, challenge, cb::mcbp::Datatype::Raw, 0); state = State::Done; return cb::engine_errc::success; } cb::engine_errc SaslAuthCommandContext::authBadParameters() { auto* ts = get_thread_stats(&connection); ts->auth_cmds++; ts->auth_errors++; connection.releaseSaslServerContext(); return cb::engine_errc::invalid_arguments; } cb::engine_errc SaslAuthCommandContext::authFailure(cb::sasl::Error error) { state = State::Done; if (error == cb::sasl::Error::AUTH_PROVIDER_DIED) { cookie.sendResponse(cb::mcbp::Status::Etmpfail); } else { if (Settings::instance().isExternalAuthServiceEnabled()) { cookie.setErrorContext( "Authentication failed. This could be due to invalid " "credentials or if the user is an external user the " "external authentication service may not support the " "selected authentication mechanism."); } cookie.sendResponse(cb::mcbp::Status::AuthError); } auto* ts = get_thread_stats(&connection); ts->auth_cmds++; ts->auth_errors++; connection.releaseSaslServerContext(); return cb::engine_errc::success; }
35.736626
80
0.590281
[ "transform" ]
086f8750514a8c8ef8819b17d5121be5d5b865ea
1,852
cpp
C++
sw5653_3.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
1
2022-02-21T09:11:15.000Z
2022-02-21T09:11:15.000Z
sw5653_3.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
null
null
null
sw5653_3.cpp
sjnov11/SW-expert-academy
b7040017f2f8ff037aee40a5024284aaad1e50f9
[ "MIT" ]
1
2019-07-03T10:12:55.000Z
2019-07-03T10:12:55.000Z
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; int board[400][400]; int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; struct Cell { int x, y; int life; int time; }; bool operator <(const Cell &a, const Cell &b) { return a.life > b.life; } bool cmp(const Cell &a, const Cell &b) { return a.life > b.life; } int main() { int T; cin >> T; for (int tc = 1; tc <= T; tc++) { int N, M, K; cin >> N >> M >> K; queue<Cell> alive_cell_queue; for (int i = 0; i < 400; i++) { for (int j = 0; j < 400; j++) { board[i][j] = 0; } } for (int i = 150; i < 150 + N; i++) { for (int j = 150; j < 150 + M; j++) { cin >> board[i][j]; if (board[i][j] > 0) alive_cell_queue.push({ i,j,board[i][j],0 }); } } for (int k = 0; k < K; k++) { vector<Cell> next_cell_list; while (!alive_cell_queue.empty()) { Cell cell = alive_cell_queue.front(); alive_cell_queue.pop(); // spread if (cell.time == cell.life) { for (int d = 0; d < 4; d++) { int nx = cell.x + dir[d][0]; int ny = cell.y + dir[d][1]; if (board[nx][ny] != 0) continue; next_cell_list.push_back({ nx,ny,cell.life,0 }); } } cell.time++; if (cell.time == cell.life * 2) { board[cell.x][cell.y] = -1; } else { next_cell_list.push_back(cell); } } sort(next_cell_list.begin(), next_cell_list.end()); for (auto cell : next_cell_list) { if (cell.time > 0) alive_cell_queue.push(cell); else { if (board[cell.x][cell.y] == 0) { board[cell.x][cell.y] = cell.life; alive_cell_queue.push(cell); } } } } int answer = 0; for (int i = 0; i < 400; i++) { for (int j = 0; j < 400; j++) { if (board[i][j] > 0) answer++; } } cout << "#" << tc << " " << answer << endl; } }
22.047619
70
0.510799
[ "vector" ]
087306a2c74d9bf62971ea3d0f0047d1ff41cdb4
1,347
cpp
C++
cpp/fractional_knapsack.cpp
maojh/Hacktoberfest
12562a109677664def6d5cee3ab7cb119c85f1d9
[ "MIT" ]
1
2020-10-06T01:20:07.000Z
2020-10-06T01:20:07.000Z
cpp/fractional_knapsack.cpp
devnarayanp02/Hacktoberfest
ff1c1db99ed9a408d84c326126ff07d946d3987b
[ "MIT" ]
null
null
null
cpp/fractional_knapsack.cpp
devnarayanp02/Hacktoberfest
ff1c1db99ed9a408d84c326126ff07d946d3987b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <iterator> using namespace std; double get_optimal_value(int c, vector<int>& weights, vector<int>& values) { map<double,int> knap; for(int i=0;i<values.size();i++) { double val=values[i]/(double)weights[i]; knap.insert({val,weights[i]}); } map<double, int>::iterator itr; itr=knap.end(); itr--; double val=0; while(c>0&&itr!=knap.begin()) { if(itr->second<c) { val+=(itr->first*itr->second); c-=itr->second; itr--; } else { val+=(itr->first*c); c=0; itr--; } } if(itr->second<c) { val+=(itr->first*itr->second); c-=itr->second; itr--; } else { val+=(itr->first*c); c=0; itr--; } return val; } int main() { int n; int capacity; cin >> n >> capacity; vector<int> values(n); vector<int> weights(n); for (int i = 0; i < n; i++) { cin >> values[i] >> weights[i]; } double optimal_value = get_optimal_value(capacity, weights, values); cout.precision(10); cout <<fixed<< optimal_value <<endl; return 0; }
19.521739
76
0.445434
[ "vector" ]
087447a8b83f7460a3825fe8c7efe53ebc56ee93
12,282
cxx
C++
Rendering/Core/vtkTransformInterpolator.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
1
2021-12-02T07:23:36.000Z
2021-12-02T07:23:36.000Z
Rendering/Core/vtkTransformInterpolator.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
null
null
null
Rendering/Core/vtkTransformInterpolator.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
1
2021-12-02T07:29:15.000Z
2021-12-02T07:29:15.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkTransformInterpolator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTransformInterpolator.h" #include "vtkObjectFactory.h" #include "vtkTransform.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkProp3D.h" #include "vtkTupleInterpolator.h" #include "vtkQuaternion.h" #include "vtkQuaternionInterpolator.h" #include <list> vtkStandardNewMacro(vtkTransformInterpolator); // PIMPL STL encapsulation for list of transforms, and list of // quaternions. This just keeps track of all the data the user specifies, // which is later dumped into the interpolators. struct vtkQTransform { double Time; double P[3]; double S[3]; vtkQuaterniond Q; vtkQTransform() { this->Time = 0.0; this->P[0] = this->P[1] = this->P[2] = 0.0; this->S[0] = this->S[1] = this->S[2] = 0.0; } vtkQTransform(double t, vtkTransform *xform) { this->Time = t; if ( xform ) { xform->GetPosition(this->P); xform->GetScale(this->S); double q[4]; xform->GetOrientationWXYZ(q); //Rotation (in degrees) around unit vector q[0] = vtkMath::RadiansFromDegrees(q[0]); this->Q.SetRotationAngleAndAxis(q[0], q+1); } else { this->P[0] = this->P[1] = this->P[2] = 0.0; this->S[0] = this->S[1] = this->S[2] = 0.0; } } }; // The list is arranged in increasing order in T class vtkTransformList : public std::list<vtkQTransform> {}; typedef vtkTransformList::iterator TransformListIterator; //---------------------------------------------------------------------------- vtkTransformInterpolator::vtkTransformInterpolator() { // Set up the interpolation this->InterpolationType = INTERPOLATION_TYPE_SPLINE; // Spline interpolation this->PositionInterpolator = vtkTupleInterpolator::New(); this->ScaleInterpolator = vtkTupleInterpolator::New(); this->RotationInterpolator = vtkQuaternionInterpolator::New(); // Quaternion interpolation this->TransformList = new vtkTransformList; this->Initialized = 0; } //---------------------------------------------------------------------------- vtkTransformInterpolator::~vtkTransformInterpolator() { delete this->TransformList; if ( this->PositionInterpolator ) { this->PositionInterpolator->Delete(); } if ( this->ScaleInterpolator ) { this->ScaleInterpolator->Delete(); } if ( this->RotationInterpolator ) { this->RotationInterpolator->Delete(); } } //---------------------------------------------------------------------------- vtkMTimeType vtkTransformInterpolator::GetMTime() { vtkMTimeType mTime=this->Superclass::GetMTime(); vtkMTimeType posMTime, scaleMTime, rotMTime; if ( this->PositionInterpolator ) { posMTime = this->PositionInterpolator->GetMTime(); mTime = (posMTime > mTime ? posMTime : mTime); } if ( this->ScaleInterpolator ) { scaleMTime = this->ScaleInterpolator->GetMTime(); mTime = (scaleMTime > mTime ? scaleMTime : mTime); } if ( this->RotationInterpolator ) { rotMTime = this->RotationInterpolator->GetMTime(); mTime = (rotMTime > mTime ? rotMTime : mTime); } return mTime; } //---------------------------------------------------------------------------- int vtkTransformInterpolator::GetNumberOfTransforms() { return static_cast<int>(this->TransformList->size()); } //---------------------------------------------------------------------------- double vtkTransformInterpolator::GetMinimumT() { if ( this->TransformList->empty() ) { return -VTK_FLOAT_MAX; } else { return this->TransformList->front().Time; } } //---------------------------------------------------------------------------- double vtkTransformInterpolator::GetMaximumT() { if ( this->TransformList->empty() ) { return VTK_FLOAT_MAX; } else { return this->TransformList->back().Time; } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::Initialize() { this->TransformList->clear(); } //---------------------------------------------------------------------------- void vtkTransformInterpolator::AddTransform(double t, vtkTransform *xform) { int size = static_cast<int>(this->TransformList->size()); // Check special cases: t at beginning or end of list if ( size <= 0 || t < this->TransformList->front().Time ) { this->TransformList->push_front(vtkQTransform(t,xform)); return; } else if ( t > this->TransformList->back().Time ) { this->TransformList->push_back(vtkQTransform(t,xform)); return; } else if ( size == 1 && t == this->TransformList->back().Time ) { this->TransformList->front() = vtkQTransform(t,xform); return; } // Okay, insert in sorted order TransformListIterator iter = this->TransformList->begin(); TransformListIterator nextIter = ++(this->TransformList->begin()); for (int i=0; i < (size-1); i++, ++iter, ++nextIter) { if ( t == iter->Time ) { (*iter) = vtkQTransform(t,xform); } else if ( t > iter->Time && t < nextIter->Time ) { this->TransformList->insert(nextIter, vtkQTransform(t,xform)); } } this->Modified(); } //---------------------------------------------------------------------------- void vtkTransformInterpolator::AddTransform(double t, vtkMatrix4x4 *matrix) { vtkTransform *xform = vtkTransform::New(); xform->SetMatrix(matrix); this->AddTransform(t,xform); xform->Delete(); } //---------------------------------------------------------------------------- void vtkTransformInterpolator::AddTransform(double t, vtkProp3D *prop3D) { this->AddTransform(t,prop3D->GetMatrix()); } //---------------------------------------------------------------------------- void vtkTransformInterpolator::RemoveTransform(double t) { if ( t < this->TransformList->front().Time || t > this->TransformList->back().Time ) { return; } TransformListIterator iter = this->TransformList->begin(); for ( ; iter->Time != t && iter != this->TransformList->end(); ++iter ) { } if ( iter != this->TransformList->end() ) { this->TransformList->erase(iter); } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::SetPositionInterpolator(vtkTupleInterpolator *pi) { if ( this->PositionInterpolator != pi ) { if ( this->PositionInterpolator != NULL ) { this->PositionInterpolator->Delete(); } this->PositionInterpolator = pi; if ( this->PositionInterpolator != NULL ) { this->PositionInterpolator->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::SetScaleInterpolator(vtkTupleInterpolator *si) { if ( this->ScaleInterpolator != si ) { if ( this->ScaleInterpolator != NULL ) { this->ScaleInterpolator->Delete(); } this->ScaleInterpolator = si; if ( this->ScaleInterpolator != NULL ) { this->ScaleInterpolator->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::SetRotationInterpolator(vtkQuaternionInterpolator *ri) { if ( this->RotationInterpolator != ri ) { if ( this->RotationInterpolator != NULL ) { this->RotationInterpolator->Delete(); } this->RotationInterpolator = ri; if ( this->RotationInterpolator != NULL ) { this->RotationInterpolator->Register(this); } this->Modified(); } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::InitializeInterpolation() { if ( this->TransformList->empty() ) { return; } // Set up the interpolators if we need to if ( !this->Initialized || this->GetMTime() > this->InitializeTime ) { if ( !this->PositionInterpolator ) { this->PositionInterpolator = vtkTupleInterpolator::New(); } if ( !this->ScaleInterpolator ) { this->ScaleInterpolator = vtkTupleInterpolator::New(); } if ( !this->RotationInterpolator ) { this->RotationInterpolator = vtkQuaternionInterpolator::New(); } if ( this->InterpolationType == INTERPOLATION_TYPE_LINEAR ) { this->PositionInterpolator->SetInterpolationTypeToLinear(); this->ScaleInterpolator->SetInterpolationTypeToLinear(); this->RotationInterpolator->SetInterpolationTypeToLinear(); } else if ( this->InterpolationType == INTERPOLATION_TYPE_SPLINE ) { this->PositionInterpolator->SetInterpolationTypeToSpline(); this->ScaleInterpolator->SetInterpolationTypeToSpline(); this->RotationInterpolator->SetInterpolationTypeToSpline(); } else { ; //manual override, user manipulates interpolators directly } this->PositionInterpolator->Initialize(); this->ScaleInterpolator->Initialize(); this->RotationInterpolator->Initialize(); this->PositionInterpolator->SetNumberOfComponents(3); this->ScaleInterpolator->SetNumberOfComponents(3); // Okay, now we can load the interpolators with data TransformListIterator iter = this->TransformList->begin(); for ( ; iter != this->TransformList->end(); ++iter) { this->PositionInterpolator->AddTuple(iter->Time,iter->P); this->ScaleInterpolator->AddTuple(iter->Time,iter->S); this->RotationInterpolator->AddQuaternion(iter->Time,iter->Q); } this->Initialized = 1; this->InitializeTime.Modified(); } } //---------------------------------------------------------------------------- void vtkTransformInterpolator::InterpolateTransform(double t, vtkTransform *xform) { if ( this->TransformList->empty() ) { return; } // Make sure the xform and this class are initialized properly xform->Identity(); this->InitializeInterpolation(); // Evaluate the interpolators if ( t < this->TransformList->front().Time ) { t = this->TransformList->front().Time; } else if ( t > this->TransformList->back().Time ) { t = this->TransformList->back().Time; } double P[3],S[3],Q[4]; vtkQuaterniond q; this->PositionInterpolator->InterpolateTuple(t,P); this->ScaleInterpolator->InterpolateTuple(t,S); this->RotationInterpolator->InterpolateQuaternion(t,q); Q[0] = vtkMath::DegreesFromRadians(q.GetRotationAngleAndAxis(Q+1)); xform->Translate(P); xform->RotateWXYZ(Q[0],Q+1); xform->Scale(S); } //---------------------------------------------------------------------------- void vtkTransformInterpolator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "There are " << this->GetNumberOfTransforms() << " transforms to be interpolated\n"; os << indent << "Interpolation Type: "; if ( this->InterpolationType == INTERPOLATION_TYPE_LINEAR ) { os << "Linear\n"; } else if ( this->InterpolationType == INTERPOLATION_TYPE_SPLINE ) { os << "Spline\n"; } else //if ( this->InterpolationType == INTERPOLATION_TYPE_MANUAL ) { os << "Manual\n"; } os << indent << "Position Interpolator: "; if ( this->PositionInterpolator ) { os << this->PositionInterpolator << "\n"; } else { os << "(null)\n"; } os << indent << "Scale Interpolator: "; if ( this->ScaleInterpolator ) { os << this->ScaleInterpolator << "\n"; } else { os << "(null)\n"; } os << indent << "Rotation Interpolator: "; if ( this->RotationInterpolator ) { os << this->RotationInterpolator << "\n"; } else { os << "(null)\n"; } }
27.172566
85
0.581746
[ "vector" ]
08765e8ad3eec56ae85247ba437a42bd47fd1b86
1,696
hpp
C++
bench/tests/qdb/ts/col_double_aggregate.hpp
bureau14/qdb-benchmark
1839d7ac04417de56b7a7fb2b7deff50756b3048
[ "BSD-2-Clause" ]
5
2017-01-19T09:35:40.000Z
2021-02-26T07:31:38.000Z
bench/tests/qdb/ts/col_double_aggregate.hpp
bureau14/qdb-benchmark
1839d7ac04417de56b7a7fb2b7deff50756b3048
[ "BSD-2-Clause" ]
1
2015-11-09T15:38:28.000Z
2015-11-12T11:14:58.000Z
bench/tests/qdb/ts/col_double_aggregate.hpp
bureau14/qdb-benchmark
1839d7ac04417de56b7a7fb2b7deff50756b3048
[ "BSD-2-Clause" ]
3
2015-11-02T09:37:09.000Z
2017-05-05T06:38:49.000Z
#pragma once #include <bench/tests/qdb/qdb_test_template.hpp> #include <time.h> namespace bench { namespace tests { namespace qdb { namespace ts { class col_double_average : public qdb_test_template<col_double_average> { public: explicit col_double_average(bench::test_config config) : qdb_test_template(config), _ts_size(config.content_size) { } void setup() override { qdb_test_template::setup(); _qdb.ts_create(alias(0), {qdb_ts_column_info_t{"double_col", qdb_ts_column_double}}); std::vector<qdb_ts_double_point> points(_ts_size); qdb_time_t cursor = 1490206139; std::generate(points.begin(), points.end(), [&cursor]() { return qdb_ts_double_point{qdb_timespec_t{cursor++, 0}, static_cast<double>(cursor)}; }); _inserted_range.begin = points.front().timestamp; _inserted_range.end = points.back().timestamp; _qdb.ts_col_double_inserts(alias(0), "double_col", points.data(), points.size()); } void run_iteration(std::uint32_t iteration) { _qdb.ts_col_double_average(alias(0), "double_col", _inserted_range); } void cleanup() override { _qdb.remove(alias(0)); qdb_test_template::cleanup(); } static std::string name() { return "qdb_ts_col_double_average"; } static std::string description() { return "Each thread averages the whole time series"; } static bool size_dependent() { return true; } private: const size_t _ts_size; qdb_ts_range_t _inserted_range; }; } // namespace ts } // namespace qdb } // namespace tests } // namespace bench
21.74359
117
0.654481
[ "vector" ]
08795b8f0b1cbe3e46aec2e928ff26b8a1035d1b
3,789
hpp
C++
include/Nazara/Core/ObjectHandle.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
include/Nazara/Core/ObjectHandle.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
include/Nazara/Core/ObjectHandle.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_OBJECTHANDLE_HPP #define NAZARA_OBJECTHANDLE_HPP #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/HandledObject.hpp> #include <memory> #include <ostream> #include <string> namespace Nz { template<typename T> class ObjectHandle { friend HandledObject<T>; public: ObjectHandle(); explicit ObjectHandle(T* object); template<typename U> ObjectHandle(const ObjectHandle<U>& ref); template<typename U> ObjectHandle(ObjectHandle<U>&& ref); ObjectHandle(const ObjectHandle& handle) = default; ObjectHandle(ObjectHandle&& handle) noexcept; ~ObjectHandle(); T* GetObject() const; bool IsValid() const; void Reset(T* object = nullptr); void Reset(const ObjectHandle& handle); void Reset(ObjectHandle&& handle) noexcept; ObjectHandle& Swap(ObjectHandle& handle); std::string ToString() const; explicit operator bool() const; operator T*() const; T* operator->() const; ObjectHandle& operator=(T* object); ObjectHandle& operator=(const ObjectHandle& handle) = default; ObjectHandle& operator=(ObjectHandle&& handle) noexcept; static const ObjectHandle InvalidHandle; protected: std::shared_ptr<const Detail::HandleData> m_handleData; }; template<typename T> std::ostream& operator<<(std::ostream& out, const ObjectHandle<T>& handle); template<typename T> bool operator==(const ObjectHandle<T>& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator==(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator==(const ObjectHandle<T>& lhs, const T& rhs); template<typename T> bool operator!=(const ObjectHandle<T>& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator!=(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator!=(const ObjectHandle<T>& lhs, const T& rhs); template<typename T> bool operator<(const ObjectHandle<T>& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator<(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator<(const ObjectHandle<T>& lhs, const T& rhs); template<typename T> bool operator<=(const ObjectHandle<T>&, const ObjectHandle<T>& rhs); template<typename T> bool operator<=(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator<=(const ObjectHandle<T>& lhs, const T& rhs); template<typename T> bool operator>(const ObjectHandle<T>& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator>(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator>(const ObjectHandle<T>& lhs, const T& rhs); template<typename T> bool operator>=(const ObjectHandle<T>& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator>=(const T& lhs, const ObjectHandle<T>& rhs); template<typename T> bool operator>=(const ObjectHandle<T>& lhs, const T& rhs); template<typename T, typename U> ObjectHandle<T> ConstRefCast(const ObjectHandle<U>& ref); template<typename T, typename U> ObjectHandle<T> DynamicRefCast(const ObjectHandle<U>& ref); template<typename T, typename U> ObjectHandle<T> ReinterpretRefCast(const ObjectHandle<U>& ref); template<typename T, typename U> ObjectHandle<T> StaticRefCast(const ObjectHandle<U>& ref); template<typename T> struct PointedType<ObjectHandle<T>> { using type = T; }; template<typename T> struct PointedType<const ObjectHandle<T>> { using type = T; }; } namespace std { template<typename T> void swap(Nz::ObjectHandle<T>& lhs, Nz::ObjectHandle<T>& rhs); } #include <Nazara/Core/ObjectHandle.inl> #endif // NAZARA_OBJECTHANDLE_HPP
37.147059
97
0.737398
[ "object" ]
087caade63a7405045348d767aa1879a1cce289e
3,979
cc
C++
lib/kahypar/tests/partition/refinement/quotient_graph_block_scheduler_test.cc
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
lib/kahypar/tests/partition/refinement/quotient_graph_block_scheduler_test.cc
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
lib/kahypar/tests/partition/refinement/quotient_graph_block_scheduler_test.cc
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
/******************************************************************************* * This file is part of KaHyPar. * * Copyright (C) 2018 Sebastian Schlag <sebastian.schlag@kit.edu> * Copyright (C) 2018 Tobias Heuer <tobias.heuer@live.com> * * KaHyPar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * KaHyPar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KaHyPar. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include <set> #include <vector> #include "gmock/gmock.h" #include "kahypar/definitions.h" #include "kahypar/partition/metrics.h" #include "kahypar/partition/refinement/flow/quotient_graph_block_scheduler.h" using ::testing::Test; using ::testing::Eq; namespace kahypar { class AQuotientGraphBlockScheduler : public Test { public: AQuotientGraphBlockScheduler() : context(), hypergraph(7, 4, HyperedgeIndexVector { 0, 2, 6, 9, 12 }, HyperedgeVector { 0, 2, 0, 1, 3, 4, 3, 4, 6, 2, 5, 6 }, 4), scheduler(nullptr) { hypergraph.setNodePart(0, 0); hypergraph.setNodePart(1, 1); hypergraph.setNodePart(2, 3); hypergraph.setNodePart(3, 2); hypergraph.setNodePart(4, 2); hypergraph.setNodePart(5, 3); hypergraph.setNodePart(6, 3); context.partition.k = 4; scheduler = new QuotientGraphBlockScheduler(hypergraph, context); } Context context; Hypergraph hypergraph; QuotientGraphBlockScheduler* scheduler; }; TEST_F(AQuotientGraphBlockScheduler, HasCorrectQuotientGraphEdges) { scheduler->buildQuotientGraph(); std::vector<std::pair<PartitionID, PartitionID> > adjacentBlocks = { std::make_pair(0, 1), std::make_pair(0, 2), std::make_pair(0, 3), std::make_pair(1, 2), std::make_pair(2, 3) }; size_t idx = 0; for (const auto& e : scheduler->qoutientGraphEdges()) { ASSERT_EQ(adjacentBlocks[idx].first, e.first); ASSERT_EQ(adjacentBlocks[idx].second, e.second); idx++; } } TEST_F(AQuotientGraphBlockScheduler, HasCorrectCutHyperedges) { scheduler->buildQuotientGraph(); for (const auto& e : scheduler->blockPairCutHyperedges(0, 1)) { ASSERT_EQ(e, 1); } for (const auto& e : scheduler->blockPairCutHyperedges(0, 2)) { ASSERT_EQ(e, 1); } for (const auto& e : scheduler->blockPairCutHyperedges(0, 3)) { ASSERT_EQ(e, 0); } for (const auto& e : scheduler->blockPairCutHyperedges(1, 2)) { ASSERT_EQ(e, 1); } for (const auto& e : scheduler->blockPairCutHyperedges(2, 3)) { ASSERT_EQ(e, 2); } } TEST_F(AQuotientGraphBlockScheduler, HasCorrectCutHyperedgesAfterMove) { scheduler->buildQuotientGraph(); scheduler->changeNodePart(1, 1, 0); size_t idx = 0; for (const auto& e : scheduler->blockPairCutHyperedges(0, 1)) { unused(e); idx++; } ASSERT_EQ(idx, 0); for (const auto& e : scheduler->blockPairCutHyperedges(0, 2)) { ASSERT_EQ(e, 1); } for (const auto& e : scheduler->blockPairCutHyperedges(0, 3)) { ASSERT_EQ(e, 0); } idx = 0; for (const auto& e : scheduler->blockPairCutHyperedges(1, 2)) { unused(e); idx++; } ASSERT_EQ(idx, 0); for (const auto& e : scheduler->blockPairCutHyperedges(2, 3)) { ASSERT_EQ(e, 2); } } } // namespace kahypar
32.349593
94
0.613219
[ "vector" ]
087d4dcae8b4eb17b029db22ad5edd43d444a7f9
20,707
hpp
C++
include/UnityEngine/StateMachineBehaviour.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/StateMachineBehaviour.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/UnityEngine/StateMachineBehaviour.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Animator class Animator; // Forward declaring type: AnimatorStateInfo struct AnimatorStateInfo; } // Forward declaring namespace: UnityEngine::Animations namespace UnityEngine::Animations { // Forward declaring type: AnimatorControllerPlayable struct AnimatorControllerPlayable; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: StateMachineBehaviour class StateMachineBehaviour; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::StateMachineBehaviour); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::StateMachineBehaviour*, "UnityEngine", "StateMachineBehaviour"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: UnityEngine.StateMachineBehaviour // [TokenAttribute] Offset: FFFFFFFF // [RequiredByNativeCodeAttribute] Offset: 6BBD54 class StateMachineBehaviour : public ::UnityEngine::ScriptableObject { public: // protected System.Void .ctor() // Offset: 0x18D2844 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static StateMachineBehaviour* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::StateMachineBehaviour::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<StateMachineBehaviour*, creationType>())); } // public System.Void OnStateEnter(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex) // Offset: 0x18D280C void OnStateEnter(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex); // public System.Void OnStateUpdate(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex) // Offset: 0x18D2810 void OnStateUpdate(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex); // public System.Void OnStateExit(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex) // Offset: 0x18D2814 void OnStateExit(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex); // public System.Void OnStateMove(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex) // Offset: 0x18D2818 void OnStateMove(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex); // public System.Void OnStateIK(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex) // Offset: 0x18D281C void OnStateIK(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex); // public System.Void OnStateMachineEnter(UnityEngine.Animator animator, System.Int32 stateMachinePathHash) // Offset: 0x18D2820 void OnStateMachineEnter(::UnityEngine::Animator* animator, int stateMachinePathHash); // public System.Void OnStateMachineExit(UnityEngine.Animator animator, System.Int32 stateMachinePathHash) // Offset: 0x18D2824 void OnStateMachineExit(::UnityEngine::Animator* animator, int stateMachinePathHash); // public System.Void OnStateEnter(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D2828 void OnStateEnter(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateUpdate(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D282C void OnStateUpdate(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateExit(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D2830 void OnStateExit(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateMove(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D2834 void OnStateMove(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateIK(UnityEngine.Animator animator, UnityEngine.AnimatorStateInfo stateInfo, System.Int32 layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D2838 void OnStateIK(::UnityEngine::Animator* animator, ::UnityEngine::AnimatorStateInfo stateInfo, int layerIndex, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateMachineEnter(UnityEngine.Animator animator, System.Int32 stateMachinePathHash, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D283C void OnStateMachineEnter(::UnityEngine::Animator* animator, int stateMachinePathHash, ::UnityEngine::Animations::AnimatorControllerPlayable controller); // public System.Void OnStateMachineExit(UnityEngine.Animator animator, System.Int32 stateMachinePathHash, UnityEngine.Animations.AnimatorControllerPlayable controller) // Offset: 0x18D2840 void OnStateMachineExit(::UnityEngine::Animator* animator, int stateMachinePathHash, ::UnityEngine::Animations::AnimatorControllerPlayable controller); }; // UnityEngine.StateMachineBehaviour #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateEnter // Il2CppName: OnStateEnter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int)>(&UnityEngine::StateMachineBehaviour::OnStateEnter)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateUpdate // Il2CppName: OnStateUpdate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int)>(&UnityEngine::StateMachineBehaviour::OnStateUpdate)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateExit // Il2CppName: OnStateExit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int)>(&UnityEngine::StateMachineBehaviour::OnStateExit)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateExit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMove // Il2CppName: OnStateMove template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int)>(&UnityEngine::StateMachineBehaviour::OnStateMove)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateIK // Il2CppName: OnStateIK template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int)>(&UnityEngine::StateMachineBehaviour::OnStateIK)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateIK", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMachineEnter // Il2CppName: OnStateMachineEnter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, int)>(&UnityEngine::StateMachineBehaviour::OnStateMachineEnter)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateMachinePathHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMachineEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateMachinePathHash}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMachineExit // Il2CppName: OnStateMachineExit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, int)>(&UnityEngine::StateMachineBehaviour::OnStateMachineExit)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateMachinePathHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMachineExit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateMachinePathHash}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateEnter // Il2CppName: OnStateEnter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateEnter)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateUpdate // Il2CppName: OnStateUpdate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateUpdate)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateExit // Il2CppName: OnStateExit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateExit)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateExit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMove // Il2CppName: OnStateMove template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateMove)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateIK // Il2CppName: OnStateIK template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, ::UnityEngine::AnimatorStateInfo, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateIK)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateInfo = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimatorStateInfo")->byval_arg; static auto* layerIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateIK", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateInfo, layerIndex, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMachineEnter // Il2CppName: OnStateMachineEnter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateMachineEnter)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateMachinePathHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMachineEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateMachinePathHash, controller}); } }; // Writing MetadataGetter for method: UnityEngine::StateMachineBehaviour::OnStateMachineExit // Il2CppName: OnStateMachineExit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::StateMachineBehaviour::*)(::UnityEngine::Animator*, int, ::UnityEngine::Animations::AnimatorControllerPlayable)>(&UnityEngine::StateMachineBehaviour::OnStateMachineExit)> { static const MethodInfo* get() { static auto* animator = &::il2cpp_utils::GetClassFromName("UnityEngine", "Animator")->byval_arg; static auto* stateMachinePathHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* controller = &::il2cpp_utils::GetClassFromName("UnityEngine.Animations", "AnimatorControllerPlayable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::StateMachineBehaviour*), "OnStateMachineExit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{animator, stateMachinePathHash, controller}); } };
79.642308
289
0.779253
[ "vector" ]
0885468db49dcd8269d31f989e030c3b1b40e972
1,168
cpp
C++
Clerk/UI/Transactions/TransactionsTagsRender.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
14
2016-11-01T15:48:02.000Z
2020-07-15T13:00:27.000Z
Clerk/UI/Transactions/TransactionsTagsRender.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
29
2017-11-16T04:15:33.000Z
2021-12-22T07:15:42.000Z
Clerk/UI/Transactions/TransactionsTagsRender.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
2
2018-08-15T15:25:11.000Z
2019-01-28T12:49:50.000Z
#include "TransactionsTagsRender.h" TransactionsTagsRender::TransactionsTagsRender() : wxDataViewCustomRenderer("arrstring", wxDATAVIEW_CELL_INERT, wxDVR_DEFAULT_ALIGNMENT) { } TransactionsTagsRender::~TransactionsTagsRender() { } bool TransactionsTagsRender::Render(wxRect rect, wxDC *dc, int state) { int x = rect.GetX(); int y = rect.GetY(); wxFont font = dc->GetFont(); font.SetPointSize(8); dc->SetFont(font); for (unsigned int i = 0; i < _value.Count(); i++) { wxString text = _value[i]; wxSize size = dc->GetTextExtent(text); dc->SetBrush(wxBrush(wxColor(241, 248, 255))); dc->DrawRectangle(x, y + 1, size.GetWidth() + 10, rect.GetHeight() - 2); int offset = (rect.GetHeight() - size.GetHeight()) / 2; dc->SetTextForeground(wxColor(100, 100, 100)); dc->DrawText(text, wxPoint(x + 5, y + offset)); x = x + size.GetWidth() + 15; } return true; } wxSize TransactionsTagsRender::GetSize() const { return wxDefaultSize; } bool TransactionsTagsRender::SetValue(const wxVariant &value) { _value = value.GetArrayString(); return true; } bool TransactionsTagsRender::GetValue(wxVariant &WXUNUSED(value)) const { return true; }
21.236364
136
0.706336
[ "render" ]
088c96039a052220a25880abfc8b67c3cf9e5fc0
5,410
cpp
C++
lib/node_types/esp/src/distance-hcsr04.cpp
WhereIsTheExit/iotempower
9079ff9bc42b6a456bc016d638de0713feb49c62
[ "MIT" ]
null
null
null
lib/node_types/esp/src/distance-hcsr04.cpp
WhereIsTheExit/iotempower
9079ff9bc42b6a456bc016d638de0713feb49c62
[ "MIT" ]
null
null
null
lib/node_types/esp/src/distance-hcsr04.cpp
WhereIsTheExit/iotempower
9079ff9bc42b6a456bc016d638de0713feb49c62
[ "MIT" ]
null
null
null
// hcsr04.cpp // Important to include Functional Interrupt as else it does not allow to // define a class-based (object specific) interrupt #include <FunctionalInterrupt.h> #include "distance-hcsr04.h" void Hcsr04::echo_changed(void) { unsigned long current = micros(); // directly read time to be as precise as possible if(triggered) { if(digitalRead(_echo_pin)) { // this went up -> measure burst start interval_start = current; } else { // is down, so that is the measure burst end interval_end = current; triggered = false; // prevent another trigger measured = true; } } } Hcsr04::Hcsr04(const char* name, uint8_t trigger_pin, uint8_t echo_pin) : Device(name, 10000) { _timeout_us = timeout_us; _echo_pin = echo_pin; _trigger_pin = trigger_pin; add_subdevice(new Subdevice("")); } void Hcsr04::start() { pinMode(_echo_pin, INPUT); // no pullup pinMode(_trigger_pin, OUTPUT); digitalWrite(_trigger_pin, 0); last_triggered = micros()-(IOTEMPOWER_HCSR04_INTERVAL*1000); delay(1); // let port settle attachInterrupt(digitalPinToInterrupt(_echo_pin), [&] () { echo_changed(); }, CHANGE); _started = true; } bool Hcsr04::measure() { unsigned long current = micros(); unsigned long delta = current - last_triggered; // triggering means to pull up the trigger pin for at least 10ms // this triggers an echo to be sent out // when the echo is started to be sent out the echo pin is pulled // up by the hcsr04 until it receives the echo back then that is pulled // down. if(triggered) { if(delta >= _timeout_us) { // timed out -> reset ulog(F("hcrs04 timeout %lu"), current); digitalWrite(_trigger_pin, 0); // set pin back to 0 (should already be) trigger_started = false; triggered = false; measured = false; } } else { // not triggered -> trigger new // Eventually trigger new signal if(!trigger_started) { if(delta >= IOTEMPOWER_HCSR04_INTERVAL*1000) { last_triggered = current; digitalWrite(_trigger_pin,1); // start signal trigger_started = true; } } else { // trigger was started // First we need to send a 10ms signal if(delta >= 10000) { // this should be done now digitalWrite(_trigger_pin, 0); // set pin back to 0 triggered = true; trigger_started = false; } } } if(measured) { delta = interval_end - interval_start; measured = false; // release lock unsigned int d = (unsigned int)(delta*100/582); if(d<=IOTEMPOWER_HCSR04_MAX_DISTANCE) { if(distance_buffer_fill < IOTEMPOWER_HCSR04_BUFFER_SIZE) { // let buffer fill first distance_buffer[distance_buffer_fill] = d; distance_sum += d; distance_buffer_fill ++; } else { // we start returning values, when the buffer is full // add new distance to buffer start distance_sum -= distance_buffer[IOTEMPOWER_HCSR04_BUFFER_SIZE-1]; // this is replaced for(int i=IOTEMPOWER_HCSR04_BUFFER_SIZE-1; i>=1; i--) { distance_buffer[i] = distance_buffer[i-1]; } distance_buffer[0] = d; distance_sum += d; // do some median/average thing over buffer (discard values that are too far off from average) // unsigned long valid_sum = 0; // unsigned int valid_count = 0; // for(int i=IOTEMPOWER_HCSR04_BUFFER_SIZE-1; i>=0; i--) { // unsigned int d = distance_buffer[i]; // if(abs(d * IOTEMPOWER_HCSR04_BUFFER_SIZE - distance_sum) // <= IOTEMPOWER_HCSR04_BUFFER_SIZE*IOTEMPOWER_HCSR04_MAX_DISTANCE / 5) { // less than 20% derivation from average // valid_sum += d; // valid_count ++; // } // } // if(valid_count > IOTEMPOWER_HCSR04_BUFFER_SIZE/2) { // d = (valid_sum + valid_count/2) / valid_count; // real median unsigned int median_buffer[IOTEMPOWER_HCSR04_BUFFER_SIZE]; for(int i=0; i<IOTEMPOWER_HCSR04_BUFFER_SIZE; i++) { int j; for(j=i; j>0; j--) { // swap it down to right position if(distance_buffer[i]<median_buffer[j-1]) median_buffer[j] = median_buffer[j-1]; // make space and move up else break; } median_buffer[j]=distance_buffer[i]; // add at right position } d = median_buffer[IOTEMPOWER_HCSR04_BUFFER_SIZE/2]; if(measured_value().empty() || abs(measured_value().as_int() - d) >= _precision ) { measured_value().from(d); return true; } } // endif buffer is filled } // endif under max distance } return false; // no new value available }
41.615385
138
0.556007
[ "object" ]
08927ecd5922487697eae9a575134543dc703c6d
254,120
cpp
C++
src/legup_io_patch/GenerateRTL.cpp
nefrock/LeFlow
6ac21fcfc2108fb163d3e41c41bbbd197a721e8e
[ "MIT" ]
497
2018-07-22T06:51:16.000Z
2022-03-06T17:53:27.000Z
src/legup_io_patch/GenerateRTL.cpp
nefrock/LeFlow
6ac21fcfc2108fb163d3e41c41bbbd197a721e8e
[ "MIT" ]
38
2018-08-14T08:49:29.000Z
2022-02-16T23:52:31.000Z
src/legup_io_patch/GenerateRTL.cpp
nefrock/LeFlow
6ac21fcfc2108fb163d3e41c41bbbd197a721e8e
[ "MIT" ]
92
2018-07-23T02:53:59.000Z
2022-03-17T14:44:53.000Z
//===-- GenerateRTL.cpp -----------------------------------------*- C++ -*-===// // // This file is distributed under the LegUp license. See LICENSE for details. // //===----------------------------------------------------------------------===// // // This file implements the GenerateRTL object // //===----------------------------------------------------------------------===// #include "Allocation.h" #include "GenerateRTL.h" #include "BipartiteWeightedMatchingBinding.h" #include "PatternBinding.h" #include "SchedulerDAG.h" #include "SDCScheduler.h" #include "LegupPass.h" #include "LegupConfig.h" #include "Ram.h" #include "utils.h" #include "RTL.h" #include "Debug.h" #include "llvm/Pass.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/IR/ValueSymbolTable.h" #include "llvm/IR/Metadata.h" #include <sstream> #include <fstream> #include <sstream> #include <cstdlib> #include "llvm/Support/FileSystem.h" #define DEBUG_TYPE "LegUp:GenerateRTL" using namespace llvm; using namespace legup; namespace legup { void GenerateRTL::updateOperationUsage( std::map<std::string, int> &_OperationUsage) { for (std::map<std::string, int>::iterator i = OperationUsageFunction.begin(), e = OperationUsageFunction.end(); i != e; ++i) { std::string OpName = i->first; if (_OperationUsage.find(OpName) == _OperationUsage.end()) { _OperationUsage[OpName] = i->second; } else { _OperationUsage[OpName] += i->second; } } } void GenerateRTL::setOperationUsageFunction(Instruction *instr) { //mem related instr should not be counted //as it isn't an "operation" with an fmax/area. if (isMem(instr)) return; std::string OpName = LEGUP_CONFIG->getOpNameFromInst(instr, alloc); if (OperationUsageFunction.find(OpName) == OperationUsageFunction.end()) { OperationUsageFunction[OpName] = 1; } else { OperationUsageFunction[OpName] += 1; } } std::string GenerateRTL::verilogName(const Value &val) { return verilogName(&val); } // return the unique Verilog identifier for val std::string GenerateRTL::verilogName(const Value *val) { // keep global updated return alloc->verilogNameFunction(val, Fp); } // get ram from a GetElementPtrInst, or getElementPtr constant RAM* GenerateRTL::getRam(Value *op) { const Value *ram; DEBUG(errs() << "getRam: " << *op << "\n"); ram = op; if (const User *U = dyn_cast<User>(op)) { if (U->getNumOperands() > 1) { ram = U->getOperand(0); } } return alloc->getRAM(ram); } //NC changes... wrapper function RTLSignal *GenerateRTL::getGEP(State *state, User *GEP) { int offsetValue = 0; return getGEP(state, GEP, offsetValue); } // get ram address from a GetElementPtrInst, or getElementPtr constant RTLSignal *GenerateRTL::getGEP(State *state, User *GEP, int &value) { int baseValue = 0; RTLSignal *basePointer = getOp(state, GEP->getOperand(0), baseValue); //RTLWidth w("`MEMORY_CONTROLLER_ADDR_SIZE-1"); //basePointer->setWidth(w); int offsetValue = 0; RTLSignal *offset = getGEPOffset(state, GEP, offsetValue); if (!offset) { value = baseValue; return basePointer; } // add offset to base pointer RTLOp *gep; if (LEGUP_CONFIG->getParameterInt("GROUP_RAMS") && LEGUP_CONFIG->getParameterInt("GROUP_RAMS_SIMPLE_OFFSET") && basePointer->isConst()) { // We can OR these cases where basePointer is a TAG: // gep = (`TAG_g_mem | (4 * offset)); gep = rtl->addOp(RTLOp::Or); } else { gep = rtl->addOp(RTLOp::Add); } value = baseValue + offsetValue; gep->setOperand(0, basePointer); gep->setOperand(1, offset); return gep; } //NC changes... wrapper RTLSignal *GenerateRTL::getGEPOffset(State *state, User *GEP) { int value = 0; return getGEPOffset(state, GEP, value); } RTLSignal *GenerateRTL::getGEPOffset(State *state, User *GEP, int &value) { RTLSignal *gepOffset = NULL; gep_type_iterator GTI = gep_type_begin(GEP); for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e; ++i, ++GTI) { Value *Op = *i; int offsetValue = 0; RTLSignal *offset = getByteOffset(state, Op, GTI, offsetValue); if (!offset) continue; if (!gepOffset) { gepOffset = offset; value = offsetValue; } else { RTLOp *newGepOffset = rtl->addOp(RTLOp::Add); newGepOffset->setOperand(0, gepOffset); newGepOffset->setOperand(1, offset); int newGepOffsetValue = value + offsetValue; RTLWidth w("`MEMORY_CONTROLLER_ADDR_SIZE-1"); gepOffset->setWidth(w); gepOffset = newGepOffset; value = newGepOffsetValue; } } return gepOffset; } //NC changes... wrapper RTLSignal *GenerateRTL::getByteOffset(State *state, Value *Op, gep_type_iterator GTI) { int offsetValue = 0; return getByteOffset(state, Op, GTI, offsetValue); } RTLSignal *GenerateRTL::getByteOffset(State *state, Value *Op, gep_type_iterator GTI, int &offsetValue) { // Build a mask for high order bits. const DataLayout* TD = alloc->getDataLayout(); unsigned IntPtrWidth = TD->getPointerSizeInBits(); uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth); // apply mask uint64_t Size = TD->getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask; RTLWidth w("`MEMORY_CONTROLLER_ADDR_SIZE-1"); RTLOp *offset = rtl->addOp(RTLOp::Mul); offset->setOperand(0, rtl->addConst(utostr(Size), w)); offsetValue = Size; if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) { if (OpC->isZero()) { offsetValue = 0; return NULL; } // Handle a struct index, which adds its field offset. if (StructType *STy = dyn_cast<StructType>(*GTI)) { offsetValue = TD->getStructLayout(STy)->getElementOffset( OpC->getZExtValue()); return rtl->addConst( utostr( TD->getStructLayout(STy)->getElementOffset( OpC->getZExtValue())), w); } offset->setOperand(1, getConstantSignal(OpC)); offsetValue *= OpC->getValue().getSExtValue(); } else { int op1Value = 0; offset->setOperand(1, getOp(state, Op, op1Value)); offsetValue *= op1Value; } return offset; } bool GenerateRTL::fromSameState(Value *v, State *state) { // never gets called assert(0); errs() << "fromSameState: " << *v << "\n"; Instruction *operand = dyn_cast<Instruction>(v); if (!operand || isa<AllocaInst>(operand)) { return false; } errs() << "fromSameState: " << *operand << "\n"; //if (isa<LoadInst>(operand)) return false; if (sched->getFSM(Fp)->getEndState(operand) == state) { return true; } else { return false; } } // does the value 'v' finish in another state? bool GenerateRTL::fromOtherState(Value *v, State *state) { Instruction *operand = dyn_cast<Instruction>(v); if (!operand) return false; if (isa<PHINode>(operand)) return true; if (sched->getFSM(Fp)->getEndState(operand) != state) { return true; } else { return false; } } bool GenerateRTL::usedSameState(Value *instr, State *state) { // never called assert(0); for (Value::user_iterator i = instr->user_begin(), e = instr->user_end(); i != e; ++i) { Instruction *use = dyn_cast<Instruction>(*i); if (!use) continue; if (sched->getFSM(Fp)->getEndState(use) == state) { return true; } } return false; } // is the value 'val' used in a state other than 'state'? bool GenerateRTL::usedAcrossStates(Value *val, State *state) { for (Value::user_iterator i = val->user_begin(), e = val->user_end(); i != e; ++i) { Instruction *use = dyn_cast<Instruction>(*i); if (!use) continue; if (sched->getFSM(Fp)->getEndState(use) != state) { return true; } } return false; } // like getOp but instead of returning a wire, // returns a register RTLSignal *GenerateRTL::getOpReg(Value *v, State* state) { if (rtl->exists(verilogName(v) + "_reg")) { RTLSignal *reg = rtl->find(verilogName(v) + "_reg"); return reg; } else { return getOp(state, v); } } void GenerateRTL::createMultiPumpMultiplierFU(Instruction *AxB, Instruction *CxD) { // create multipump /* multipump multipump_inst ( .clk( clk ), .clk2x( clk2x ), .clk1x_follower( clk1x_follower ), .inA( main_1_6_reg_wire ), .inB( 32'd12 ), .outAxB( main_encode_exit__crit_edge_phitmp_wire ), .inC( main_1_5_reg_wire ), .inD( -32'd44 ), .outCxD( main_encode_exit__crit_edge_phitmp29_wire ) ); */ // registers retain their value so we just need // to connect up the divider RTLModule *m = rtl->addModule("multipump", "multipump_" + verilogName(AxB)); // add a comment std::string tmp; raw_string_ostream Out(tmp); Out << "/* " << getValueStr(AxB) << "\n" << getValueStr(CxD) << "*/"; m->setBody(Out.str()); m->addIn("clk")->connect(rtl->find("clk")); m->addIn("clk2x")->connect(rtl->find("clk2x")); m->addIn("clk1x_follower")->connect(rtl->find("clk1x_follower")); Value *vop0 = AxB->getOperand(0); Value *vop1 = AxB->getOperand(1); // in many cases for a 64-bit multiply, only 32-bit operands are required unsigned sizeAxB = max(MBW->getMinBitwidth(vop0), MBW->getMinBitwidth(vop1)); vop0 = CxD->getOperand(0); vop1 = CxD->getOperand(1); // in many cases for a 64-bit multiply, only 32-bit operands are required unsigned sizeCxD = max(MBW->getMinBitwidth(vop0), MBW->getMinBitwidth(vop1)); assert(sizeAxB == sizeCxD); //RTLWidth width(AxB->getType()); RTLWidth width(sizeAxB); MultipumpOperation &multipumpAxB = multipumpOperations[AxB]; RTLSignal *inA_wire = rtl->addWire(multipumpAxB.op0, width); m->addIn("inA")->connect(inA_wire); RTLSignal *inB_wire = rtl->addWire(multipumpAxB.op1, width); m->addIn("inB")->connect(inB_wire); RTLSignal *outAxB_actual = rtl->addWire( multipumpAxB.name + "_outAxB_actual", RTLWidth(sizeAxB * 2)); m->addOut("outAxB")->connect(outAxB_actual); RTLOp *trunc = rtl->addOp(RTLOp::Trunc); trunc->setCastWidth(getBitWidth(AxB->getType())); trunc->setOperand(0, outAxB_actual); RTLSignal *outAxB = rtl->addWire(multipumpAxB.out, trunc->getWidth()); outAxB->connect(trunc); MultipumpOperation &multipumpCxD = multipumpOperations[CxD]; RTLSignal *outCxD_actual = rtl->addWire( multipumpCxD.name + "_outCxD_actual", RTLWidth(sizeAxB * 2)); m->addOut("outCxD")->connect(outCxD_actual); RTLOp *trunc2 = rtl->addOp(RTLOp::Trunc); trunc2->setCastWidth(getBitWidth(CxD->getType())); trunc2->setOperand(0, outCxD_actual); RTLSignal *outCxD = rtl->addWire(multipumpCxD.out, trunc2->getWidth()); outCxD->connect(trunc2); RTLSignal *en = rtl->addWire("lpm_mult_" + verilogName(CxD) + "_en"); m->addIn("clken")->connect(en); RTLSignal *inC_wire = rtl->addWire(multipumpCxD.op0, width); m->addIn("inC")->connect(inC_wire); RTLSignal *inD_wire = rtl->addWire(multipumpCxD.op1, width); m->addIn("inD")->connect(inD_wire); //m->addParam("size", utostr(getBitWidth(AxB->getType()))); m->addParam("size", utostr(sizeAxB)); if (sizeAxB < getBitWidth(AxB->getType()) && isa<SExtInst>(vop0) && isa<SExtInst>(vop1)) { m->addParam("sign", "\"SIGNED\""); } else { m->addParam("sign", "\"UNSIGNED\""); } } RTLSignal *GenerateRTL::createMulFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1) { /* lpm_mult lpm_mult_component ( .clock (clk2x), .dataa (dataa_wire), .datab (datab_wire), .result (dsp_out), .aclr (1'b0), .clken (1'b1), .sum (1'b0)); defparam lpm_mult_component.lpm_hint = "DEDICATED_MULTIPLIER_CIRCUITRY=YES,MAXIMIZE_SPEED=5", lpm_mult_component.lpm_representation = "SIGNED", lpm_mult_component.lpm_type = "LPM_MULT", lpm_mult_component.lpm_pipeline = 0, lpm_mult_component.lpm_widtha = 32, lpm_mult_component.lpm_widthb = 32, lpm_mult_component.lpm_widthp = 64; */ // registers retain their value so we just need // to connect up the divider RTLModule *d = rtl->addModule("lpm_mult", "lpm_mult_" + verilogName(instr)); // add a comment std::string tmp; raw_string_ostream Out(tmp); Out << "/* " << getValueStr(instr) << "*/"; d->setBody(Out.str()); Value *vop0 = instr->getOperand(0); Value *vop1 = instr->getOperand(1); const Type *T = vop0->getType(); unsigned origSize = T->getPrimitiveSizeInBits(); // in many cases for a 64-bit multiply, only 32-bit operands are required unsigned size = max(MBW->getMinBitwidth(vop0), MBW->getMinBitwidth(vop1)); std::string sign = "\"UNSIGNED\""; if (size < origSize) { RTLOp *trunc_op0 = rtl->addOp(RTLOp::Trunc); trunc_op0->setCastWidth(size); trunc_op0->setOperand(0, op0); RTLSignal *a = rtl->addWire("lpm_mult_" + verilogName(instr) + "_a", RTLWidth(size)); a->connect(trunc_op0); RTLOp *trunc_op1 = rtl->addOp(RTLOp::Trunc); trunc_op1->setCastWidth(size); trunc_op1->setOperand(0, op1); RTLSignal *b = rtl->addWire("lpm_mult_" + verilogName(instr) + "_b", RTLWidth(size)); b->connect(trunc_op1); if (isa<SExtInst>(vop0) && isa<SExtInst>(vop1)) { sign = "\"SIGNED\""; } d->addIn("dataa")->connect(a); d->addIn("datab")->connect(b); } else { d->addIn("dataa")->connect(op0); d->addIn("datab")->connect(op1); } RTLSignal *FU_actual = rtl->addWire( "lpm_mult_" + verilogName(instr) + "_out_actual", RTLWidth(size * 2)); d->addOut("result")->connect(FU_actual); RTLSignal *FU = rtl->addWire("lpm_mult_" + verilogName(instr) + "_out", RTLWidth(origSize)); RTLOp *trunc = rtl->addOp(RTLOp::Trunc); trunc->setCastWidth(FU->getWidth()); trunc->setOperand(0, FU_actual); FU->connect(trunc); RTLSignal *en = rtl->addWire(getEnableName(instr)); unsigned pipelineStages = Scheduler::getNumInstructionCycles(instr); if (pipelineStages == 0) { RTLSignal *NONE = rtl->addConst(""); d->addIn("clock")->connect(NONE); } else { d->addIn("clock")->connect(rtl->find("clk")); } d->addIn("aclr")->connect(ZERO); d->addIn("clken")->connect(en); d->addIn("sum")->connect(ZERO); d->addParam("lpm_pipeline", utostr(pipelineStages)); // multiplier input sizes must be the same in LLVM d->addParam("lpm_widtha", utostr(size)); d->addParam("lpm_widthb", utostr(size)); // product width must be double d->addParam("lpm_widthp", utostr(size * 2)); d->addParam("lpm_representation", sign); //lpm_mult_component.lpm_hint = "DEDICATED_MULTIPLIER_CIRCUITRY=YES,MAXIMIZE_SPEED=5", d->addParam("lpm_hint", "\"\""); return FU; } unsigned GenerateRTL::getOpSizeShared(Instruction *instr, RTLSignal *op, unsigned opIndex) { assert( (opIndex == 0 || opIndex == 1) && "opIndex has to be 0 or 1 since instr should be a div or rem"); unsigned minSize = op->getWidth().numBits(rtl, alloc); unsigned maxMinSize = minSize; std::string fuId = ""; if (this->binding->existsBindingInstrFU(instr)) fuId = this->binding->getBindingInstrFU(instr); if (fuId != "" && instructionsAssignedToFU.find(fuId) != instructionsAssignedToFU.end()) { for (std::set<Instruction *>::iterator i = instructionsAssignedToFU[fuId].begin(), ie = instructionsAssignedToFU[fuId].end(); i != ie; ++i) { Instruction *thisInstr = *i; RTLSignal *thisSig = rtl->findExists( verilogName(thisInstr->getOperand(opIndex))); if (thisSig) maxMinSize = thisSig->getWidth().numBits(rtl, alloc); else if (USE_MB && MBW->bitwidthIsKnown(thisInstr->getOperand(opIndex))) { maxMinSize = MBW->getMinBitwidth( thisInstr->getOperand(opIndex)); } else continue; if (maxMinSize > minSize) { minSize = maxMinSize; } } } return minSize; } RTLWidth GenerateRTL::getOutSizeShared(Instruction *instr) { RTLWidth w; if (USE_MB && MBW->bitwidthIsKnown(instr)) { w = RTLWidth(instr, MBW); unsigned size = MBW->getMinBitwidth(instr); std::string fuId = ""; if (this->binding->existsBindingInstrFU(instr)) fuId = this->binding->getBindingInstrFU(instr); if (fuId != "" && instructionsAssignedToFU.find(fuId) != instructionsAssignedToFU.end()) { for (std::set<Instruction *>::iterator i = instructionsAssignedToFU[fuId].begin(), ie = instructionsAssignedToFU[fuId].end(); i != ie; ++i) { Instruction *thisInstr = *i; unsigned thisMinSize = MBW->getMinBitwidth(thisInstr); if (thisMinSize > size) { size = thisMinSize; w = RTLWidth(thisInstr, MBW); } } } } else { w = RTLWidth(instr->getType()); } return w; } // Instantiate a pipelined divider module RTLSignal *GenerateRTL::createDivFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1) { std::set<Instruction *>::iterator instIter; RTLModule *d; // registers retain their value so we just need // to connect up the divider // We support TWO styles different divider implementations: // 1) Altera's LPM divider // 2) A generic divider from opencores.org // We are keeping both options available, because the Altera one // seems to use less Si area std::map<std::string, std::string> nm; // port name map nm["width_d"] = "width_d"; nm["width_n"] = "width_n"; nm["sign_d"] = "sign_d"; nm["sign_n"] = "sign_n"; nm["quotient"] = "quotient"; nm["remain"] = "remain"; nm["clock"] = "clock"; nm["clken"] = "clken"; nm["numer"] = "numer"; nm["denom"] = "denom"; nm["stages"] = "stages"; if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "generic") { // Figure out if this is a signed or unsigned unit // For the generic case, there are separate Verilog modules for // signed vs unsigned. For the Altera case, there's only a single module. if (instr->getOpcode() == Instruction::SDiv || instr->getOpcode() == Instruction::SRem) { nm["module"] = "div_signed"; } else { nm["module"] = "div_unsigned"; } } else { assert (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "altera"); nm["module"] = "lpm_divide"; nm["width_d"] = "lpm_widthd"; nm["width_n"] = "lpm_widthn"; nm["sign_d"] = "lpm_drepresentation"; nm["sign_n"] = "lpm_nrepresentation"; nm["stages"] = "lpm_pipeline"; } d = rtl->addModule(nm["module"], nm["module"] + "_" + verilogName(instr)); // add a comment std::string tmp; raw_string_ostream Out(tmp); Out << "/* " << getValueStr(instr) << "*/"; d->setBody(Out.str()); RTLSignal *FU = rtl->addWire("lpm_divide_" + verilogName(instr) + "_temp_out", RTLWidth(instr->getType())); RTLSignal *unused = rtl->addWire(verilogName(instr) + "_unused", RTLWidth(instr->getType())); if (isDiv(instr)) { d->addOut(nm["quotient"])->connect(FU); d->addOut(nm["remain"])->connect(unused); } else { assert(isRem(instr)); d->addOut(nm["quotient"])->connect(unused); d->addOut(nm["remain"])->connect(FU); } RTLSignal *en = rtl->addWire(getEnableName(instr)); d->addIn(nm["clock"])->connect(rtl->find("clk")); if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "altera") d->addIn("aclr")->connect(ZERO); d->addIn(nm["clken"])->connect(en); unsigned pipelineStages = Scheduler::getNumInstructionCycles(instr); if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "generic") { // janders note the "-1" for generic divider // This is because in the generic divider, if the width is 16, it actually takes 17 cycles to complete its work. pipelineStages = pipelineStages - 1; } if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "altera") { // Check whether this divider should be multi-cycled or pipelined if (LEGUP_CONFIG->getParameterInt("MULTI_CYCLE_REMOVE_REG_DIVIDERS")) { // Will insert multi-cycle constraints for this divider after binding alloc->add_multicycled_divider(instr); } else { } } else { if (LEGUP_CONFIG->getParameterInt("MULTI_CYCLE_REMOVE_REG_DIVIDERS")) { errs() << "Generic dividers not supported with MULTI_CYCLE_REMOVE_REG_DIVIDERS set.\n"; exit(-1); } } d->addParam(nm["stages"], utostr(pipelineStages)); // numerator/denominator sizes must be the same in LLVM std::string sign = "\"UNSIGNED\""; if (instr->getOpcode() == Instruction::SDiv || instr->getOpcode() == Instruction::SRem) sign = "\"SIGNED\""; //Get the size of the numerator unsigned size = op0->getWidth().numNativeBits(rtl, alloc); unsigned minSize = getOpSizeShared(instr, op0, 0); if (USE_MB) { bool op0Signed = op0->getWidth().getSigned(); op0->setWidth(RTLWidth(minSize, size, op0Signed)); if (sign == "\"SIGNED\"" && !op0Signed && !(size == minSize)) { minSize++; } size = min(minSize, size); if (size == 1) errs() << "minSize:" << utostr(minSize) << "\n"; } d->addIn(nm["numer"], RTLWidth(size))->connect(op0); FU->setWidth(RTLWidth(size)); if (!isDiv(instr)) unused->setWidth(RTLWidth(size)); d->addParam(nm["width_n"], utostr(size)); size = instr->getOperand(1)->getType()->getPrimitiveSizeInBits(); minSize = getOpSizeShared(instr, op1, 1); if (USE_MB) { bool op1Signed = op1->getWidth().getSigned(); op1->setWidth(RTLWidth(minSize, size, op1Signed)); if (sign == "\"SIGNED\"" && !op1Signed && !(size == minSize)) { minSize++; } size = min(size, minSize); } d->addIn(nm["denom"], RTLWidth(size))->connect(op1); if (isDiv(instr)) unused->setWidth(RTLWidth(size)); else FU->setWidth(RTLWidth(size)); d->addParam(nm["width_d"], utostr(size)); if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") != "generic") { d->addParam(nm["sign_d"], sign); d->addParam(nm["sign_n"], sign); } if (LEGUP_CONFIG->getParameter("DIVIDER_MODULE") == "altera") { d->addParam("lpm_hint", "\"LPM_REMAINDERPOSITIVE=FALSE\""); } RTLWidth w = getOutSizeShared(instr); RTLSignal *FUout = rtl->addWire("lpm_divide_" + verilogName(instr) + "_out",w); FUout->connect(FU); return FUout; } RTLSignal *GenerateRTL::createFPFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1, unsigned opCode) { // registers retain their value so we just need // to connect up the FP cores int width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); assert(width == 32 || width == 64); std::string name; switch (opCode) { case Instruction::FDiv: name = "altfp_divider"; break; case Instruction::FAdd: name = "altfp_adder"; break; case Instruction::FSub: name = "altfp_subtractor"; break; case Instruction::FMul: name = "altfp_multiplier"; break; } if (width == 64) { name = name + utostr(width); } return createFP_FU_Helper(name, instr, op0, op1, /*fu_module=*/NULL); } RTLSignal *GenerateRTL::createFPFUUnary(Instruction *instr, RTLSignal *op0, unsigned opCode) { int width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); std::string name; switch (opCode) { case Instruction::FPTrunc: name = "altfp_truncate"; break; case Instruction::FPExt: name = "altfp_extend"; break; case Instruction::FPToSI: name = "altfp_fptosi"; break; case Instruction::SIToFP: name = "altfp_sitofp"; CastInst *I = dyn_cast<CastInst>(instr); width = I->getDestTy()->getPrimitiveSizeInBits(); break; } assert(width == 32 || width == 64); if (!(isa<FPTruncInst>(instr) || isa<FPExtInst>(instr))) { // trunc/ext do not spec width name = name + utostr(width); } return createFP_FU_Helper(name, instr, op0, /*op1*/NULL, /*fu_module=*/NULL); } RTLSignal *GenerateRTL::createFCmpFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1) { int width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); assert(width == 32 || width == 64); int latency = Scheduler::getNumInstructionCycles(instr); std::string name = "altfp_compare" + utostr(width) + "_" + utostr(latency); RTLModule *d = rtl->addModule(name, name + "_" + verilogName(instr)); RTLSignal *FU = createFP_FU_Helper(name, instr, op0, op1, /*fu_module=*/d); RTLSignal *unused = rtl->addWire(verilogName(instr) + "_unused", RTLWidth(instr->getType())); if (const FCmpInst *cmp = dyn_cast<FCmpInst>(instr)) { switch (cmp->getPredicate()) { case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ: d->addOut("aeb")->connect(FU); d->addOut("aneb")->connect(unused); d->addOut("alb")->connect(unused); d->addOut("aleb")->connect(unused); d->addOut("agb")->connect(unused); d->addOut("ageb")->connect(unused); d->addOut("unordered")->connect(unused); break; case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE: d->addOut("aeb")->connect(unused); d->addOut("aneb")->connect(FU); d->addOut("alb")->connect(unused); d->addOut("aleb")->connect(unused); d->addOut("agb")->connect(unused); d->addOut("ageb")->connect(unused); d->addOut("unordered")->connect(unused); break; case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT: d->addOut("aeb")->connect(unused); d->addOut("aneb")->connect(unused); d->addOut("alb")->connect(FU); d->addOut("aleb")->connect(unused); d->addOut("agb")->connect(unused); d->addOut("ageb")->connect(unused); d->addOut("unordered")->connect(unused); break; case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE: d->addOut("aeb")->connect(unused); d->addOut("aneb")->connect(unused); d->addOut("alb")->connect(unused); d->addOut("aleb")->connect(FU); d->addOut("agb")->connect(unused); d->addOut("ageb")->connect(unused); d->addOut("unordered")->connect(unused); break; case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT: d->addOut("aeb")->connect(unused); d->addOut("aneb")->connect(unused); d->addOut("alb")->connect(unused); d->addOut("aleb")->connect(unused); d->addOut("agb")->connect(FU); d->addOut("ageb")->connect(unused); d->addOut("unordered")->connect(unused); break; case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE: d->addOut("aeb")->connect(unused); d->addOut("aneb")->connect(unused); d->addOut("alb")->connect(unused); d->addOut("aleb")->connect(unused); d->addOut("agb")->connect(unused); d->addOut("ageb")->connect(FU); d->addOut("unordered")->connect(unused); break; default: llvm_unreachable("Illegal FCmp predicate"); } } return FU; } // this helper function creates an RTLModule named fu_name (unless you // pass in an RTLModule *fu_module). Connects the dataa and datab // ports to op0 and op1 respectively. Also creates the clock enable // signals. Arguments: op1 and fu_module are optional (set to NULL to ignore // them) RTLSignal *GenerateRTL::createFP_FU_Helper(std::string fu_name, Instruction *instr, RTLSignal *op0, RTLSignal *op1, RTLModule *fu_module) { // registers retain their value so we just need // to connect up the FP cores RTLSignal *FU = rtl->addWire(fu_name + "_" + verilogName(instr) + "_out", RTLWidth(instr->getType())); // module is specified for altfp_compare which has special output ports if (fu_module == NULL) { int latency = Scheduler::getNumInstructionCycles(instr); fu_name = fu_name + "_" + utostr(latency); fu_module = rtl->addModule(fu_name, fu_name + "_" + verilogName(instr)); fu_module->addOut("result")->connect(FU); } // add a comment std::string tmp; raw_string_ostream Out(tmp); Out << "/* " << getValueStr(instr) << "*/"; fu_module->setBody(Out.str()); // enable signal create_fu_enable_signals(instr); RTLSignal *en = rtl->addWire(getEnableName(instr)); fu_module->addIn("dataa", RTLWidth(op0->getWidth().numNativeBits(rtl, alloc))) ->connect(op0); if (op1) { fu_module->addIn("datab", RTLWidth(op1->getWidth().numNativeBits(rtl, alloc))) ->connect(op1); } fu_module->addIn("clock")->connect(rtl->find("clk")); fu_module->addIn("clk_en")->connect(en); return FU; } // create a functional unit (fu) module instantiation for the given // instruction and input operand signals RTLSignal *GenerateRTL::createFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1) { if (isDiv(instr) || isRem(instr)) { return createDivFU(instr, op0, op1); } else if (EXPLICIT_LPM_MULTS && alloc->useExplicitDSP(instr)) { return createMulFU(instr, op0, op1); } //If the instruction is one of the floating point operation, call FP create module //with opCode (unsigned) as additional parameter unsigned opCode = instr->getOpcode(); switch (instr->getOpcode()) { case Instruction::FAdd: case Instruction::FSub: case Instruction::FMul: case Instruction::FDiv: return createFPFU(instr, op0, op1, opCode); case Instruction::FCmp: return createFCmpFU(instr, op0, op1); case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::FPToSI: case Instruction::SIToFP: return createFPFUUnary(instr, op0, opCode); } // fixes to match gcc: case where shifting by more than the number // of bits in the number // should probably ignore this case because it's undefined in the C // standard. if (isLogicalShift(instr)) { RTLOp *truncate = rtl->addOp(RTLOp::Rem); const Type *T = instr->getOperand(1)->getType(); unsigned size = T->getPrimitiveSizeInBits(); truncate->setOperand(0, op1); truncate->setOperand(1, rtl->addConst(utostr(size), size)); op1 = truncate; } if (op1Signed(instr)) { RTLOp *sext = rtl->addOp(RTLOp::SExt); //sext->setCastWidth(w); RTLWidth w = op0->getWidth(); //if adding keyword $signed to an unsigned number, we need to create a temp //signal that pads the bitwidth with a 0, to make sure $signed doesn't accidentally //convert an unsigned number to a signed number if (!w.getSigned() && w.numBits(rtl, alloc) < w.numNativeBits(rtl, alloc)) { w = RTLWidth(w.numBits(rtl, alloc) + 1, w.numNativeBits(rtl, alloc), false); RTLSignal *op0_old = op0; op0 = rtl->addWire(verilogName(instr) + "_op0_temp", w); op0->connect(op0_old); } sext->setCastWidth(w); sext->setOperand(0, op0); op0 = sext; } if (op2Signed(instr)) { RTLOp *sext = rtl->addOp(RTLOp::SExt); //sext->setCastWidth(w); RTLWidth w = op1->getWidth(); //if adding keyword $signed to an unsigned number, we need to create a temp //signal that pads the bitwidth with a 0, to make sure $signed doesn't accidentally //convert an unsigned number to a signed number if (!w.getSigned() && w.numBits(rtl, alloc) < w.numNativeBits(rtl, alloc)) { w = RTLWidth(w.numBits(rtl, alloc) + 1, w.numNativeBits(rtl, alloc), false); RTLSignal *op1_old = op1; op1 = rtl->addWire(verilogName(instr) + "_op1__temp", w); op1->connect(op1_old); } sext->setCastWidth(w); sext->setOperand(0, op1); op1 = sext; } RTLOp *FUop = rtl->addOp(instr); FUop->setOperand(0, op0); FUop->setOperand(1, op1); RTLWidth outWidth = RTLWidth(instr, MBW); FUop->setWidth(outWidth); RTLSignal *FUoutput = FUop; // FUop->setWidth(RTLWidth(MBW->getMinBitwidth(instr))); // FUop->setNativeWidth(RTLWidth(instr->getType())); // if(MBW->isSigned(instr)) FUop->setSigned(true); // if(MBW->bitwidthIsKnown(instr) && MBW->isSigned(instr)) FUop->getWidth().setSigned(true); // FUop->getWidth().setSigned(MBW->isSigned(instr)); int latency = Scheduler::getNumInstructionCycles(instr); if (latency > 0 && !LEGUP_CONFIG->does_flow_support_multicycle_paths()) { // add flops for user specified set_operation_latency // this is for adders/subtractors/shifts - functional units without // lpm_* module instantiations RTLSignal *en = rtl->addWire(getEnableName(instr)); RTLOp *enCond = rtl->addOp(RTLOp::EQ); enCond->setOperand(0, en); enCond->setOperand(1, ONE); // create shift register RTLSignal *prev_stage_reg = NULL; for (int i = 0; i < latency; i++) { RTLSignal *stage_reg = rtl->addReg( verilogName(instr) + "_stage" + utostr(i) + "_reg", outWidth); stage_reg->setCheckXs(false); RTLSignal *driver = prev_stage_reg; if (prev_stage_reg == NULL) { // first register is driven by FU wire driver = FUoutput; } stage_reg->addCondition(enCond, driver, instr); prev_stage_reg = stage_reg; } FUoutput = prev_stage_reg; } assert(FUoutput); return FUoutput; } void GenerateRTL::visitReturnInst(ReturnInst &I) { // don't print anything for void return if (I.getNumOperands() != 0) { RTLSignal *return_val = rtl->find("return_val"); connectSignalToDriverInState( return_val, getOp(this->state, I.getOperand(0)), this->state, &I); } PropagatingSignals *ps = alloc->getPropagatingSignals(); bool shouldConnectMemorySignals = ps->functionUsesMemory(Fp->getName()); if (shouldConnectMemorySignals) { // finish = 1 when waitrequest == 0 RTLOp *wait = rtl->addOp(RTLOp::EQ); wait->setOperand(0, rtl->find("memory_controller_waitrequest")); wait->setOperand(1, ZERO); connectSignalToDriverInState(rtl->find("finish"), wait, this->state, &I); } else { connectSignalToDriverInState(rtl->find("finish"), ONE, this->state, &I); } } void GenerateRTL::visitUnreachableInst(UnreachableInst &I) { } std::string getPipelineLabel(const BasicBlock *BB) { const TerminatorInst *TI = BB->getTerminator(); static std::map<std::string, int> numLabels; static std::map<const BasicBlock *, std::string> bbUniqueLabel; std::string label = getMetadataStr(TI, "legup.label"); if (bbUniqueLabel.find(BB) == bbUniqueLabel.end()) { numLabels[label]++; bbUniqueLabel[BB] = label + "_" + utostr(numLabels[label]); } return bbUniqueLabel[BB]; } Instruction *getInductionVar(BasicBlock *BB) { Instruction *inductionVar = NULL; for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { if (getMetadataInt(I, "legup.canonical_induction")) { inductionVar = I; break; } } assert(inductionVar); return inductionVar; } RTLOp *GenerateRTL::getPipelineStateCondition(RTLSignal *signal, Instruction *instr, PIPELINE_STATE pipelineState) { bool PIPELINED = isPipelined(instr); std::string label = ""; int II = 0; if (!PIPELINED) return 0; BasicBlock *BB = instr->getParent(); Instruction *inductionVar = getInductionVar(BB); label = getPipelineLabel(BB); II = getPipelineII(BB); // induction variable signals are hard coded for now if (signal == rtl->find(verilogName(inductionVar) + "_reg") || instr == inductionVar) { return 0; } TerminatorInst *TI = BB->getTerminator(); if (instr == TI->getOperand(0)) { signal->connect(rtl->find(label + "_pipeline_finish")); return 0; } int startTime = getMetadataInt(instr, "legup.pipeline.start_time"); int timeAvail = getMetadataInt(instr, "legup.pipeline.avail_time"); int expectedAvailTime = startTime + Scheduler::getNumInstructionCycles((Instruction*) instr); int time = timeAvail; if (pipelineState == INPUT_READY) { // load/store or floating point instructions take multiple cycles to // complete. Sometimes we want to connect the memory_controller_addr // and other signals to *start* the operation time = startTime; } else if (timeAvail != expectedAvailTime) { // this is caused when we have an operation, say an 'add' that // is normally chained in this scheduler. But since IMS doesn't // support chaining, the IMS schedules the add into the next // cycle. assert(timeAvail == expectedAvailTime + 1); time = expectedAvailTime; } RTLSignal *ii_state = rtl->find(label + "_ii_state"); // connect the signal during the correct ii_state and valid_bit time RTLOp *cond = rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst(utostr(time % II), ii_state->getWidth())), rtl->find(label + "_valid_bit_" + utostr(time))); if (signal->isReg()) { //it it's a register, add the waitrequest condition to it RTLSignal *waitrequest = getWaitRequest(BB->getParent()); RTLOp *regCond = rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::Not)->setOperands(waitrequest), cond); return regCond; } return cond; } RTLOp *GenerateRTL::createOptoCheckState(State *state) { RTLOp *cond; cond = rtl->addOp(RTLOp::EQ); cond->setOperand(0, rtl->find("cur_state")); cond->setOperand(1, getStateSignal(state)); return cond; } void GenerateRTL::connectSignalToDriverInState(RTLSignal *signal, RTLSignal *driver, State *state, Instruction *instr, PIPELINE_STATE pipelineState, bool setToDriverBits) { assert(state); assert(driver); RTLOp *cond; RTLOp *pipeline_cond = getPipelineStateCondition(signal, instr, pipelineState); if (isPipelined(instr) && pipeline_cond) { cond = pipeline_cond; } else { cond = createOptoCheckState(state); } signal->addCondition(cond, driver, instr, setToDriverBits); } // create signal which checks state AND another condition void GenerateRTL::connectSignalToDriverInStateWithCondition( RTLSignal *signal, RTLSignal *driver, State *state, RTLOp *newCond, Instruction *instr) { assert(state); assert(driver); RTLOp *stateCond = createOptoCheckState(state); ; RTLOp *cond; if (newCond) { cond = rtl->addOp(RTLOp::And); cond->setOperands(stateCond, newCond); } else { cond = stateCond; } signal->addCondition(cond, driver, instr); } void GenerateRTL::visitGetElementPtrInst(GetElementPtrInst &I) { // RAM pointer RTLSignal *gep = rtl->addWire(verilogName(&I), RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); connectSignalToDriverInState(gep, getGEP(this->state, &I), this->state, &I); } int GenerateRTL::connectedToPortB(Instruction *instr) { if (!this->binding->existsBindingInstrFU(instr)) return 0; std::string fuId = this->binding->getBindingInstrFU(instr); size_t found; found = fuId.find("mem_dual_port_0"); if (found != string::npos) { return 0; } else { found = fuId.find("mem_dual_port_1"); if (found != string::npos) { return 1; } else { errs() << "Error: mem_port not matched! FuId: " << fuId << "\n"; return -1; } } } void GenerateRTL::visitLoadInst(LoadInst &I) { LoadInst *instr = &I; Value *addr = I.getPointerOperand(); std::cout<<"Visiting Load"<<std::endl; I.print(outs()); std::cout<<std::endl; State *endState = fsm->getEndState(&I); assert(endState); RTLWidth w(instr->getType()); //if the ranges aren't dynamic, then minimize loads as well. When dynamic ranges are specific //in a file, then comparators could be used to check the ranges coming from the loads, so they //shouldn't be minimized. if (LEGUP_CONFIG->getParameter("MB_RANGE_FILE") == "") w = RTLWidth(instr, MBW); RTLSignal *loadWire = rtl->addWire(verilogName(instr), w); std::string regName = verilogName(instr) + "_reg"; if (!rtl->exists(regName)) { RTLSignal *loadReg = rtl->addReg(regName, w); connectSignalToDriverInState(loadReg, loadWire, endState, instr, OUTPUT_READY); } if (LEGUP_CONFIG->isInterfacePort(addr->getName())){ std::string label = addr->getName().str(); if (!rtl->exists(label + "_in")){ bool isInternal = LEGUP_CONFIG->isInternalInterface(label); rtl->addIn(label + "_in",w); PropagatingSignals *ps = alloc->getPropagatingSignals(); RTLSignal *temp_port_signal = new RTLSignal(label + "_in","",w); temp_port_signal ->setType("input"); PropagatingSignal propInterfacePort(temp_port_signal , isInternal, false); ps->addPropagatingSignalToFunctionNamed(Fp->getName(),propInterfacePort); } RTLOp *trunc = rtl->addOp(RTLOp::Trunc); trunc->setCastWidth(loadWire->getWidth()); trunc->setOperand(0, rtl->find(label + "_in")); connectSignalToDriverInState(loadWire, trunc, endState, instr); return; } assert(connectedToPortB(instr) != -1 && "FU doesn't match the mem port"); std::string port = connectedToPortB(instr) ? "b" : "a"; RAM *ram = NULL; if (LEGUP_CONFIG->getParameterInt("LOCAL_RAMS")) { ram = alloc->getLocalRamFromValue(addr); } if (ram && alloc->isRAMLocaltoFct(Fp, ram)) { std::string name = ram->getName(); //errs() << "Connecting local RAM: " << ram->getName() << "\n"; // convert byte address to word address RTLOp *wordAddr = rtl->addOp(RTLOp::Shr); wordAddr->setOperand(0, getOp(this->state, addr)); int bytes = ram->getDataWidth() / 8; int ignore = (bytes == 0) ? 0 : (int) log2(bytes); wordAddr->setOperand(1, new RTLConst(utostr(ignore), RTLWidth(3))); connectSignalToDriverInState(rtl->find(name + "_address_" + port), wordAddr, this->state, instr); connectSignalToDriverInState(rtl->find(name + "_write_enable_" + port), ZERO, this->state, instr); connectSignalToDriverInState(loadWire, rtl->find(name + "_out_" + port), endState, instr); } else { loadStoreCommon(&I, addr); RTLSignal *memOut; // for parallel function // readdata needs to be taken from stored register bool isParallelFunction = Fp->hasFnAttribute("totalNumThreads"); if (isParallelFunction) { memOut = rtl->find("memory_controller_out_stored_on_datavalid_" + port); } else { memOut = rtl->find("memory_controller_out_" + port); } RTLSignal *memWe = rtl->find("memory_controller_write_enable_" + port); connectSignalToDriverInState(memWe, ZERO, this->state, instr); // need to truncate memory_controller_out, which is usually // bigger than loadWire RTLOp *trunc = rtl->addOp(RTLOp::Trunc); trunc->setCastWidth(loadWire->getWidth()); trunc->setOperand(0, memOut); connectSignalToDriverInState(loadWire, trunc, endState, instr); } } void GenerateRTL::visitStoreInst(StoreInst &I) { Value *addr = I.getPointerOperand(); RTLWidth w(I.getValueOperand()->getType()); std::cout<<"Visiting Store"<<std::endl; I.print(outs()); std::cout<<std::endl; if (LEGUP_CONFIG->isInterfacePort(addr->getName())){ std::string label = addr->getName().str(); if (!rtl->exists(label)){ bool isInternal = LEGUP_CONFIG->isInternalInterface(label); rtl->addOutReg(label,w); rtl->addOutReg(label + "_valid",1); PropagatingSignals *ps = alloc->getPropagatingSignals(); RTLSignal *temp_port_signal = new RTLSignal(label,"",w); temp_port_signal ->setType("output"); PropagatingSignal propInterfacePort(temp_port_signal , isInternal, false); RTLSignal *temp_port_valid_signal = new RTLSignal(label + "_valid", "",1); temp_port_valid_signal->setType("output"); PropagatingSignal propInterfacePortValid(temp_port_valid_signal , isInternal, false); ps->addPropagatingSignalToFunctionNamed(Fp->getName(),propInterfacePort); ps->addPropagatingSignalToFunctionNamed(Fp->getName(),propInterfacePortValid); } RTLOp *ext = rtl->addOp(RTLOp::ZExt); ext->setCastWidth(w); ext->setOperand(0, getOp(this->state, I.getOperand(0))); connectSignalToDriverInState(rtl->find(label), ext, this->state, &I); RTLSignal *validPortSignal = rtl->find(label + "_valid"); connectSignalToDriverInState(validPortSignal,ONE, this->state, &I); validPortSignal->setDefaultDriver(ZERO); return; } assert(connectedToPortB(&I) != -1 && "FU doesn't match the mem port"); std::string port = connectedToPortB(&I) ? "b" : "a"; RAM *ram = NULL; if (LEGUP_CONFIG->getParameterInt("LOCAL_RAMS")) { //NC changes... //TODO: DEBUGGING PROCEDURE IN THIS BLOCK NEEDS TO BE RE-THINKED ram = alloc->getLocalRamFromValue(addr); } if (ram && alloc->isRAMLocaltoFct(Fp, ram)) { std::string name = ram->getName(); assert(!ram->isROM()); // todo: refactor with visitLoadInst // convert byte address to word address RTLOp *wordAddr = rtl->addOp(RTLOp::Shr); wordAddr->setOperand(0, getOp(this->state, addr)); int bytes = ram->getDataWidth() / 8; int ignore = (bytes == 0) ? 0 : (int)log2(bytes); wordAddr->setOperand(1, new RTLConst(utostr(ignore), RTLWidth(3))); connectSignalToDriverInState(rtl->find(name + "_address_" + port), wordAddr, this->state, &I); connectSignalToDriverInState(rtl->find(name + "_write_enable_" + port), ONE, this->state, &I); connectSignalToDriverInState(rtl->find(name + "_in_" + port), getOp(this->state, I.getOperand(0)), this->state, &I); } else { loadStoreCommon(&I, addr); RTLSignal *memIn = rtl->find("memory_controller_in_" + port); RTLSignal *memWe = rtl->find("memory_controller_write_enable_" + port); connectSignalToDriverInState(memWe, ONE, this->state, &I); // zero extend the operand to be the same size as the // memory_controller_in RTLOp *ext = rtl->addOp(RTLOp::ZExt); ext->setCastWidth(memIn->getWidth()); ext->setOperand(0, getOp(this->state, I.getOperand(0))); connectSignalToDriverInState(memIn, ext, this->state, &I); // NC changes if (LEGUP_CONFIG->getParameterInt("INSPECT_DEBUG")) { int adrOffsetValue = 0; RTLSignal* adrSig = getOp(this->state, addr, adrOffsetValue); if (adrOffsetValue == 0) adrOffsetValue = -1; StateStoreInfo* storeInfo = new StateStoreInfo(this->state, port, adrSig, adrOffsetValue, &I); statesStoreMapping.push_back(storeInfo); } } } // size: 0 for bool/byte, 1 for short, 2 for word, 3 for long/other (struct, ptr, etc...) unsigned GenerateRTL::getInstrMemSize(Instruction *instr) { int bitwidth; if (isa<StoreInst>(*instr)) { bitwidth = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); } else { bitwidth = instr->getType()->getPrimitiveSizeInBits(); } if (bitwidth == 0) { // other ie. struct, pointer bitwidth = alloc->getDataLayout()->getPointerSize() * 8; } switch (bitwidth) { case 1: return 0; break; // bool case 8: return 0; break; // byte case 16: return 1; break; // short case 32: return 2; break; // word case 64: return 3; break; // long/other default: errs() << "Invalid bitwidth '" << bitwidth << "' for instr: " << *instr << "\n"; return 0; } } void GenerateRTL::loadStoreCommon(Instruction *instr, Value *addr) { assert(isa<PointerType>(addr->getType())); assert(connectedToPortB(instr) != -1 && "FU doesn't match the mem port"); std::string port = connectedToPortB(instr) ? "b" : "a"; RTLSignal *memAddr = rtl->find("memory_controller_address_" + port); RTLSignal *memSize = rtl->find("memory_controller_size_" + port); RTLSignal *memEn = rtl->find("memory_controller_enable_" + port); connectSignalToDriverInState(memAddr, getOp(this->state, addr), this->state, instr); connectSignalToDriverInState(memEn, ONE, this->state, instr); if (alloc->usesGenericRAMs()) { unsigned size = getInstrMemSize(instr); connectSignalToDriverInState(memSize, rtl->addConst(utostr(size), RTLWidth(2)), this->state, instr); } } // ignore switch/branch/phi instructions // these are handled already by the FSM generated in scheduling void GenerateRTL::visitBranchInst(BranchInst &I) { } void GenerateRTL::visitSwitchInst(SwitchInst &I) { } void GenerateRTL::visitPHINode(PHINode &phi) { } // printf statements in C are replaced with $display() verilog statements for // modelsim simulation void GenerateRTL::visitPrintf(CallInst *CI, Function *called) { RTLOp *printf = NULL; if (called->getName() == "puts") { // puts expects a newline added printf = rtl->addOp(RTLOp::Display); } else { // $write() is $display() but without the newline. printf = rtl->addOp(RTLOp::Write); } Value *str = *CI->op_begin(); // handle getelementptr if (const User *U = dyn_cast<User>(str)) { if (U->getNumOperands() > 1) { str = U->getOperand(0); } } GlobalVariable *G = dyn_cast<GlobalVariable>(str); if (!G) { outs() << "Cannot statically resolve char pointer for " << "printf call. Skipping verilog $display statement for:\n" << *CI << "\n"; return; } assert(G); Constant *C = G->getInitializer(); int index = 0; //errs() << "printf: " << *CA << "\n"; //if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) { if (ConstantDataArray *CA = dyn_cast<ConstantDataArray>(C)) { //errs() << "printf: " << *CA << "\n"; // LLVM 3.4 update: //std::string s = "\"" + arrayToString(CA) + "\""; std::string st = CA->getAsString().str(); st = st.substr(0, st.size() - 1); std::string s = "\"" + st + "\""; printf->setOperand(index, rtl->addConst(s)); index++; } for (CallSite::arg_iterator AI = CI->op_begin() + 1, AE = CI->op_end() - 1; AI != AE; ++AI) { Value *arg = *AI; printf->setOperand(index, getOp(this->state, arg)); index++; } connectSignalToDriverInState(rtl->getUnsynthesizableSignal(), printf, this->state, CI); } // this function is used to create function_memory_controller_out_port_instNum signal // used to connect parallel module "instantiations" // It creates a 2-bit shift register (for 2-cycle memory latency) // where the MSB is asserted in the cycle when the data comes back from memory // this needs to be stored in this cycle when sending it down to a parallel instance // before it is overwritten by readdata for another parallel instance // similar function, "createMemoryReaddataStorageForParallelFunction" used to create // storage "inside" the parallel module. Both functions are needed to get the correct // data from memory void GenerateRTL::createMemoryReaddataLogicForParallelInstance(RTLSignal *gnt, const std::string name, const std::string postfix, const std::string instanceNum) { // 2-bit shift register // data is "ready" (readdata has come back) // when dataReady1 is asserted RTLSignal *dataReady0, *dataReady1; dataReady0 = rtl->addReg(name + "_dataReady0" + postfix + instanceNum); dataReady1 = rtl->addReg(name + "_dataReady1" + postfix + instanceNum); // read and not write RTLSignal *memRead = rtl->addOp(RTLOp::And)->setOperands( rtl->find(name + "_enable" + postfix + instanceNum), rtl->addOp(RTLOp::Not)->setOperands( rtl->find(name + "_write_enable" + postfix + instanceNum))); // read and granted RTLSignal *memReadGranted = rtl->addOp(RTLOp::And)->setOperands(gnt, memRead); RTLSignal *wait, *memoryControllerOut; // choose the correct memory controller signal depending on // whether this function uses Pthreads or not if (usesPthreads) { wait = rtl->find("memory_controller_waitrequest_arbiter"); memoryControllerOut = rtl->find("memory_controller_out_arbiter" + postfix); } else { wait = rtl->find("memory_controller_waitrequest"); memoryControllerOut = rtl->find("memory_controller_out" + postfix); } RTLSignal *reset; reset = rtl->find("reset"); RTLOp *notWait = rtl->addOp(RTLOp::Not)->setOperands(wait); // this signal is high one state after the read is granted dataReady0->addCondition(reset, ZERO); dataReady0->addCondition(notWait, memReadGranted); // this signal is high when the data read is ready to be stored dataReady1->addCondition(reset, ZERO); // for hybrid flow if (LEGUP_CONFIG->isHybridFlow()) { // it has to be a different for the hybrid flow // since the top level of the hybrid sends down readdata // two states after the read // hence this dataReady1->addCondition(notWait, dataReady0); } else { // for pure HW flow, the data is available on // the next clock edge after dataReady0 dataReady1->connect(dataReady0); } // create the memory_controller_out signals to be connected // to a parallel instance RTLSignal *out = rtl->find(name + "_out" + postfix + instanceNum); RTLSignal *out_reg = rtl->addReg(name + "_out_reg" + postfix + instanceNum, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); // connect memory_controller_out when the data is ready // retain this data to avoid inferring a latch out->setDefaultDriver(out_reg); out->addCondition( dataReady1, memoryControllerOut); // register used to avoid inferring a latch // stores the readdata on posedge clk out_reg->addCondition(reset, rtl->addConst("0", RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); out_reg->addCondition( dataReady1, memoryControllerOut); } //create state1 and state2 to start/stop module instance and set state transitions void GenerateRTL::createStateTransitions(CallInst *CI, State *&state1, State *&state2, bool &isStateTerminating) { BasicBlock *bb = CI->getParent(); assert(bb == this->state->getBasicBlock()); FiniteStateMachine* fsm = sched->getFSM(Fp); state1 = fsm->newState(this->state, "LEGUP_function_call"); stateSignals[state1] = rtl->addParam("state_placeholder", "placeholder"); state1->setBasicBlock(bb); // state1->setFunctionCall(true); isStateTerminating = this->state->isTerminating(); if (isStateTerminating) { state2 = fsm->newState(state1, "LEGUP_function_call"); stateSignals[state2] = rtl->addParam("state_placeholder", "placeholder"); state2->setBasicBlock(bb); state2->setTerminating(this->state->isTerminating()); State::Transition origTransition = this->state->getTransition(); state2->setTransition(origTransition); } else { // No need for an extra call state, just set it to the state's default transition state2 = this->state->getDefaultTransition(); } this->state->setTerminating(false); // update FSM. CI will be removed from state when we return state1->push_back(CI); fsm->setStartState(CI, state1); fsm->setEndState(CI, state1); // need to clear all original transitions. // 'state' must have only 1 transition - because we must go to state1 // where we'll wait for the call to complete. State::Transition blank; this->state->setTransition(blank); this->state->setDefaultTransition(state1); assert(this->state->getNumTransitions() == 1); state1->setDefaultTransition(state1); } void GenerateRTL::connectStartSignal(CallInst *CI, State *endState, const std::string moduleName, const std::string instanceName, RTLOp *oneCond, RTLOp *zeroCond) { RTLSignal *startReg = rtl->addReg(moduleName + "_start" + instanceName); // connect one in the call state connectSignalToDriverInStateWithCondition(startReg, ONE, this->state, oneCond, CI); // connect zero in the next state connectSignalToDriverInStateWithCondition(startReg, ZERO, endState, zeroCond); } int GenerateRTL::getNumThreads(const CallInst *CI) { int numThreads = getMetadataInt(CI, "NUMTHREADS"); // if it's a OpenMP wrapper function, // don't create multiple instances std::string functionType = getMetadataStr(CI, "TYPE"); if (functionType == "legup_wrapper_omp") { numThreads = 0; } return numThreads; } // given a call inst, get its metadata // to determine the instance number int GenerateRTL::getInstanceNum(const CallInst *CI, const int loopIndex) { int instanceNum; const int numThreads = getMetadataInt(CI, "NUMTHREADS"); // if the loop is unrolled if (numThreads == 1) { instanceNum = getMetadataInt(CI, "THREADID"); } else { instanceNum = loopIndex; } return instanceNum; } // prepend "_inst" to instanceNum std::string GenerateRTL::getInstanceName(const CallInst *CI, const int loopIndex) { std::string functionType = getMetadataStr(CI, "TYPE"); // if this a call to a parallel function // if (getMetadataInt(CI, "NUMTHREADS") && functionType != // "legup_wrapper_omp") if (getNumThreads(CI)) return "_inst" + utostr(getInstanceNum(CI, loopIndex)); else return ""; } RTLOp *GenerateRTL::getOpToCheckThreadID(RTLSignal *threadIDSignal, const int threadIDValue) { RTLOp *checkthreadID = rtl->addOp(RTLOp::EQ)->setOperands( threadIDSignal, rtl->addConst(utostr(threadIDValue), threadIDSignal->getWidth())); return checkthreadID; } // create and connect start signal for module instance void GenerateRTL::createStartSignal(CallInst *CI, State *state1, const std::string moduleName, const int numThreads, const std::string functionType) { RTLSignal *wait; // get the waitrequest signal if (functionType == "legup_wrapper_pthreadcall") { wait = rtl->find("memory_controller_waitrequest_arbiter"); } else { wait = rtl->find("memory_controller_waitrequest"); } RTLOp *noWait = rtl->addOp(RTLOp::EQ)->setOperands(wait, ZERO); // setting up the start signal if (numThreads > 0) { // if there are parallel functions, // connect the start signal to all parallel instances for (int i = 0; i < numThreads; i++) { RTLOp *checkthreadID = 0; // for pthread_create, create Op to check threadID if (functionType == "legup_wrapper_pthreadcall") { RTLSignal *threadIDValue = getPthreadThreadID(CI, moduleName); checkthreadID = getOpToCheckThreadID(threadIDValue, getInstanceNum(CI, i)); } connectStartSignal(CI, state1, moduleName, getInstanceName(CI, i), checkthreadID, noWait); } } else { // if sequential function, // just connect it to the one instance connectStartSignal(CI, state1, moduleName, getInstanceName(CI)); } } // create and connect argument signals to module instance void GenerateRTL::createArgumentSignals(CallInst *CI, Function *called, const std::string moduleName, const int numThreads, const std::string functionType) { RTLSignal *argSignal; // iterate through each argument CallSite::arg_iterator AI = CI->op_begin(), AE = CI->op_end() - 1; for (Function::arg_iterator FI = called->arg_begin(), Fe = called->arg_end(); FI != Fe; ++FI) { assert(AI != AE); Value *arg = *AI; assert(arg); std::string name = moduleName + "_" + alloc->verilogNameFunction(FI, called); RTLWidth w(arg, MBW); // adjust width of arguments for bitcast cases // ie. %2 = call i8* bitcast (void (i32*, i32, i32)* @legup_memset_4 to // i8* (i8*, i8, i64)*)(i8* %1, i8 0, i64 40) multi_cycle_set_force_wire_operand(true); // Temporary solution... RTLSignal *argDriver = getOp(this->state, arg); multi_cycle_set_force_wire_operand(false); argDriver->setWidth(w); if (numThreads > 0) { // if there are parallel functions, // connect signal to all parallel instances for (int i = 0; i < numThreads; i++) { RTLOp *checkthreadID = 0; argSignal = rtl->addReg(name + getInstanceName(CI, i), w); // for pthread_create, create Op to check threadID if (functionType == "legup_wrapper_pthreadcall") { RTLSignal *threadIDValue = rtl->find(moduleName + "_threadID"); checkthreadID = getOpToCheckThreadID(threadIDValue, getInstanceNum(CI, i)); } connectSignalToDriverInStateWithCondition( argSignal, argDriver, this->state, checkthreadID, CI); } } else { // if sequential function, // just connect it to the one instance connectSignalToDriverInState(rtl->addReg(name, w), argDriver, this->state, CI); } ++AI; } } RTLSignal *GenerateRTL::getPthreadThreadID(CallInst *CI, const std::string moduleName) { // get the threadID which is an operand of the store instruction // right before the call to the pthread function Value *threadIDValueArg; Instruction *threadID = CI->getPrevNode(); if (StoreInst *st = dyn_cast<StoreInst>(threadID)) { if (getMetadataInt(threadID, "legup_pthread_functionthreadID")) { // get the value operand of the store instruction threadIDValueArg = st->getValueOperand(); } else { assert (0 && "The Pthread function threadID cannot be found\n"); } } else { assert (0 && "The store instruction after the call to pthread function cannot be found\n"); } assert(threadIDValueArg); // get bottom 16 bits of the value being stored // this is the threadID RTLSignal *threadIDValue = rtl->addWire(moduleName + "_threadID", RTLWidth(16)); RTLOp *trunc_op = rtl->addOp(RTLOp::Trunc); //set the cast width to the bottom 16 bits trunc_op->setCastWidth(RTLWidth("15", "0")); // get the bottom 16 bits of threadVar signal trunc_op->setOperand(0, getOpReg(threadIDValueArg, this->state)); connectSignalToDriverInState(threadIDValue, trunc_op, this->state, CI); return threadIDValue; } void GenerateRTL::connectReturnSignal(State *callState, CallInst *CI, Function *calledFunction, const std::string moduleName, const int numThreads, const int loopIndex) { const Type *rT = calledFunction->getReturnType(); RTLWidth T(rT); RTLOp *resetCond = rtl->addOp(RTLOp::Or)->setOperands( rtl->find("reset"), rtl->addOp(RTLOp::EQ) ->setOperands(rtl->find("cur_state"), stateSignals[this->state])); RTLSignal *ret = rtl->addWire( moduleName + "_return_val" + getInstanceName(CI, loopIndex), T); RTLSignal *retReg = rtl->addReg(moduleName + "_return_val" + getInstanceName(CI, loopIndex) + "_reg", T); retReg->addCondition(resetCond, rtl->addConst("0", T)); RTLSignal *finish = rtl->find(moduleName + "_finish" + getInstanceName(CI, loopIndex)); retReg->addCondition(finish, ret); if (!numThreads) connectSignalToDriverInState(rtl->addWire(verilogName(CI), T), retReg, callState, CI); } // create return signal for module instance void GenerateRTL::createReturnSignal(State *callState, CallInst *CI, Function *called, const std::string moduleName, const int numThreads, const std::string functionType) { std::string instanceNum; // setting up return value const Type *rT = called->getReturnType(); if (rT->getTypeID() != Type::VoidTyID) { if (numThreads > 0) { if (functionType == "legup_wrapper_pthreadpoll") { RTLWidth T(rT); RTLSignal *ret = rtl->addWire(moduleName + "_return_val", T); connectSignalToDriverInState(rtl->addWire(verilogName(CI), T), ret, callState, CI); } else { // if there are parallel functions, // connect the return signal to all parallel instances for (int i = 0; i < numThreads; i++) { connectReturnSignal(callState, CI, called, moduleName, numThreads, i); } } } else { // if sequential function, // just connect it to the one instance connectReturnSignal(callState, CI, called, moduleName, numThreads); } } } void GenerateRTL::connectFinishSignal(CallInst *CI, RTLSignal *finish_final, const std::string moduleName, const std::string functionType, const int numThreads, std::vector<RTLSignal *> &finishVector, const int loopIndex) { std::string finishName = moduleName + "_finish"; std::string instanceName = getInstanceName(CI, loopIndex); // adding finish signal for each instance RTLSignal *instanceFinishReg = rtl->addReg(finishName + instanceName + "_reg"); RTLSignal *finish_inst = rtl->addWire(finishName + instanceName); RTLOp *resetCond; // To clear finish_reg signal for each instance if (functionType == "legup_wrapper_pthreadcall") { // for pthreads, since the calls are non-blocking // we need to clear it after it has been detected by pthread_join // so it's safe to clear it whenever each instance is started RTLSignal *start_inst = rtl->find(moduleName + "_start" + instanceName); resetCond = rtl->addOp(RTLOp::Or)->setOperands(rtl->find("reset"), start_inst); } else { // otherwise, for sequential and OpenMP functions // calls are blocking, hence reset in the // state before the call state resetCond = rtl->addOp(RTLOp::Or)->setOperands( rtl->find("reset"), rtl->addOp(RTLOp::EQ)->setOperands(rtl->find("cur_state"), stateSignals[this->state])); } // if (resetCond) // finishName_reg_inst <= 0; instanceFinishReg->addCondition(resetCond, ZERO); // if (finishName_inst) // finishName_reg_inst <= 1'b1; instanceFinishReg->addCondition(finish_inst, ONE); // for OpenMP, you need to AND all finish signal together // push all signals into a vector if (functionType == "omp_function") { finishVector.push_back(instanceFinishReg); // if in last iteration of loop if (getInstanceNum(CI, loopIndex) == numThreads - 1) { // now AND the finish signals together RTLOp *op_and = rtl->recursivelyAddOp(RTLOp::And, finishVector, numThreads); finish_final->connect(op_and); } } else { assert(instanceFinishReg); finish_final->connect(instanceFinishReg); } } void GenerateRTL::createFinishSignal(CallInst *CI, State *callState, State *callEndState, const std::string moduleName, const int numThreads, const std::string functionType) { // create finish signal std::string finishName_final = moduleName + "_finish_final"; RTLSignal *finish_final = rtl->addWire(finishName_final); // set the transition from callState to callEndState if (functionType == "legup_wrapper_pthreadcall") { // for pthread functions, just move onto next state // without checking the finish signal // since it's non-blocking callState->setDefaultTransition(callEndState); } else { // if not pthreads, check the finish signal to move to next state callState->setTransitionSignal(finish_final); callState->addTransition(callEndState); } // finish signal for pthread poll is create later if (functionType != "legup_wrapper_pthreadpoll") { vector<RTLSignal *> finishVector; if (numThreads > 0) { // for parallel functions, the finish signal from each instance // needs to be registered for (int i = 0; i < numThreads; i++) { connectFinishSignal(CI, finish_final, moduleName, functionType, numThreads, finishVector, i); } } else { // you need to register the finish signal // since if there is memory access to shared memory space in the // very last state a function // the finish signal goes may go high then low while the waitrequest // is asserted // in which case the calling function's FSM will be able to move // onto the next state due to the waitrequest connectFinishSignal(CI, finish_final, moduleName, functionType, numThreads, finishVector); } } } void GenerateRTL::connectWaitrequestForParallelFunctions( CallInst *CI, State *callState, const std::string name, const std::string funcName, const std::string functionType, const int loopIndex) { std::string instanceName = getInstanceName(CI, loopIndex); RTLSignal *wait, *wait_local, *gnt, *gnt_reg, *gntNotGiven, *waitDriver; RTLOp *avalonStall; // waitrequest is asserted when // 1. this instance is accessing shared memory space and Avalon waitrequest // is asserted // 2. enable is asserted but gnt is not given wait_local = rtl->addWire(name + "_waitrequest" + instanceName); if (usesPthreads) { wait = rtl->find("memory_controller_waitrequest_arbiter"); } else { wait = rtl->find("memory_controller_waitrequest"); } RTLOp *notWait_local = rtl->addOp(RTLOp::Not)->setOperands(wait_local); int instanceIndex = getInstanceNum(CI, loopIndex); gnt = rtl->find(funcName + "_memory_controller_gnt_" + utostr(instanceIndex)); gnt_reg = rtl->addReg(funcName + "_memory_controller_gnt_" + utostr(instanceIndex) + "_reg"); RTLSignal *en_a = rtl->find(name + "_enable_a" + instanceName); RTLSignal *en_b = rtl->find(name + "_enable_b" + instanceName); RTLSignal *notGnt = rtl->addOp(RTLOp::Not)->setOperands(gnt); RTLSignal *memAccess = rtl->addOp(RTLOp::Or)->setOperands(en_a, en_b); gntNotGiven = rtl->addOp(RTLOp::And)->setOperands(memAccess, notGnt); if (LEGUP_CONFIG->isHybridFlow()) { // in hybrid case, waitrequest is asserted when // there is a memory request but the grant is not given at the current // level // or when there is an waitrequest over avalon from parent module // for avalon waitrequest, grant is registered since Avalon memory // accesses // are pipelined, hence the avalon waitrequest comes one state after // memory request from current level gnt_reg->addCondition(notWait_local, gnt); avalonStall = rtl->addOp(RTLOp::And)->setOperands(wait, gnt_reg); waitDriver = rtl->addOp(RTLOp::Or)->setOperands(gntNotGiven, avalonStall); } else { // pure HW case, waitrequest is asserted when // there is a memory request but the grant is not given at the current // level // or when the grant is given but wait request is asserted from the // parent module // (this happens when the grant is not given from the parent module) waitDriver = rtl->addOp(RTLOp::Or)->setOperands( gntNotGiven, rtl->addOp(RTLOp::And)->setOperands(gnt, wait)); } assert(waitDriver); // connect waitrequest signal if (functionType == "legup_wrapper_pthreadcall") { // can't check the state for pthreads case // as the FSM will be moving to execute other things with the // pthread instances running in parallel wait_local->connect(waitDriver); } else { connectSignalToDriverInState(wait_local, waitDriver, callState, CI); } } void GenerateRTL::createWaitrequestLogic(CallInst *CI, State *callState, std::string name, const int numThreads, const std::string functionType) { std::string funcName; Function *called = CI->getCalledFunction(); if (!called) { // indirect call, for example: // tail call void bitcast (i32 (...)* @exit to void (i32)*)(i32 1) // noreturn nounwind Value *Callee = CI->getCalledValue(); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee)) { if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) { funcName = RF->getName(); } } } else { funcName = called->getName(); } PropagatingSignals *ps = alloc->getPropagatingSignals(); bool shouldConnectMemorySignals = ps->functionUsesMemory(funcName) || usesPthreads; stripInvalidCharacters(funcName); // setting up the waitrequest signal if (numThreads > 0) { for (int i = 0; i < numThreads; i++) { connectWaitrequestForParallelFunctions(CI, callState, name, funcName, functionType, i); } } else if (shouldConnectMemorySignals) { RTLSignal *wait_local = rtl->addWire(name + "_waitrequest"); // connectSignalToDriverInState(wait_local, // rtl->find("memory_controller_waitrequest"), callState, CI); wait_local->connect(rtl->find("memory_controller_waitrequest")); } } // connect pthreadID and functionID signals to operand // based on state void GenerateRTL::connectPthreadIDSignals(CallInst *CI, RTLSignal *pollThreadID, RTLSignal *pollFunctionID) { // get the state in which the wrapper is called State *callState = fsm->getEndState(CI); // get the thread variable from the call instruction Value *threadVar = CI->getArgOperand(0); assert(threadVar); // get and connect threadID signal from the bottom half // of thread variable RTLOp *op = selectTopOrBottomHalfBits(threadVar, callState, false); connectSignalToDriverInState(pollThreadID, op, callState, CI); // get and connect functionID signal from the top half // of thread variable RTLOp *op2 = selectTopOrBottomHalfBits(threadVar, callState, true); connectSignalToDriverInState(pollFunctionID, op2, callState, CI); } RTLOp *GenerateRTL::selectTopOrBottomHalfBits(Value *V, State *state, bool top) { // get the RTLSignal for that value RTLSignal *signal = getOpReg(V, state); RTLOp *op; RTLConst *constant; // if V is a constant int if (dyn_cast<ConstantInt>(V)) { if (top) { // if you want the top half, then // right shift by half the bitwidth op = rtl->addOp(RTLOp::Shr); constant = rtl->addConst(utostr(16), RTLWidth("4", "0")); } else { // if you want the bottom half, then // AND with FFFF op = rtl->addOp(RTLOp::And); constant = rtl->addConst(utostr(0xFFFF), RTLWidth("15", "0")); } op->setOperands(signal, constant); } else { // else if it's a signal // then select the correct width op = rtl->addOp(RTLOp::Trunc); if (top) { op->setCastWidth(RTLWidth("31", "16")); } else { op->setCastWidth(RTLWidth("15", "0")); } op->setOperand(0, signal); } return op; } void GenerateRTL::connectPthreadPollFinishAndReturnVal( CallInst *CI, RTLSignal *pollThreadID, RTLSignal *pollFunctionID) { /* we want to make the following signals for finish when there are two functions, A & B, each with two threads, legup_pthreadpoll_finish = 0; if (legup_pthreadpoll_threadID == 0 && legup_pthreadpoll_functionID == 0 && legup_pthreadcall_A_finish_final0 == 1) legup_pthreadpoll_finish = 1; if (legup_pthreadpoll_threadID == 1 && legup_pthreadpoll_functionID == 0 && legup_pthreadcall_A_finish_final1 == 1) legup_pthreadpoll_finish = 1; if (legup_pthreadpoll_threadID == 0 && legup_pthreadpoll_functionID == 1 && legup_pthreadcall_B_finish_final0 == 1) legup_pthreadpoll_finish = 1; if (legup_pthreadpoll_threadID == 1 && legup_pthreadpoll_functionID == 1 && legup_pthreadcall_B_finish_final1 == 1) legup_pthreadpoll_finish = 1; also make the following signals for return_val when there are two functions, A & B, each with two threads, legup_pthreadpoll_return_val = 0; if (legup_pthreadpoll_threadID == 0 && legup_pthreadpoll_functionID == 0 && legup_pthreadcall_A_finish_final0 == 1) legup_pthreadpoll_return_val = legup_pthreadcall_A_return_val_inst0; if (legup_pthreadpoll_threadID == 1 && legup_pthreadpoll_functionID == 0 && legup_pthreadcall_A_finish_final1 == 1) legup_pthreadpoll_return_val = legup_pthreadcall_A_return_val_inst1; if (legup_pthreadpoll_threadID == 0 && legup_pthreadpoll_functionID == 1 && legup_pthreadcall_B_finish_final0 == 1) legup_pthreadpoll_return_val = legup_pthreadcall_B_return_val_inst0; if (legup_pthreadpoll_threadID == 1 && legup_pthreadpoll_functionID == 1 && legup_pthreadcall_B_finish_final1 == 1) legup_pthreadpoll_return_val = legup_pthreadcall_B_return_val_inst1; */ // get the name of the pthread function std::string pthreadFuncName = CI->getCalledFunction()->getName(); // get the number of threads for that pthread function int numThreads = getNumThreads(CI); // find the finish signal for pthread polling wrapper RTLSignal *finish = rtl->addWire("legup_pthreadpoll_finish_final"); finish->setDefaultDriver(ZERO); // iterate through each thread of the pthread function for (int i = 0; i < numThreads; i++) { std::string instNum = utostr(getInstanceNum(CI, i)); // find the finish signal from pthread calling wrapper RTLSignal *pthreadCallFinish = rtl->addWire(pthreadFuncName + "_finish_inst" + instNum + "_reg"); // if (legup_pthreadpoll_threadID == 0 && // legup_pthreadcall_A_finish_final0 == 1) // legup_pthreadpoll_finish = 1; RTLSignal *finishCond = rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::EQ)->setOperands( pollThreadID, rtl->addConst(instNum, RTLWidth(16))), pthreadCallFinish); // if there is more than one function in the pthread polling wrapper // need to check the functionID as well // if (legup_pthreadpoll_functionID == 0 && legup_pthreadpoll_threadID // == 0 && legup_pthreadcall_A_finish_final0 == 1) // legup_pthreadpoll_finish = 1; // // get the functionID for this pthread function int functionID = getMetadataInt(CI, "FUNCTIONID"); RTLSignal *functionIDCond = rtl->addOp(RTLOp::EQ)->setOperands( pollFunctionID, rtl->addConst(utostr(functionID), RTLWidth(16))); RTLSignal *finishCond_final = rtl->addOp(RTLOp::And)->setOperands(finishCond, functionIDCond); finish->addCondition(finishCond_final, ONE); // if there are any non-void pthead functions // connect the return value signal if (!CI->getCalledFunction()->getReturnType()->isVoidTy()) { const Type *rT = PointerType::get(IntegerType::get(CI->getContext(), 8), 0); // make the return val signal RTLSignal *pthreadReturnVal = rtl->addWire("legup_pthreadpoll_return_val", RTLWidth(rT)); // set default to 0 pthreadReturnVal->setDefaultDriver( rtl->addConst(utostr(0), RTLWidth(rT))); // add register for return val RTLSignal *pthreadReturnVal_reg = rtl->addWire( pthreadFuncName + "_return_val_inst" + instNum + "_reg", RTLWidth(rT)); // connect register if instance is finished pthreadReturnVal->addCondition(finishCond_final, pthreadReturnVal_reg); // could move this entire function to merge into createfunction // rather than having something separate for pthreads.. } } } void GenerateRTL::createPthreadSignals(CallInst *CI) { // create a signal for threadID RTLSignal *pollThreadID = rtl->addWire("legup_pthreadpoll_threadID", RTLWidth(16)); // create a signal for functionID RTLSignal *pollFunctionID = rtl->addWire("legup_pthreadpoll_functionID", RTLWidth(16)); // get the type of this function std::string functionType = getMetadataStr(CI, "TYPE"); if (functionType == "legup_wrapper_pthreadpoll") { // connect pthreadpoll threadID and functionID connectPthreadIDSignals(CI, pollThreadID, pollFunctionID); } if (functionType == "legup_wrapper_pthreadcall") { // connect finish and return val signals connectPthreadPollFinishAndReturnVal(CI, pollThreadID, pollFunctionID); } } void GenerateRTL::connectFunctionMemorySignals( State *callState, CallInst *CI, std::string name, std::string postfix, const int numThreads, const std::string functionType, const int loopIndex) { std::string instanceName = getInstanceName(CI, loopIndex); // creating memory_controller signals RTLSignal *en = rtl->addWire(name + "_enable" + postfix + instanceName); RTLSignal *we = rtl->addWire(name + "_write_enable" + postfix + instanceName); RTLSignal *addr = rtl->addWire(name + "_address" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); RTLSignal *in = rtl->addWire(name + "_in" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); RTLSignal *out = rtl->addWire(name + "_out" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); RTLSignal *gnt; if (numThreads) { // for parallel functions, an arbiter is used to grant memory accesses gnt = rtl->addWire(name + "_gnt_" + utostr(getInstanceNum(CI, loopIndex))); // this decides which data is sent down to memory_controller_out // in which cycle createMemoryReaddataLogicForParallelInstance(gnt, name, postfix, instanceName); } else { // for sequential functions, just connect memory_controller_out directly connectSignalToDriverInState( out, rtl->find("memory_controller_out" + postfix), callState, CI); } RTLOp *eq = NULL; if (functionType == "omp_function" && numThreads) { // for OpenMP, you need to check the gnt signal and the state // since multiple instances are started in the same state // (gnt0 == 1) ... eq = rtl->addOp(RTLOp::EQ)->setOperands(gnt, ONE); } // pthread functions are treated specially // since they connect to memory_controller_*_arbiter_postfix if (functionType != "legup_wrapper_pthreadcall") { // Check cur_state == state && gnt0 == 1 for OpenMP // Check cur_state == state for Pthreads and sequential functions connectSignalToDriverInStateWithCondition( rtl->find("memory_controller_enable" + postfix), en, callState, eq, CI); connectSignalToDriverInStateWithCondition( rtl->find("memory_controller_write_enable" + postfix), we, callState, eq, CI); connectSignalToDriverInStateWithCondition( rtl->find("memory_controller_address" + postfix), addr, callState, eq, CI); connectSignalToDriverInStateWithCondition( rtl->find("memory_controller_in" + postfix), in, callState, eq, CI); if (alloc->usesGenericRAMs()) { // creating memory_controller_size_inst signals RTLSignal *size = rtl->addWire( name + "_size" + postfix + instanceName, RTLWidth(2)); size->setDefaultDriver(ZERO); connectSignalToDriverInStateWithCondition( rtl->find("memory_controller_size" + postfix), size, callState, eq); } } } // create memory controller signals for the function and // connect them to parent function's memory signals void GenerateRTL::createFunctionMemorySignals(State *callState, CallInst *CI, std::string name, std::string postfix, const int numThreads, const std::string functionType) { std::string funcName; Function *called = CI->getCalledFunction(); if (!called) { // indirect call, for example: // tail call void bitcast (i32 (...)* @exit to void (i32)*)(i32 1) // noreturn nounwind Value *Callee = CI->getCalledValue(); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee)) { if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) { funcName = RF->getName(); } } } else { funcName = called->getName(); } PropagatingSignals *ps = alloc->getPropagatingSignals(); bool shouldConnectMemorySignals = ps->functionUsesMemory(funcName) || usesPthreads; stripInvalidCharacters(funcName); if (numThreads > 0) { for (int i = 0; i < numThreads; i++) { connectFunctionMemorySignals(callState, CI, name, postfix, numThreads, functionType, i); } } else if (shouldConnectMemorySignals) { connectFunctionMemorySignals(callState, CI, name, postfix, numThreads, functionType); } } void GenerateRTL::createFunctionPropagatingSignals( State *state1, CallInst *CI, std::string name, const int parallelInstances, const std::string functionType) { std::string instanceNum, funcName; Function *called = CI->getCalledFunction(); if (!called) { // indirect call, for example: // tail call void bitcast (i32 (...)* @exit to void (i32)*)(i32 1) noreturn nounwind Value *Callee = CI->getCalledValue(); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee)) { if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) { funcName = RF->getName(); } } } else { funcName = called->getName(); } // Get a pointer to the PropagatingSignals singleton // PropagatingSignals *ps = alloc->getPropagatingSignals(); std::vector<PropagatingSignal *> propagatingSignals = ps->getPropagatingSignalsForFunctionNamed(funcName); stripInvalidCharacters(funcName); // Iterate through propagating signals and add wires and states for them // for (std::vector<PropagatingSignal *>::iterator si = propagatingSignals.begin(); si != propagatingSignals.end(); ++si) { PropagatingSignal *propSignal = *si; std::string signalType = propSignal->getType(); // TODO: Instead, use parallelInstances variable and generate arbitrator // if (propSignal->isMemory() && usesPthreads) continue; // if the signal is an output, only one module can have access to it // at a single time, so we must add it to the state machine // if (signalType == "output") { RTLSignal *connection = rtl->addWire(funcName + "_" + propSignal->getName(), propSignal->getSignal()->getWidth()); RTLSignal *outputPort; outputPort = rtl->find(propSignal->getName()); connectSignalToDriverInState(outputPort, connection, state1, CI, INPUT_READY, true); } } } // calling semantics: when calling a function there are 2 states // 1) assign inputs/outputs of the module. set start=1 // 2) wait until finish=1 // make sure ram signals registers are connected void GenerateRTL::createFunction(CallInst &I) { CallInst *CI = &I; Function *called = getCalledFunction(CI); // get the number of parallel instances of this function std::string functionType = getMetadataStr(CI, "TYPE"); int numThreads = getNumThreads(CI); State *callState, *callEndState = NULL; bool isStateTerminating; createStateTransitions(CI, callState, callEndState, isStateTerminating); std::string moduleName = verilogName(called); createStartSignal(CI, callState, moduleName, numThreads, functionType); std::string name = moduleName + "_" + "memory_controller"; if (functionType != "legup_wrapper_pthreadpoll") { // setting up argument signals createArgumentSignals(CI, called, moduleName, numThreads, functionType); // MATHEW: Is there a better way to do this? if (!(LEGUP_CONFIG->isCustomVerilog(*called) && !(LEGUP_CONFIG->customVerilogUsesMemory(*called)))) { // Setting up the memory controller signals createFunctionMemorySignals(callState, CI, name, "_a", numThreads, functionType); createFunctionMemorySignals(callState, CI, name, "_b", numThreads, functionType); // create waitrequest logic createWaitrequestLogic(CI, callState, name, numThreads, functionType); } // MATHEW: Please generalize this to work for openmp if (functionType != "legup_wrapper_omp" && functionType != "omp_function") { // setting up propagating signals createFunctionPropagatingSignals(callState, CI, name, numThreads, functionType); } } createFinishSignal(CI, callState, callEndState, moduleName, numThreads, functionType); createReturnSignal(callState, CI, called, moduleName, numThreads, functionType); // signal for disabling the divider and other multicycle functional units // for two states while we call the function RTLSignal *fct_call = rtl->addWire("legup_function_call"); fct_call->setDefaultDriver(ZERO); connectSignalToDriverInState(fct_call, ONE, callState, CI); if (isStateTerminating) { connectSignalToDriverInState(fct_call, ONE, callEndState, CI); } } void GenerateRTL::visitCallInst(CallInst &CI) { Function *called = getCalledFunction(&CI); if (called->getName() == "printf" || called->getName() == "puts") { visitPrintf(&CI, called); } else if (called->getName() == "putchar") { unsigned char C = cast<ConstantInt>(CI.getOperand(1))->getZExtValue(); bool LastWasHex = false; RTLOp *write = rtl->addOp(RTLOp::Write); write->setOperand(0, rtl->addConst(charToString(C, LastWasHex))); connectSignalToDriverInState(rtl->getUnsynthesizableSignal(), write, this->state, &CI); } else if (called->getName() == "exit") { RTLSignal *finish = rtl->addOp(RTLOp::Finish); connectSignalToDriverInState(rtl->getUnsynthesizableSignal(), finish, this->state, &CI); } else if (isaDummyCall(&CI)) { // ignore } else { // normal function calls are already handled by generateAllCallInsts } } // get the first state of this basic block State *GenerateRTL::getFirstState(BasicBlock *BB) { for (FiniteStateMachine::iterator state = ++fsm->begin(), se = fsm->end(); state != se; ++state) { if (state->getBasicBlock() == BB) return state; } assert(0 && "Couldn't find state for BB"); } void GenerateRTL::modifyFSMForAllLoopPipelines() { std::set<BasicBlock *> visited; for (FiniteStateMachine::iterator state = ++fsm->begin(), se = fsm->end(); state != se; ++state) { for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { BasicBlock *BB = (*instr)->getParent(); if (visited.find(BB) != visited.end()) continue; visited.insert(BB); if (getMetadataInt(BB->getTerminator(), "legup.pipelined")) { this->pipelinedBBs.insert(BB); assert(getFirstState(BB) == state); } } } for (std::set<BasicBlock *>::iterator BB = this->pipelinedBBs.begin(), be = this->pipelinedBBs.end(); BB != be; ++BB) { modifyFSMForLoopPipeline(*BB); } } void GenerateRTL::generateAllLoopPipelines() { pipeRTLFile() << "Found " << this->pipelinedBBs.size() << " loops to pipeline\n"; for (std::set<BasicBlock *>::iterator BB = this->pipelinedBBs.begin(), be = this->pipelinedBBs.end(); BB != be; ++BB) { generateLoopPipeline(*BB); } } // there are two possibilities for the loop bounds: // 1) there is a constant bound - just use the tripCount from the metadata // 2) there is a variable bound - use LoopInfo to get the tripCount LLVM value // The LLVM IR will look like: // %indvar = phi i32 [ %indvar.next, %.lr.ph ], [ 0, %.lr.ph.preheader ] // %indvar.next = add i32 %indvar, 1 // %exitcond = icmp eq i32 %13, %bound RTLSignal* GenerateRTL::getLoopExitCond(BasicBlock *BB, RTLSignal *indvar) { const Instruction *inductionVar = getInductionVar(BB); RTLWidth inductionWidth = RTLWidth(inductionVar->getType()); TerminatorInst *TI = BB->getTerminator(); RTLSignal *bound = NULL; int tripCount = getMetadataInt(TI, "legup.tripCount"); if (tripCount > 0) { pipeRTLFile() << "Constant tripCount: " << tripCount << "\n"; bound = new RTLConst(utostr(tripCount - 1), inductionWidth); } else { LoopInfo *LI = alloc->getLI(BB->getParent()); assert(LI); Loop *loop = LI->getLoopFor(BB); // TODO: LLVM 3.4 update: getTripCount() has been removed. // reproduce it here to get same functionality //Value *tripCountVal = loop->getTripCount(); Value *tripCountVal = 0; PHINode *IV = loop->getCanonicalInductionVariable(); if (IV == 0 || IV->getNumIncomingValues() != 2) { tripCountVal = 0; } else { bool P0InLoop = loop->contains(IV->getIncomingBlock(0)); Value *Inc = IV->getIncomingValue(!P0InLoop); BasicBlock *BackedgeBlock = IV->getIncomingBlock(!P0InLoop); if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator())) { if (BI->isConditional()) { if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { if (ICI->getOperand(0) == Inc) { if (BI->getSuccessor(0) == loop->getHeader()) { if (ICI->getPredicate() == ICmpInst::ICMP_NE) tripCountVal = ICI->getOperand(1); } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) { tripCountVal = ICI->getOperand(1); } } } } } } // TODO: end LLVM 3.4 update changes //errs() << "isLoopSimplifyForm?: " << loop->isLoopSimplifyForm() << "\n"; if (tripCountVal) { pipeRTLFile() << "Variable tripCount: " << *tripCountVal << "\n"; bound = rtl->addOp(RTLOp::Sub)->setOperands( rtl->find(verilogName(tripCountVal)), rtl->addConst("1", inductionWidth)); } else { // use the signals manually. For instance (%13 is loop-invariant // from outside the loop BB): // %tmp248 = add i32 %tmp178, %indvar237 // %16 = icmp sgt i32 %tmp248, %13 // br i1 %16, label %loopexit, label %loop //assert(TI->getNumTransitions() == 2); // ICmpInst *cmp = dyn_cast<ICmpInst>(TI->getOperand(0)); assert(cmp); Value *op0val = cmp->getOperand(0); Value *op1val = cmp->getOperand(1); State *pipelineWaitState = getFirstState(BB); assert(pipelineWaitState->isWaitingForPipeline()); RTLSignal *op0 = NULL; if (isPipelined(op0val)) { op0 = getPipelineSignal(op0val, 0); assert( op0 && "Branch condition operation not available at time=0"); } else { op0 = getOp(pipelineWaitState, op0val); } RTLSignal *op1 = NULL; if (isPipelined(op1val)) { op1 = getPipelineSignal(op1val, 0); assert( op1 && "Branch condition operation not available at time=0"); } else { op1 = getOp(pipelineWaitState, op1val); } return rtl->addOp(cmp)->setOperands(op0, op1); } } return rtl->addOp(RTLOp::EQ)->setOperands(indvar, bound); } // if the function has memory then returns waitrequest signal // otherwise returns 0 (to ignore the waitrequest) RTLSignal* GenerateRTL::getWaitRequest(Function *F) { PropagatingSignals *ps = alloc->getPropagatingSignals(); RTLSignal *waitrequest; std::string functionName = F->getName().str(); if (ps->functionUsesMemory(functionName)) { waitrequest = rtl->find("memory_controller_waitrequest"); } else { waitrequest = ZERO; } return waitrequest; } // this function generates all the control signals and registers // required for the loop pipeline for basic block BB // the main control signals are: // ii_state = 0, 1, 2, 3, ..., II-1, 0, 1, 2, ..., II-1, ... // valid_bit_0 -> valid_bit_1 -> ... -> valid_bit_maxTime (shift register) // using these signals you can turn on an operation for a particular stage of // the pipeline. valid_bit makes sure the inputs are valid for that time slot, // and the ii_state makes sure you only perform the operation once per pipeline // stage. // void GenerateRTL::generateLoopPipeline(BasicBlock *BB) { const Instruction *inductionVar = getInductionVar(BB); //rtl->addRegLEGUP_pipeline_start TerminatorInst *TI = BB->getTerminator(); int II = getMetadataInt(TI, "legup.II"); int totalTime = getMetadataInt(TI, "legup.totalTime"); int maxStage = getMetadataInt(TI, "legup.maxStage"); // std::string label = getMetadataStr(TI, "legup.label"); std::string label = getPipelineLabel(BB); // generate valid bits pipeRTLFile() << "Generating Loop Pipeline for label: \"" << label << "\"\n"; pipeRTLFile() << "BB: " << getLabel(BB) << "\n"; pipeRTLFile() << "II: " << II << "\n"; pipeRTLFile() << "Time: " << totalTime << "\n"; pipeRTLFile() << "maxStage: " << maxStage << "\n"; pipeRTLFile() << "Induction var: " << *inductionVar << "\n"; pipeRTLFile() << "Label: " << label << "\n"; RTLSignal *waitrequest = rtl->addOp(RTLOp::EQ)->setOperands( getWaitRequest(BB->getParent()), ZERO); RTLSignal *start = rtl->addWire(label + "_pipeline_start"); start->setDefaultDriver(ZERO); start->addCondition(rtl->find("reset"), ZERO); // started bit is high when pipeline is active RTLSignal *started = rtl->addReg(label + "_started"); started->addCondition(rtl->find("reset"), ZERO); // begin = (start & ~started & ~waitrequest) RTLOp *not_started = rtl->addOp(RTLOp::Not)->setOperands(started); RTLOp *begin = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::And)->setOperands(start, not_started)); // RTLOp *begin = rtl->addOp(RTLOp::And)->setOperands(start, not_started); started->addCondition(begin, ONE); // ii_state = 0, 1, 2, 3, ..., II-1, 0, 1, 2, ..., II-1, ... RTLWidth ii_state_width = RTLWidth(requiredBits(II - 1)); RTLSignal *ii_state = rtl->addReg(label + "_ii_state", ii_state_width); ii_state->addCondition(rtl->find("reset"), new RTLConst("0", ii_state_width)); ii_state->addCondition(begin, new RTLConst("0", ii_state_width)); for (int i = 1; i <= II; i++) { // ii_state == i-1 RTLOp *eq = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst(utostr(i - 1), ii_state_width))); // RTLOp *eq = rtl->addOp(RTLOp::EQ)->setOperands( ii_state, new // RTLConst(utostr(i-1), ii_state_width)); int next = (i == II) ? 0 : i; ii_state->addCondition(eq, new RTLConst(utostr(next), ii_state_width)); } // generate induction variable for stages map<int, RTLSignal*> inductionVarStages; // can't use this minimum width - if the induction variable gets used // by another instruction there will be a bitwidth mismatch //RTLWidth inductionWidth = RTLWidth(requiredBits(tripCount-1)); RTLWidth inductionWidth = RTLWidth(inductionVar->getType()); RTLConst *ZERO_induction = new RTLConst("0", inductionWidth); inductionVarStages[0] = rtl->addReg(label + "_i_stage0", inductionWidth); inductionVarStages[0]->addCondition(rtl->find("reset"), ZERO_induction); // epilogue bit is high when the epilogue has started RTLSignal *epilogue = rtl->addReg(label + "_epilogue"); epilogue->addCondition(rtl->find("reset"), ZERO); // generate the valid shift register // high when data is valid on the pipeline step /* valid_bit_1 <= valid_bit_0; valid_bit_2 <= valid_bit_1; valid_bit_3 <= valid_bit_2; valid_bit_4 <= valid_bit_3; valid_bit_5 <= valid_bit_4; valid_bit_6 <= valid_bit_5; */ std::vector<RTLSignal *> validBits; for (int i = 0; i < totalTime; i++) { validBits.push_back(rtl->addReg(label + "_valid_bit_" + utostr(i))); if (i > 0) { //intialize on reset validBits.at(i)->addCondition(waitrequest, validBits.at(i - 1)); //validBits.at(i)->connect(validBits.at(i-1)); validBits.at(i)->addCondition(rtl->find("reset"), ZERO); //reset needs to be added after to avoid X assertion } } // if (start & ~started) // i_stage0 <= 0; inductionVarStages[0]->addCondition(begin, ZERO_induction); RTLOp *lastII = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst(utostr(II - 1), ii_state_width))); // RTLOp *lastII = rtl->addOp(RTLOp::EQ)->setOperands( ii_state, new // RTLConst(utostr(II-1), ii_state_width)); RTLOp *incrementCond = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::And)->setOperands(lastII, validBits.at(II - 1))); // RTLOp *incrementCond = rtl->addOp(RTLOp::And)->setOperands( lastII, // validBits.at(II-1)); RTLOp *incrementInduction = rtl->addOp(RTLOp::Add)->setOperands( inductionVarStages[0], ONE); // else if (ii_state == 2 & valid_bit_2 == 1) // i_stage0 <= i_stage0 + 1; inductionVarStages[0]->addCondition(incrementCond, incrementInduction); /* if (ii_state == 2) begin i_stage1 <= i_stage0; i_stage2 <= i_stage1; end */ for (int i = 1; i <= maxStage; i++) { inductionVarStages[i] = rtl->addReg(label + "_i_stage" + utostr(i), inductionWidth); inductionVarStages[i]->addCondition(begin, ZERO_induction); inductionVarStages[i]->addCondition(lastII, inductionVarStages[i - 1]); } // add reset logic for (int i = 0; i <= maxStage; i++) { inductionVarStages[i]->addCondition(rtl->find("reset"), ZERO_induction); } //rtl->find(verilogName(inductionVar)+"_reg")->connect(inductionVarStages[maxStage]); // every variable which gets used in another stage must be flopped findAllPipelineStageRegisters(BB); RTLSignal *exitCondBoundCheck = rtl->addWire(label + "_pipeline_exit_cond"); exitCondBoundCheck->connect(getLoopExitCond(BB, inductionVarStages[0])); //RTLSignal *exitcond = rtl->find(verilogName(TI->getOperand(0))); RTLOp *exitcond = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::And)->setOperands(started, rtl->addOp(RTLOp::And)->setOperands( // don't check the loop bound until we have completed at // least II cycles rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst("0", ii_state_width)), exitCondBoundCheck))); /* RTLOp *exitcond = rtl->addOp(RTLOp::EQ)->setOperands( inductionVarStages[0], new RTLConst(utostr(tripCount-1), inductionWidth));*/ RTLSignal *not_exitcond = rtl->addOp(RTLOp::Not)->setOperands(exitcond); epilogue->addCondition(exitcond, ONE); // if ((start & ~started) | (started & ~epilogue & i_stage0 != 3)) RTLSignal *not_epilogue = rtl->addOp(RTLOp::Not)->setOperands(epilogue); RTLSignal *done1 = rtl->addOp(RTLOp::And)->setOperands(started, not_epilogue); // RTLSignal *done2 = rtl->addOp(RTLOp::And)->setOperands(waitrequest, // rtl->addOp(RTLOp::And)->setOperands(done1, not_exitcond)); RTLSignal *done2 = rtl->addOp(RTLOp::And)->setOperands(done1, not_exitcond); RTLSignal *valid = rtl->addOp(RTLOp::Or)->setOperands(begin, done2); // validBits.at(0)->connect(valid); //validBits.at(0)->addCondition(rtl->addOp(RTLOp::EQ)->setOperands(rtl->find("reset"), ZERO), valid); // validBits.at(0)->setDefaultDriver(valid); validBits.at(0)->addCondition(waitrequest, valid); validBits.at(0)->addCondition(rtl->find("reset"), ZERO); //reset needs to added after to avaid X assertion RTLOp *finishCond2 = NULL; if (totalTime == 1) { // only one valid bit finishCond2 = rtl->addOp(RTLOp::Not)->setOperands(validBits.at(0)); } else { // check prior two valid bits finishCond2 = rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::Not)->setOperands( validBits.at(totalTime - 2)), validBits.at(totalTime - 1)); } RTLOp *finishCond = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::And)->setOperands(epilogue, finishCond2)); RTLSignal *finish = rtl->addWire(label + "_pipeline_finish"); finish->connect(finishCond); epilogue->addCondition(finishCond, ZERO); started->addCondition(finishCond, ZERO); State *pipelineWaitState = getFirstState(BB); assert(pipelineWaitState->isWaitingForPipeline()); pipelineWaitState->setTransitionSignal( rtl->find(label + "_pipeline_finish")); // connect the phi_temp register for cross-iteration dependencies for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { if ((Instruction*) I == inductionVar) continue; if (PHINode *phi = dyn_cast<PHINode>(I)) { // we need to connect the phi to the incoming value RTLSignal *phi_reg = rtl->addReg(verilogName(phi) + "_reg", RTLWidth(phi->getType())); RTLSignal *phi_wire = rtl->find(verilogName(phi)); Instruction *IV = dyn_cast<Instruction>( phi->getIncomingValueForBlock(BB)); assert(IV); int incomingTime = getMetadataInt(IV, "legup.pipeline.avail_time"); RTLSignal *ii_state = rtl->find(label + "_ii_state"); // connect the phi_temp register to the incoming value as soon // as it is available RTLOp *cond = rtl->addOp(RTLOp::And)->setOperands(waitrequest, rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst(utostr(incomingTime % II), ii_state->getWidth())), rtl->find( label + "_valid_bit_" + utostr(incomingTime)))); this->time = incomingTime; phi_wire->addCondition(cond, getOp(pipelineWaitState, IV), phi); phi_reg->addCondition(cond, phi_wire, phi); } } } // every variable which gets used in another stage must be flopped // this function populates pipelineSignalAvailableTable void GenerateRTL::findAllPipelineStageRegisters(BasicBlock *BB) { const Instruction *inductionVar = getInductionVar(BB); TerminatorInst *TI = BB->getTerminator(); int totalTime = getMetadataInt(TI, "legup.totalTime"); int II = getMetadataInt(TI, "legup.II"); std::string label = getPipelineLabel(BB); RTLSignal *waitrequest = rtl->addOp(RTLOp::EQ)->setOperands( getWaitRequest(BB->getParent()), ZERO); // every variable which gets used in another stage must be flopped for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { if ((Instruction*) I == inductionVar) continue; int startTime = getMetadataInt(I, "legup.pipeline.start_time"); int timeAvail = getMetadataInt(I, "legup.pipeline.avail_time"); int expectedAvailTime = startTime + Scheduler::getNumInstructionCycles(I); assert(timeAvail < totalTime); int maxTimeUse = -1; int minTimeUse = 1e6; for (Value::user_iterator ui = I->user_begin(), ue = I->user_end(); ui != ue; ++ui) { Instruction *I2 = dyn_cast<Instruction>(*ui); if (!I2) continue; if (I2->getParent() != BB) continue; int time2 = getMetadataInt(I2, "legup.pipeline.start_time"); if (isa<PHINode>(I2)) { // the current instruction gets used by a phi node time2 = timeAvail; } maxTimeUse = max(maxTimeUse, time2); minTimeUse = min(minTimeUse, time2); } // never used in the pipelined basic block if (maxTimeUse == -1) continue; assert(minTimeUse != 1e6); initializePipelineSignal(I, totalTime); // this saves a bunch of registers by only using registers on the // pipeline stage boundaries. Instead of using a register for every // single time step bool saveRegisters = LEGUP_CONFIG->getParameterInt("PIPELINE_SAVE_REG"); if (timeAvail != expectedAvailTime) { // this is caused when we have an operation, say an 'add' that // is normally chained in this scheduler. But since IMS doesn't // support chaining, the IMS schedules the add into the next // cycle. We need to build up the register from the add wire // to the add pipeline stage registers assert(timeAvail == expectedAvailTime + 1); timeAvail = expectedAvailTime; } int iiAvail = timeAvail % II; if (saveRegisters) { setPipelineSignal(I, timeAvail, rtl->find(verilogName(I))); std::set<int> stageSeen; for (int i = timeAvail + 1; i <= maxTimeUse; i++) { int stage = i / II; if (stageSeen.find(stage) == stageSeen.end()) { // create a new pipeline stage register stageSeen.insert(stage); setPipelineSignal(I, i, rtl->addReg( verilogName(I) + "_reg_stage" + utostr(stage), RTLWidth(I->getType()))); RTLSignal *ii_state = rtl->find(label + "_ii_state"); int iiCond = II - 1; if (i == timeAvail + 1) { // the first stage register, 1 cycle after available // time might be in the middle of a stage iiCond = iiAvail; } RTLOp *cond = rtl->addOp(RTLOp::And)->setOperands( waitrequest, rtl->addOp(RTLOp::And)->setOperands( rtl->addOp(RTLOp::EQ)->setOperands(ii_state, new RTLConst(utostr(iiCond), ii_state->getWidth())), rtl->find( label + "_valid_bit_" + utostr(i - 1)))); getPipelineSignal(I, i)->addCondition(cond, getPipelineSignal(I, i - 1)); } else { // still in the same stage setPipelineSignal(I, i, getPipelineSignal(I, i - 1)); } } } else { setPipelineSignal(I, timeAvail, rtl->find(verilogName(I))); // build a shift register to hold the previous values for (int i = timeAvail + 1; i <= maxTimeUse; i++) { RTLSignal *reg_time = rtl->addReg( verilogName(I) + "_reg_time" + utostr(i), RTLWidth(I->getType())); RTLSignal *prev = getPipelineSignal(I, i - 1); if (i == timeAvail + 1) { // need to add a condition on the first one... RTLSignal *reg_time_wire = rtl->addWire( verilogName(I) + "_reg_time_wire" + utostr(i), RTLWidth(I->getType())); reg_time_wire->setDefaultDriver(ZERO); RTLOp *pipelineCond = getPipelineStateCondition( reg_time_wire, I, OUTPUT_READY); reg_time_wire->addCondition(pipelineCond, prev, I); reg_time->connect(reg_time_wire); } else { reg_time->connect(prev); } setPipelineSignal(I, i, reg_time); } } // special case phi nodes if (PHINode *phi = dyn_cast<PHINode>(I)) { Instruction *IV = dyn_cast<Instruction>( phi->getIncomingValueForBlock(BB)); assert(IV); int incomingTime = getMetadataInt(IV, "legup.pipeline.avail_time"); /* errs() << "pipelineSignalAvailableTable for: " << *phi << "\n"; errs() << "timeAvail: " << timeAvail << "\n"; errs() << "maxTimeUse: " << maxTimeUse << "\n"; errs() << "minTimeUse: " << minTimeUse << "\n"; errs() << "incomingTime: " << incomingTime << "\n"; errs() << "II: " << II << "\n"; */ // consider the case of a schedule of a phi node: // II = 3 // t = 0 1 2 | 3 4 5 | 6 7 8 | 9 10 11 | // X X // where | = pipeline stage register // The phi node isn't updated with an incoming value from the loop // basic block (BB) until t=7, ii=1 (incomingTime = 7) // Lets assume now an instruction uses the phi as an operand at the // time given below: // first iteration: // t = 0: impossible, the phi operand wouldn't work in second // iteration (phi would stay the same) // t = 1: impossible // t = 2: impossible // second iteration: // t = 3: impossible // t = 4: possible - *only* if you use the wire attached to the phi // in this case, you'll get first get the default phi value // (from outside loop) in this iteration (2nd). And get the // updated value from the phi node in the 3rd iteration. // **** this is time: incomingTime - II // t = 5: possible - must use phi register // third iteration: // t = 6: possible - must use phi register // t = 7: possible - must use phi register // t = 8: possible - but, now must use the phi value stored in the // pipeline stage register 2 (i / II = 8 / 3 = 2) assert(minTimeUse >= (incomingTime - II)); assert(timeAvail >= (incomingTime - II)); RTLSignal *phi_wire = rtl->find(verilogName(phi)); RTLSignal *phi_reg = rtl->find(verilogName(phi) + "_reg"); for (int i = timeAvail; i <= maxTimeUse; i++) { RTLSignal *avail = phi_reg; if (i == incomingTime - II) { avail = phi_wire; } else if (i > incomingTime) { stage = i / II; avail = rtl->find( verilogName(I) + "_reg_stage" + utostr(stage)); } setPipelineSignal(phi, i, avail); //errs() << "\t" << i << ": " << // getPipelineSignal(phi, i)->getName() << "\n"; } } } } // this function deletes all the existing states of BB // except the very first state. This state is renamed // to LEGUP_loop_pipeline_wait. // All instructions are deleted from this state - so it is empty // This state has two transitions: // pipeline_finish is false: loop back to itself // pipeline_finish is true: transition to the next basic block // outside the loop // this state also has a special flag: isWaitingForPipeline(), for // generateDatapath() to create the pipeline // void GenerateRTL::modifyFSMForLoopPipeline(BasicBlock *BB) { State *pipelineWaitState = getFirstState(BB); //const Instruction *inductionVar = getInductionVar(BB); //int II = getPipelineII(BB); // delete everything up until the terminating state of the basic block if (!pipelineWaitState->isTerminating()) { assert(pipelineWaitState->getNumTransitions() == 1); // find first state FiniteStateMachine::iterator i = fsm->begin(); while ((State*) i != pipelineWaitState) { ++i; } // don't delete first state ++i; // delete all states after first state while (i != fsm->end()) { if (i->isTerminating()) { // preserve FSM transition information in first state State *terminatingState = i; State::Transition origTransition = terminatingState->getTransition(); pipelineWaitState->setTransition(origTransition); pipelineWaitState->setTerminating(true); i = fsm->erase(i); break; } else { i = fsm->erase(i); } } } // what's the next state after this basic block? // one of the transitions should be back to this basic block (a loop) // the other transition is what we want to know (nextStateAfterBB) assert(pipelineWaitState->isTerminating()); assert(pipelineWaitState->getNumTransitions() == 2); State *nextStateAfterBB = getStateAfterLoop(pipelineWaitState); // delete all instructions from pipelineWaitState (except phi nodes) // this is so they don't get iterated over in generateDatapath() // don't delete phi nodes so generatePHICopiesForSuccessor() works for // the predecessor basic block of the pipelined loop State::iterator j = pipelineWaitState->begin(); unsigned size = pipelineWaitState->size(); for (unsigned i = 0; i < size; i++) { if (isa<PHINode>(*j)) { j++; } else { j = pipelineWaitState->erase(j); } } std::string label = getPipelineLabel(BB); FiniteStateMachine* fsm = sched->getFSM(Fp); pipeRTLFile() << "Changing state name of '" << pipelineWaitState->getName() << "' to '"; pipelineWaitState->setName("LEGUP_loop_pipeline_wait_" + label); pipeRTLFile() << pipelineWaitState->getName() << "'\n"; pipelineWaitState->setWaitingForPipeline(true); // need to clear all original transitions. // where must wait for the pipeline to complete. assert(pipelineWaitState->getBasicBlock() == BB); State::Transition blank; pipelineWaitState->setTransition(blank); pipelineWaitState->setDefaultTransition(pipelineWaitState); pipelineWaitState->addTransition(nextStateAfterBB); // all instructions should be executed in pipelineWaitState - while we wait for the // pipeline to finish for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { fsm->setStartState(I, pipelineWaitState); fsm->setEndState(I, pipelineWaitState); } } raw_fd_ostream &GenerateRTL::pipeRTLFile() { return alloc->getPipeliningRTLFile(); } raw_fd_ostream &GenerateRTL::File() { return alloc->getGenerateRTLFile(); } // Adjust Finite State Machine for function calls void GenerateRTL::generateAllCallInsts() { std::set<CallInst *> visited; FiniteStateMachine *fsm = sched->getFSM(Fp); for (FiniteStateMachine::iterator state = ++fsm->begin(), se = fsm->end(); state != se; ++state) { State::iterator instr = state->begin(); while (instr != state->end()) { CallInst *CI = dyn_cast<CallInst>(*instr); if (CI && !isaDummyCall(CI) & !visited.count(CI)) { this->state = state; // create states and signals for this function createFunction(*CI); // create and connect threadID, functionID, // finish and return_val signals for pthread functions createPthreadSignals(CI); instr = state->remove(CI); visited.insert(CI); } else { ++instr; } } } } // print out the finite state machine void GenerateRTL::printFSMDot() { std::string fileName = "fsm." + rtl->getName() + ".dot"; printFSMDotFile(sched->getFSM(Fp), fileName); } // Update state width to account for called functions void GenerateRTL::updateStatesAfterCallInsts() { unsigned stateNum = fsm->getNumStates(); assert(stateNum > 0); // remember that states are from 0 to stateNum-1 unsigned statewidth = requiredBits(stateNum - 1); if (!LEGUP_CONFIG->getParameterInt("CASEX")) statewidth = requiredBits(stateNum - 1); else // If we are using CASEX then we set the state codes in a "one hot" style instead of binary encoding statewidth = stateNum; rtl->find("cur_state")->setWidth(RTLWidth(statewidth)); // this code uses Verilog "parameter" statements // to give a numerical value to each state name // the state names are, in essence, an enumerated type unsigned stateCount = 0; FiniteStateMachine::iterator stateIter = fsm->begin(); for (; stateIter != fsm->end(); stateIter++) { State* s = stateIter; // append the state number to the end of the state name parameter std::string pName = s->getName() + "_" + utostr(stateCount); s->setName(pName); RTLSignal *stateParam = getStateSignal(s); stateParam->setName(pName); stateParam->setWidth(RTLWidth(statewidth)); if (!LEGUP_CONFIG->getParameterInt("CASEX")) stateParam->setValue(utostr(stateCount)); else { // So, when we are using CASEX for the state machine, we need two sets of parameters // the first looks like this: // LEGUP_STATE2 10'b0000100000 // and the second looks like this: // LEGUP_STATE2_X 10'bxxxx1xxxxx // The first set is used in state assignements. // The second set is used in the casex(...) conditions. #if 0 // janders: old way of doing the param name generation -- see new way below std::string stateParamName = utostr(stateNum); std::string stateParamNameX = utostr(stateNum); stateParamName = stateParamName + "'b"; stateParamNameX = stateParamNameX + "'b"; for (int i = statewidth-1; i >= 0; i--) if (i == stateCount) { stateParamName = stateParamName + "1"; stateParamNameX = stateParamNameX + "1"; } else { stateParamName = stateParamName + "0"; stateParamNameX = stateParamNameX + "x"; } #endif // incorporate Lanny's suggestion to avoid long strings of 0's and x's in the params // but using the concatenation construct in Verilog std::string stateParamName = "{"; std::string stateParamNameX = "{"; // leading 0's and x's on the param if (stateNum - stateCount - 1 > 0) { stateParamName = stateParamName + utostr(stateNum - stateCount - 1) + "'b0, "; stateParamNameX = stateParamNameX + utostr(stateNum - stateCount - 1) + "'bx, "; } // the one-hot bit stateParamName = stateParamName + "1'b1"; stateParamNameX = stateParamNameX + "1'b1"; // trailing 0's and x's on the param if (stateCount) { stateParamName = stateParamName + ", " + utostr(stateCount) + "'b0"; stateParamNameX = stateParamNameX + ", " + utostr(stateCount) + "'bx"; } stateParamName = stateParamName + "}"; stateParamNameX = stateParamNameX + "}"; stateParam->setValue(stateParamName); RTLSignal *casexParam = rtl->addParam(pName + "_X", stateParamNameX); casexParam->setWidth(RTLWidth(statewidth)); } stateCount++; } // some states might have been removed, delete the parameter placeholders rtl->remove("state_placeholder"); } RTLSignal *GenerateRTL::getLeftHandSide(Instruction *instr) { RTLWidth w(instr, MBW); RTLSignal *instSig = rtl->addWire(verilogName(instr), w); if (!rtl->exists(verilogName(instr) + "_reg") && usedAcrossStates(instr, this->state)) { // need a wire for chaining RTLSignal *instReg = rtl->addReg(verilogName(instr) + "_reg", w); connectSignalToDriverInState(instReg, instSig, this->state, instr, OUTPUT_READY); } return instSig; } void GenerateRTL::visitSelectInst(SelectInst &I) { RTLSignal *instSig = getLeftHandSide(&I); RTLOp *FU = rtl->addOp(RTLOp::Sel); FU->setOperand(0, getOp(this->state, I.getOperand(0))); FU->setOperand(1, getOp(this->state, I.getOperand(1))); FU->setOperand(2, getOp(this->state, I.getOperand(2))); connectSignalToDriverInState(instSig, FU, this->state, &I); } bool GenerateRTL::isMultipumped(Instruction *I) { return (isMul(I) && MULTIPUMPING && multipumpOperations.find(I) != multipumpOperations.end()); } RTLSignal *GenerateRTL::createBindingFU(Instruction *instr, RTLSignal *op0, RTLSignal *op1) { RTLSignal *FU; std::string fuId = this->binding->getBindingInstrFU(instr); bool binOp = instr->isBinaryOp(); //*** Don't know about change to Multipump... Joy //*** Check for binary operation if (isMultipumped(instr)) { //errs() << "I: " << *instr << "\n"; // use multipump multiplier MultipumpOperation &multipump = multipumpOperations[instr]; std::string fuOutput = multipump.out; //errs() << fuOutput << "\n"; unsigned size = MBW->getMinBitwidth(instr->getOperand(0)); if (binOp) { size = max(MBW->getMinBitwidth(instr->getOperand(0)), MBW->getMinBitwidth(instr->getOperand(1))); } RTLOp *trunc_op0 = rtl->addOp(RTLOp::Trunc); trunc_op0->setCastWidth(size); trunc_op0->setOperand(0, op0); RTLOp *trunc_op1; if (binOp) { trunc_op1 = rtl->addOp(RTLOp::Trunc); trunc_op1->setCastWidth(size); trunc_op1->setOperand(0, op1); } connectSignalToDriverInState(rtl->find(multipump.op0), trunc_op0, this->state, instr); if (binOp) { connectSignalToDriverInState(rtl->find(multipump.op1), trunc_op1, this->state, instr); } FU = rtl->find(fuOutput); } else { connectSignalToDriverInState(rtl->find(fuId + "_op0"), op0, this->state, instr); if (binOp) { connectSignalToDriverInState(rtl->find(fuId + "_op1"), op1, this->state, instr); } FU = rtl->find(fuId); // Also, if this is a divider or remainder, and dividers are // multi-cycled, remember that we also need to multi-cycle // this instruction if (isDiv(instr) || isRem(instr)) { if (LEGUP_CONFIG->getParameterInt( "MULTI_CYCLE_REMOVE_REG_DIVIDERS")) { // Insert multi-cycle constraints for this divider after binding alloc->add_multicycled_divider(instr); } } } return FU; } std::string GenerateRTL::getEnableName(Instruction *instr) { std::string en_name; if (isDiv(instr) || isRem(instr)) { en_name = "lpm_divide_"; } else if (isFPArith(instr) || isFPCmp(instr) || isFPCast(instr)) { en_name = "altfp_"; } else { en_name = "lpm_mult_"; } en_name += verilogName(instr) + "_en"; return en_name; } // we must take into account the waitrequest signal: it could take 100 // cycles just to get to the next state. // also need to disable the divider while making function calls // TODO: should only be enabled when being used to save power void GenerateRTL::create_fu_enable_signals(Instruction *instr) { RTLSignal *en = rtl->addWire(getEnableName(instr)); PropagatingSignals *ps = alloc->getPropagatingSignals(); bool functionUsesMemory = ps->functionUsesMemory(Fp->getName()) || usesPthreads; // wait_done = 1 when waitrequest == 0 RTLOp *wait_done; if (functionUsesMemory) { wait_done = rtl->addOp(RTLOp::EQ); wait_done->setOperand(0, rtl->find("memory_controller_waitrequest")); wait_done->setOperand(1, ZERO); } else { wait_done = rtl->addOp(RTLOp::EQ); wait_done->setOperand(0, ZERO); wait_done->setOperand(1, ZERO); } if (rtl->exists("legup_function_call")) { RTLOp *fct_done = rtl->addOp(RTLOp::EQ); fct_done->setOperand(0, rtl->find("legup_function_call")); fct_done->setOperand(1, ZERO); RTLOp *div_en = rtl->addOp(RTLOp::And); div_en->setOperand(0, wait_done); div_en->setOperand(1, fct_done); en->connect(div_en); } else { en->connect(wait_done); } } // visitBinaryOperator is called on every LLVM binary operation (add, sub, etc) // in the program. This function creates the necessary functional units for the // operation and connects the operation's wire and register to the output of // the function unit during the correct state of the FSM void GenerateRTL::visitBinaryOperator(Instruction &I) { Instruction *instr = &I; // Unfortunately, visitBinaryOperator is called for every instruction // This includes those already bound in createBindingSignals, so we need // to check if this instruction is in a graph and skip it (log lookup // time, but needs to be done for every binary operation...) if (this->InstructionsInGraphs.find(instr) != this->InstructionsInGraphs.end()) { return; } // instWire is the wire associated with this operation. For instance the // LLVM instruction: // %13 = add i32 %6, %4 // Might have a wire named: // main_1_13 // Function: main, Basic Block: %1, Instruction: %13 RTLSignal *instWire = getLeftHandSide(instr); RTLSignal *op0 = getOp(this->state, instr->getOperand(0)); RTLSignal *op1 = getOp(this->state, instr->getOperand(1)); // FU holds the output of the functional unit associated with this operation RTLSignal *FU; if (this->binding->existsBindingInstrFU(instr)) { FU = createBindingFU(instr, op0, op1); } else { FU = createFU(instr, op0, op1); } unsigned pipelineStages = Scheduler::getNumInstructionCycles(instr); if (pipelineStages > 0) { create_fu_enable_signals(instr); // drive the instruction wire signal with the output of the functional // unit making sure the bitwidth is correct instWire->connect(FU); instWire->setWidth(FU->getWidth()); // store the instruction's value in a register during the ending state // of the instruction (when the functional unit output is available). // Now we can access the instruction's value in another cycle by // reading from this register RTLSignal *instReg = rtl->find(verilogName(instr) + "_reg"); connectSignalToDriverInState(instReg, instWire, fsm->getEndState(instr), instr, OUTPUT_READY); } else { assert(pipelineStages == 0); // connect the instruction wire to the functional unit output // during the active state of this operation connectSignalToDriverInState(instWire, FU, this->state, instr); } } // Similar to visitBinaryOperator for handling unary operators // Assumes FP unary operators void GenerateRTL::visitUnaryOperator(CastInst &I) { Instruction *instr = &I; // Unfortunately, visitUnaryOperator is called for every instruction // This includes those already bound in createBindingSignals, so we need // to check if this instruction is in a graph and skip it (log lookup // time, but needs to be done for every binary operation...) if (this->InstructionsInGraphs.find(instr) != this->InstructionsInGraphs.end()) { return; } // instWire is the wire associated with this operation. For instance the // LLVM instruction: // %13 = add i32 %6, %4 // Might have a wire named: // main_1_13 // Function: main, Basic Block: %1, Instruction: %13 RTLSignal *instWire = getLeftHandSide(instr); RTLSignal *op0 = getOp(this->state, instr->getOperand(0)); // Sanity checks for FPToSI/SIToFP if (isa<SIToFPInst>(instr) || isa<FPToSIInst>(instr)) { int int_width = 0; int FP_width = 0; if (isa<SIToFPInst>(instr)) { int_width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); FP_width = I.getDestTy()->getPrimitiveSizeInBits(); } else if (isa<FPToSIInst>(instr)) { int_width = I.getDestTy()->getPrimitiveSizeInBits(); FP_width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); } if (FP_width != 32 && FP_width != 64) { errs() << "Invalid Float type for: " << *instr << "\n"; llvm_unreachable(0); } if (int_width != 32) { errs() << "Invalid Integer type for: " << *instr << "\n"; llvm_unreachable(0); } assert(FP_width == 32 || FP_width == 64); } // FU holds the output of the functional unit associated with this operation RTLSignal *FU; if (this->binding->existsBindingInstrFU(instr)) { FU = createBindingFU(instr, op0, /*op1*/NULL); } else { FU = createFU(instr, op0, /*op1*/NULL); } unsigned pipelineStages = Scheduler::getNumInstructionCycles(instr); assert(pipelineStages > 0); create_fu_enable_signals(instr); // drive the instruction wire signal with the output of the functional // unit making sure the bitwidth is correct instWire->connect(FU); instWire->setWidth(FU->getWidth()); // store the instruction's value in a register during the ending state // of the instruction (when the functional unit output is available). // Now we can access the instruction's value in another cycle by // reading from this register RTLSignal *instReg = rtl->find(verilogName(instr) + "_reg"); connectSignalToDriverInState(instReg, instWire, fsm->getEndState(instr), instr, OUTPUT_READY); } void GenerateRTL::visitFCastInst(CastInst &I) { Instruction *instr = &I; // Unfortunately, visitFCastInst is called for every instruction // This includes those already bound in createBindingSignals, so we need // to check if this instruction is in a graph and skip it (log lookup // time, but needs to be done for every binary operation...) if (this->InstructionsInGraphs.find(instr) != this->InstructionsInGraphs.end()) { return; } RTLSignal *instWire = getLeftHandSide(&I); RTLSignal *op0 = getOp(this->state, instr->getOperand(0)); std::string name; if (dyn_cast<FPTruncInst>(instr)) { name = "altfp_truncate"; } else { name = "altfp_extend"; } RTLSignal *FU = createFP_FU_Helper(name, instr, op0, /*op1=*/NULL, /*fu_module=*/NULL); instWire->connect(FU); instWire->setWidth(FU->getWidth()); RTLSignal *instReg = rtl->find(verilogName(instr) + "_reg"); connectSignalToDriverInState(instReg, instWire, fsm->getEndState(instr), instr, OUTPUT_READY); } void GenerateRTL::visitFPCastInst(CastInst &I) { RTLSignal *instWire = getLeftHandSide(&I); Instruction *instr = &I; // Unfortunately, visitFPCastInst is called for every instruction // This includes those already bound in createBindingSignals, so we need // to check if this instruction is in a graph and skip it (log lookup // time, but needs to be done for every binary operation...) if (this->InstructionsInGraphs.find(instr) != this->InstructionsInGraphs.end()) { return; } int int_width = 0; int FP_width = 0; RTLSignal *op0 = getOp(this->state, instr->getOperand(0)); if (isa<SIToFPInst>(instr)) { int_width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); FP_width = I.getDestTy()->getPrimitiveSizeInBits(); } else if (isa<FPToSIInst>(instr)) { int_width = I.getDestTy()->getPrimitiveSizeInBits(); FP_width = instr->getOperand(0)->getType()->getPrimitiveSizeInBits(); } if (FP_width != 32 && FP_width != 64) { errs() << "Invalid Float type for: " << *instr << "\n"; llvm_unreachable(0); } if (int_width != 32) { errs() << "Invalid Integer type for: " << *instr << "\n"; llvm_unreachable(0); } assert(FP_width == 32 || FP_width == 64); std::string name; if (isa<SIToFPInst>(instr)) { name = "altfp_sitofp"; } else if (isa<FPToSIInst>(instr)) { name = "altfp_fptosi"; } else { assert(0); } name = name + utostr(FP_width); RTLSignal *FU = createFP_FU_Helper(name, instr, op0, /*op1=*/NULL, /*fu_module=*/NULL); instWire->connect(FU); instWire->setWidth(FU->getWidth()); RTLSignal *instReg = rtl->find(verilogName(instr) + "_reg"); connectSignalToDriverInState(instReg, instWire, fsm->getEndState(instr), instr, OUTPUT_READY); } void GenerateRTL::visitCastInst(CastInst &I) { RTLSignal *instSig = getLeftHandSide(&I); Instruction *instr = &I; RTLSignal *op0 = getOp(this->state, instr->getOperand(0)); if (isa<SExtInst>(instr) || isa<ZExtInst>(instr)) { RTLOp *ext = NULL; if (isa<SExtInst>(instr)) { ext = rtl->addOp(RTLOp::SExt); } else { ext = rtl->addOp(RTLOp::ZExt); } ext->setCastWidth(instSig->getWidth()); ext->setOperand(0, op0); connectSignalToDriverInState(instSig, ext, this->state, instr); } else if (isa<TruncInst>(instr)) { RTLOp *trunc = rtl->addOp(RTLOp::Trunc); trunc->setCastWidth(instSig->getWidth()); trunc->setOperand(0, op0); connectSignalToDriverInState(instSig, trunc, this->state, instr); } else if (isa<BitCastInst>(instr) || isa<PtrToIntInst>(instr) || isa<IntToPtrInst>(instr)) { connectSignalToDriverInState(instSig, op0, this->state, instr); } else if (isa<FPToSIInst>(instr) || isa<SIToFPInst>(instr)) { visitFPCastInst(I); } else { errs() << "Unrecognized Instruction: " << *instr << "\n"; llvm_unreachable(0); } } // pairFUsForMultipumpFU() assigns two multiplier FUs from traditional binding // and assigns one to each 'port' of the multipump unit (AxB and CxD) // Also, since multiple instructions can be assigned to a FUs, this function // updates the multipumpOperations map for each instruction assigned to this // multipump unit. Finally the RTL is generated for the multipump unit by // calling createMultiPumpMultiplierFU() // If this is the first multipump unit, the multipump_fu_name would be: // multipump_0 // We also create the signals: // multipump_0_inA // multipump_0_inB // multipump_0_outAxB_actual // multipump_0_outCxD_actual // multipump_0_inC // multipump_0_inD int GenerateRTL::pairFUsForMultipumpFU(std::string FuName1, std::string FuName2, int multipump_fu_num, raw_ostream &out) { int num_multipump_ops = 0; std::string multipump_fu_name = "multipump"; // multipump fu name. For instance "multipump_0" std::string fu = multipump_fu_name + "_" + utostr(multipump_fu_num); MultipumpOperation multipump; multipump.name = fu; multipump.out = fu + "_AxB"; multipump.op0 = fu + "_inA"; multipump.op1 = fu + "_inB"; MultipumpOperation multipump2; multipump2.name = fu; multipump2.out = fu + "_CxD"; multipump2.op0 = fu + "_inC"; multipump2.op1 = fu + "_inD"; out << "Multipump FU: " << fu << ", pairing: " << FuName1 << " and " << FuName2 << "\n"; out << "\tFU1: " << FuName1 << "\n"; std::vector<Instruction*> &FUInsts1 = this->binding->getInstructionsAssignedToFU(FuName1); for (unsigned n = 0; n < FUInsts1.size(); n++) { Instruction *I1 = FUInsts1.at(n); out << "\t\tI: " << *I1 << "\n"; multipumpOperations[I1] = multipump; num_multipump_ops++; } out << "\tFU2: " << FuName2 << "\n"; std::vector<Instruction*> &FUInsts2 = this->binding->getInstructionsAssignedToFU(FuName2); for (unsigned n = 0; n < FUInsts2.size(); n++) { Instruction *I2 = FUInsts2.at(n); out << "\t\tI: " << *I2 << "\n"; multipumpOperations[I2] = multipump2; num_multipump_ops++; } createMultiPumpMultiplierFU(FUInsts1.at(0), FUInsts2.at(0)); return num_multipump_ops; } // createMultipumpSignals() is similar to createBindingSignals but for // multi-pump functional units. // Recall, a multipump multiply unit can perform two multiply operations // per cycle: AxB and CxD (input ports: A, B, C, D) // However, binding has no knowledge of multipumping, so each multiplier FU is // assumed to only perform one multiply operation per cycle. // Hence, the multipump unit is equivalent to *two* normal multiply // functional units from traditional multiplier binding. // This function groups pairs of compatible multiply FUs and assigning // them to the same multi-pump unit. // So there are three levels of datastructures: // 1) Individual multiplier operations -- these correspond to LLVM mul // instructions // 2) Multiplier functional units (FUs) that execute one or more multiplier // operations. Binding determines which multipliers are assigned to a FU. // To get the multiplier FU name for an operation use: // getBindingInstrFU(I) // For instance, if the following two multipliers are paired by binding: // %37 = mul nsw i32 %36, %35 // %28 = mul nsw i32 %27, %26 // getBindingInstrFU(I) might return the FU name: // multipump_main_22_37 // 3) Multi-pump functional units -- to get the signaling information for // a multiply operation use the map: // multipumpOperations[I2] // The multipumpOperations map is updated in pairFUsForMultipumpFU() void GenerateRTL::createMultipumpSignals() { formatted_raw_ostream out(alloc->getMultipumpingFile()); unsigned multipump_fu_num = 0; map<bool, map<unsigned, unsigned> > pairCount; map<bool, map<unsigned, std::string> > prevFU; std::set<std::string> unPairedFUs; // multiplierFUs contains the binding FU name for each multiplier FU // there may be many multipliers assigned to the same multiplier FU std::set<std::string> multiplierFUs; int num_multiply_ops = 0; for (Binding::iterator i = this->binding->begin(), ie = this->binding->end(); i != ie; ++i) { Instruction *I = i->first; if (!isMul(I)) continue; num_multiply_ops++; std::string bindingFU = this->binding->getBindingInstrFU(I); multiplierFUs.insert(bindingFU); } unPairedFUs = multiplierFUs; int num_multipump_ops = 0; // Iterate over all multiply FUs and greedily finds pairs // of compatible FUs to assign to one multipump functional unit. // Compatible multiply operations have the same: // 1. bitwidth (size) // 2. sign (isSigned) // We keep track of the number of multiply operations using the map: // pairCount[isSigned][size] // Once we find two multiply FU to pair then we call pairFUsForMultipumpFU() for (std::set<std::string>::iterator i = multiplierFUs.begin(); i != multiplierFUs.end(); ++i) { std::string fuId = *i; std::vector<Instruction*> &FUInsts = this->binding->getInstructionsAssignedToFU(fuId); Instruction *I = FUInsts.at(0); assert(I); Value *vop0 = I->getOperand(0); Value *vop1 = I->getOperand(1); bool isSigned = false; unsigned size = max(MBW->getMinBitwidth(vop0), MBW->getMinBitwidth(vop1)); unsigned origSize = I->getType()->getPrimitiveSizeInBits(); if (size < origSize) { if (isa<SExtInst>(vop0) && isa<SExtInst>(vop1)) { isSigned = true; } } out << "FU: " << fuId << "\n"; out << "\tFirst inst assigned to FU: " << *I << "\n"; out << "\tisSigned: " << isSigned << "\n"; out << "\tsize: " << size << "\n"; if (LEGUP_CONFIG->getParameterInt("MB_MINIMIZE_HW")) { out << "\tminBW: " << MBW->getMinBitwidth(I) << " - " << *I << "\n"; out << "\tminBW op0: " << MBW->getMinBitwidth(I->getOperand(0)) << " - " << *I->getOperand(0) << "\n"; out << "\tminBW op1: " << MBW->getMinBitwidth(I->getOperand(1)) << " - " << *I->getOperand(1) << "\n"; } if (pairCount[isSigned].find(size) == pairCount[isSigned].end()) { pairCount[isSigned][size] = 0; } pairCount[isSigned][size]++; if (pairCount[isSigned][size] == 2) { std::string prevFuId = prevFU[isSigned][size]; assert(prevFuId != ""); num_multipump_ops += pairFUsForMultipumpFU(prevFuId, fuId, multipump_fu_num, out); multipump_fu_num++; unPairedFUs.erase(prevFuId); unPairedFUs.erase(fuId); pairCount[isSigned][size] = 0; prevFU[isSigned][size] = ""; } else { prevFU[isSigned][size] = fuId; } } if (unPairedFUs.empty()) { assert(num_multiply_ops == num_multipump_ops); } else { out << "Some multiplier FUs were not paired with a multipump unit due " << "to an odd number of multiply FUs or incompatibilities " << "(sign/bitwidth):\n"; for (std::set<std::string>::iterator i = unPairedFUs.begin(), ie = unPairedFUs.end(); i != ie; ++i) { out << "\t" << *i << "\n"; } } } // create necessary signals for binding // also see: visitBinaryOperator() void GenerateRTL::createBindingSignals() { for (Binding::iterator i = this->binding->begin(), ie = this->binding->end(); i != ie; ++i) { Instruction *instr = i->first; std::string fuId = i->second; if (isMultipumped(instr)) { continue; } if (isMem(instr)) continue; if (rtl->exists(fuId)) continue; RTLSignal *op0, *op1; RTLSignal *FU, *fu; op0 = rtl->addWire(fuId + "_op0", RTLWidth(instr->getOperand(0), MBW)); if (instr->isBinaryOp()) { op1 = rtl->addWire(fuId + "_op1", RTLWidth(instr->getOperand(1), MBW)); FU = createFU(instr, op0, op1); } else if (instr->isCast()) { FU = createFU(instr, op0, NULL); } fu = rtl->addWire(fuId, FU->getWidth()); fu->connect(FU); } } // share registers for a group of instructions assigned to the same FU void GenerateRTL::shareRegistersForFU(std::set<Instruction *> &Instructions, std::map<Instruction*, std::set<Instruction*> > &IndependentInstructions) { // the key is the instruction that remains the shared register // the set of instructions are all the instructions that share the register std::map<Instruction *, std::set<Instruction *> > registers; // loop over every instruction assigned to this functional unit for (std::set<Instruction *>::iterator j = Instructions.begin(), je = Instructions.end(); j != je; ++j) { Instruction *instr = *j; // if it is a store, the verilogName(*inst) couldn't get its reg name if (isMem(instr)) { continue; } bool isSharable = false; // loop over all the registers for (std::map<Instruction *, std::set<Instruction *> >::iterator a = registers.begin(), ae = registers.end(); a != ae; ++a) { Instruction *sharedRegInstr = a->first; std::set<Instruction *> &instructionsAssignedToReg = a->second; assert(sharedRegInstr != instr); // are we independent from every single instruction assigned to // this register? bool independent = true; for (std::set<Instruction *>::iterator k = instructionsAssignedToReg.begin(), je = instructionsAssignedToReg.end(); k != je; ++k) { Instruction *instrAssigned = *k; if (IndependentInstructions[instrAssigned].find(instr) == IndependentInstructions[instrAssigned].end()) { independent = false; } } // errs() << "Independent?:"<<utostr(independent)<<"\n"; if (independent) { isSharable = true; //errs() << "Shared output: " << *sharedRegInstr << "\n"; RTLSignal *sharedReg = rtl->find( verilogName(sharedRegInstr) + "_reg"); assert(sharedReg->getType() == "reg"); RTLSignal *oldReg = rtl->find(verilogName(instr) + "_reg"); //determine whether new register has a signed value bool newIsSigned = sharedReg->getWidth().getSigned() || oldReg->getWidth().getSigned(); unsigned newWidth = sharedReg->getWidth().numBits(rtl, alloc); unsigned oldWidth = oldReg->getWidth().numBits(rtl, alloc); if (newIsSigned) { if (!sharedReg->getWidth().getSigned()) newWidth++; else if (!oldReg->getWidth().getSigned()) oldWidth++; } if (newWidth < oldWidth) newWidth = oldWidth; newWidth = min(newWidth, sharedRegInstr->getType()->getPrimitiveSizeInBits()); // errs() << "Setting sharedReg to width:"<<utostr(newWidth)<<"\n"; // sharedReg->setWidth(RTLWidth(newWidth)); sharedReg->setWidth( RTLWidth(newWidth, sharedReg->getWidth().numNativeBits(rtl, alloc), newIsSigned)); // errs() << "Setting sharedReg to signed:"<<utostr(newIsSigned)<<"\n"; // sharedReg->getWidth().setSigned(newIsSigned); // now make sure the shared register is active at the // correct times State *state = sched->getFSM(Fp)->getEndState(instr); connectSignalToDriverInState(sharedReg, rtl->find(verilogName(instr)), state, instr, OUTPUT_READY); // convert the old register into a wire and drive it by the // shared register // errs() << "Converting reg to wire: " << *instr << "\n"; oldReg->setType("wire"); oldReg->connect(sharedReg, instr); registers[sharedRegInstr].insert(instr); break; } } if (!isSharable) { // errs()<<"Creating a new shared register\n"; // create a new shared register registers[instr].insert(instr); } } } // share registers for div/rem and multiply functional units void GenerateRTL::shareRegistersFromBinding() { /* std::map<std::string, std::set<Instruction *> > instructionsAssignedToFU; for(Binding::iterator i = binding->begin(), ie = binding->end(); i != ie; ++i) { Instruction *instr = i->first; std::string fuId = i->second; instructionsAssignedToFU[fuId].insert(instr); }*/ // loop over all functional unit types for (std::map<std::string, std::set<Instruction *> >::iterator i = instructionsAssignedToFU.begin(), ie = instructionsAssignedToFU.end(); i != ie; ++i) { std::string fuId = i->first; std::set<Instruction *> &Instructions = i->second; std::map<Instruction*, std::set<Instruction*> > IndependentInstructions; // use live variable analysis to determine independent instructions Binding::FindIndependentInstructions(Instructions, IndependentInstructions, alloc->getLVA(Fp), fsm); shareRegistersForFU(Instructions, IndependentInstructions); } } // This string contains: function_opcodename_pair#instruction# // For example, if we are in function f, and this is the third // pair, we could label the nodes in the graph as: // f_signed_add_64_p3 // The problem is a graph may have multiple signed_add_64's, so we // add also a label for the instruction # (i): // f_signed_add_64_p3i0, f_signed_add_64_p3i1... std::string GenerateRTL::getPatternFUName(Graph::GraphNodes_iterator &GNi, int PairNumber) { Instruction * I = GNi->first; // GNi->second is the Node with that instruction (a Graph object is made of // nodes, and each node has an instruction as well as other information, // see Graph.h) int label = GNi->second->label; return alloc->verilogNameFunction(Fp, Fp) + "_" + LEGUP_CONFIG->getOpNameFromInst(I, alloc) + "_p" + legup::IntToString(PairNumber) + "i" + legup::IntToString(label); } void GenerateRTL::connectPatternFU(Graph::GraphNodes_iterator &GNi, int PairNumber) { // GNi->first is the instruction corresponding to this node Instruction * I = GNi->first; assert(GNi->second->I == GNi->first); // get the state of the instruction this->state = sched->getFSM(Fp)->getEndState(I); RTLWidth width(I->getType()); // create the wire that is the output of the FU RTLSignal *fu = rtl->addWire(getPatternFUName(GNi, PairNumber), width); // and also the output register RTLSignal *instSig = getLeftHandSide(I); connectSignalToDriverInState(instSig, fu, this->state, I); } void GenerateRTL::create_pattern_fu( // the name of this FU std::string name1, // the node in graph 1 corresponding to this FU Node *node1, Node *node2) { // and the instruction Instruction * I1 = node1->I; // get the state of the instruction (in graph 1) this->state = sched->getFSM(Fp)->getEndState(I1); assert(this->state); RTLWidth width(I1->getType()); // this wire will either connect to an input mux, to an input // register from another FU, or an input wire from another FU // To see which, check if this node has a predecessor in the Graph RTLSignal *op0; // if the left predecessor of this node (p1) is an operation (as // opposed to an input), then the op0 wire connects to the output // of the previous FU (wire or register) if (node1->p1->is_op) { op0 = getOp(this->state, I1->getOperand(0)); } else { // mux // otherwise, the left predecessor of this node is not an // operation in the graph, it is an input. So, add a mux op0 = rtl->addWire(name1 + "_op0", width); connectSignalToDriverInState(op0, getOp(this->state, I1->getOperand(0)), this->state, I1); } // repeat above for right predecessor, again connecting it to an // input wire, reg, or a mux RTLSignal *op1; if (node1->p2->is_op) { op1 = getOp(this->state, I1->getOperand(1)); } else { // mux // otherwise, the left predecessor of this node is not an // operation in the graph, it is an input. So, add a mux op1 = rtl->addWire(name1 + "_op1", width); connectSignalToDriverInState(op1, getOp(this->state, I1->getOperand(1)), this->state, I1); } // Create this FU RTLSignal *FU = createFU(I1, op0, op1); RTLSignal *fu = rtl->find(name1); fu->connect(FU); // Now we need to bind the equivalent node in graph 2 to the // functional unit we just created // This is a little tricky because graphs can be equivalent but // topologically different (due to commutative operations), hence // we will need to use the Graph2_Labels map now (mapping nodes in // g1 to g2 using labels), so that we can check if operands need to // be swapped. Instruction * I2 = node2->I; // the instruction this->state = sched->getFSM(Fp)->getEndState(I2); // its state assert(this->state); // Now, as stated above, if this node represents a commutative // operation, it could be that its operands need to be swapped to // "fit" into the functional unit it needs to be bound to. // To tell if this is the case, compare this node to its equivalent // node in graph1 ("node1") // case 1: Neither operand is an operation (both are mux inputs). // In this case, no need to swap if (!node1->p1->is_op && !node1->p2->is_op) { // op0 from above, still mux input connectSignalToDriverInState(op0, getOp(this->state, I2->getOperand(0)), this->state, I2); // op1 from above, still mux input connectSignalToDriverInState(op1, getOp(this->state, I2->getOperand(1)), this->state, I2); } // case 2: Both operands are instructions, so to be sure if they // are in the right order, we check if the labels match although, // order doesn't matter because this is commutative else if (node1->p1->is_op && node1->p2->is_op) { } // case 3: One operand is an instruction, the other isn't. But we // need to be sure that instruction is on the right side else if (node1->p1->is_op) { // OK, so the left operand is an op, // so the right operand is a mux Value *op = I2->getOperand(1); // right side, so connect normally if (!node2->p1->is_op) { op = I2->getOperand(0); // switch operands } connectSignalToDriverInState(op1, getOp(this->state, op), this->state, I2); } else { // node1->p2 is an op, so left operand is a mux Value *op = I2->getOperand(0); if (!node2->p2->is_op) { op = I2->getOperand(1); } connectSignalToDriverInState(op0, getOp(this->state, op), this->state, I2); } } // Iterate over every pair of graphs, and create functional units / connect // wires and reg to functional units for each pair void GenerateRTL::create_functional_units_for_pairs() { int PairNumber = 0; // for naming pairs uniquely for (std::map<Graph*, Graph*>::iterator p = this->GraphPairs.begin(), pe = this->GraphPairs.end(); p != pe; ++p) { Graph * g1 = p->first; // first graph in this pair (p is a reference // to a pair) Graph * g2 = p->second; // second in the pair // Part 1. Assign a unique name to every node in graph 1. This is the // functional unit name. // Also here, a wire and reg is created for each node in graph 1 std::map<Node*, std::string> FUNames; // This map keeps track of the // name for every node // Now iterate through all the nodes in graph1 and assign names to all // nodes for (Graph::GraphNodes_iterator GNi = g1->GraphNodes.begin(), GNe = g1->GraphNodes.end(); GNi != GNe; ++GNi) { connectPatternFU(GNi, PairNumber); // fill our FUNames map with this node and its name FUNames[GNi->second] = getPatternFUName(GNi, PairNumber); } // For the next part, we will need a map of every node in graph1 to its // corresponding node in graph2. We could make a map<Node*, Node*>, but // from previous analysis (Binding.cpp) we have already labeleld all // nodes in each graph the same way (so equivalent nodes have the same // label, each label is an integer) std::map<unsigned, Node*> Graph2_Labels; for (Graph::GraphNodes_iterator GNi = g2->GraphNodes.begin(), GNe = g2->GraphNodes.end(); GNi != GNe; ++GNi) { int label = GNi->second->label; // now we can map an int (label) to a node in graph2, and since we // have also labelled all nodes in graph1 the same way, we can map // graph1 nodes to graph2 Graph2_Labels[label] = GNi->second; connectPatternFU(GNi, PairNumber); } // Now, every FU in graph 1 has a unique name. Next, create each FU and // connect them properly to make the hardware chain // Once each FU is made from the nodes in graph1, the corresponding // node in graph2 will be bound to that same functional unit // Iterate over all nodes in the graph again, but for which we now have // a unique name for (std::map<Node*, std::string>::iterator FUi = FUNames.begin(), FUe = FUNames.end(); FUi != FUe; ++FUi) { // the name of this FU (from part 1 above) std::string name1 = FUi->second; // the node in graph 1 corresponding to this FU Node * node1 = FUi->first; // equivalent node in graph 2 Node *node2 = Graph2_Labels[node1->label]; create_pattern_fu(name1, node1, node2); } PairNumber++; } } // This function is responsible for two things which are necessary to perform // Binding with graph objects: // // 1. Creating a set of properly connected functional units for each pair // 2. For two graphs which are bound together, mapping the equivalent // instructions in both graphs to the same functional units // // Note that all graphs which need to be paired are already contained in the // map GraphPairs (mapping graph g1 to graph g2 if g1 and g2 need to be paired) void GenerateRTL::updateRTLWithPatterns() { create_functional_units_for_pairs(); // all instructions from the first graph are driven by their equivalent // instructions from the second graph for (std::map<Value*, Value*>::iterator i = this->AllBindingPairs.begin(), e = this->AllBindingPairs.end(); i != e; ++i) { std::string firstName = verilogName(i->first); std::string secondName = verilogName(i->second); if (rtl->exists(secondName + "_reg")) { connectSignalToDriverInState( rtl->find(secondName + "_reg"), rtl->find(firstName), fsm->getEndState((Instruction *)(i->first)), (Instruction *)(i->first)); } RTLSignal *first = rtl->findExists(firstName); RTLSignal *second = rtl->findExists(secondName); if (first && second) { first->connect(second, (Instruction*) (i->first)); if (second->getWidth().numBits(rtl, alloc) < first->getWidth().numBits(rtl, alloc)) { second->setWidth(first->getWidth()); } } first = rtl->findExists(firstName + "_reg"); second = rtl->findExists(secondName + "_reg"); if (first && second) { // this signal shares a register with the second graph first->setType("wire"); first->connect(second, (Instruction*) (i->first)); if (second->getWidth().numBits(rtl, alloc) < first->getWidth().numBits(rtl, alloc)) { second->setWidth(first->getWidth()); } } } } std::vector<PropagatingSignal> GenerateRTL::addPropagatingMemorySignalsToModuleWithPostfix( RTLModule *_rtl, std::string postfix) { std::vector<RTLSignal *> signals; std::vector<PropagatingSignal> propSignals; signals.push_back(_rtl->addOut("memory_controller_enable" + postfix)); signals.push_back( _rtl->addOut("memory_controller_address" + postfix, RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1"))); signals.push_back(_rtl->addOut("memory_controller_write_enable" + postfix)); signals.push_back( _rtl->addOut("memory_controller_in" + postfix, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); if (alloc->usesGenericRAMs()) { signals.push_back( _rtl->addOut("memory_controller_size" + postfix, RTLWidth(2))); } signals.push_back( _rtl->addIn("memory_controller_out" + postfix, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); for (std::vector<RTLSignal *>::iterator it = signals.begin(); it != signals.end(); ++it) { if ((*it)->getType() == "output") { (*it)->setDefaultDriver(ZERO); connectSignalToDriverInState(*it, ZERO, sched->getFSM(Fp)->begin()); } // Create a propagating signal wrapper that points to *it, // stops at the top level module, and is marked as a memory // signal. PropagatingSignal propSignal(*it, true, true); propSignals.push_back(propSignal); } return propSignals; } std::vector<PropagatingSignal> GenerateRTL::addPropagatingMemorySignalsToFunctionWithPostfix( Function *F, std::string postfix) { std::vector<RTLSignal *> signals; std::vector<PropagatingSignal> propSignals; signals.push_back(new RTLSignal("memory_controller_enable" + postfix, "")); signals.push_back( new RTLSignal("memory_controller_address" + postfix, "", RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1"))); signals.push_back( new RTLSignal("memory_controller_write_enable" + postfix, "")); signals.push_back( new RTLSignal("memory_controller_in" + postfix, "", RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); if (alloc->usesGenericRAMs()) { signals.push_back( new RTLSignal("memory_controller_size" + postfix, "", RTLWidth(2))); } for (std::vector<RTLSignal *>::iterator it = signals.begin(); it != signals.end(); ++it) { (*it)->setType("output"); } RTLSignal *controllerOut = new RTLSignal("memory_controller_out" + postfix, "", RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); controllerOut->setType("input"); signals.push_back(controllerOut); for (std::vector<RTLSignal *>::iterator it = signals.begin(); it != signals.end(); ++it) { // Create a propagating signal wrapper that points to *it, // stops at the top level module, and is marked as a memory // signal. PropagatingSignal propSignal(*it, true, true); propSignals.push_back(propSignal); } return propSignals; } void GenerateRTL::addPropagatingMemorySignalsToFunction(Function *F) { std::vector<PropagatingSignal> aSignals, bSignals; aSignals = addPropagatingMemorySignalsToFunctionWithPostfix(F, "_a"); bSignals = addPropagatingMemorySignalsToFunctionWithPostfix(F, "_b"); RTLSignal *waitrequest = new RTLSignal("memory_controller_waitrequest", ""); waitrequest->setType("input"); PropagatingSignal propWaitrequest(waitrequest, true, true); PropagatingSignals *ps = alloc->getPropagatingSignals(); ps->addPropagatingSignalsToFunctionNamed(F->getName().str(), aSignals); ps->addPropagatingSignalsToFunctionNamed(F->getName().str(), bSignals); ps->addPropagatingSignalToFunctionNamed(F->getName().str(), propWaitrequest); } void GenerateRTL::addPropagatingSignalsToCustomVerilog(Function *F) { bool isCV = LEGUP_CONFIG->isCustomVerilog(*F); assert( isCV && "You can only add propagating signals to Custom Verilog functions.\n"); bool requiresMemorySignals = LEGUP_CONFIG->customVerilogUsesMemory(*F); std::vector<CustomVerilogIO> cvIO = LEGUP_CONFIG->getCustomVerilogIOForFunction(F); for (std::vector<CustomVerilogIO>::iterator it = cvIO.begin(); it != cvIO.end(); ++it) { CustomVerilogIO &cvIO = *it; RTLWidth width = RTLWidth(cvIO.bitFrom, cvIO.bitTo); RTLSignal *signal = new RTLSignal(cvIO.name, "", width); if (cvIO.isInput) { signal->setType("input"); } else { signal->setType("output"); } // Create the Propagating Signal wrapper // PropagatingSignal propSignal(signal); PropagatingSignals *ps = alloc->getPropagatingSignals(); ps->addPropagatingSignalToFunctionNamed(F->getName().str(), propSignal); } if (requiresMemorySignals) { addPropagatingMemorySignalsToFunction(F); } } // Adds propagating ports to a module or a wire if // the propagating signal stops propagating at this // function. // void GenerateRTL::addPropagatingPortsToModule(RTLModule *_rtl) { PropagatingSignals *ps = alloc->getPropagatingSignals(); std::string functionName = Fp->getName().str(); bool propagatingMemoryAdded = false; // Adds a signal that will propagate to a custom verilog module // assert(!(LEGUP_CONFIG->isCustomVerilog(functionName)) && "You can't process a custom verilog module!"); std::vector<Function *> functions = getFunctionsCalledByFunction(Fp); std::vector<std::string> functionNames; for (std::vector<Function *>::iterator it = functions.begin(); it != functions.end(); ++it) { Function *function = *it; std::vector<std::string>::iterator b = functionNames.begin(); std::vector<std::string>::iterator e = functionNames.end(); if (std::find(b, e, function->getName().str()) == e) { functionNames.push_back(function->getName().str()); } if (LEGUP_CONFIG->isCustomVerilog(function->getName().str())) { // Custom Verilog Modules don't exist in the RTL, so we add // their propagating signals to the propagating signals // data structure whenever custom verilog modules are // instantiated. // addPropagatingSignalsToCustomVerilog(function); } } std::vector<PropagatingSignal *> signals = ps->getPropagatingSignalsForFunctionsWithNames(functionNames); for (std::vector<PropagatingSignal *>::iterator si = signals.begin(); si != signals.end();) { PropagatingSignal propSignalCopy = **si; // PropagatingSignal *propSignal = *si; si++; RTLSignal *signal; // if local RAMs is turn on, and all RAMS are localized // for this function, then continue // MATHEW TODO: Fix this check for "memory_controller_waitrequest" /* if (LEGUP_CONFIG->getParameterInt("LOCAL_RAMS") && alloc->fctOnlyUsesLocalRAMs(Fp) && propSignalCopy.getName() != "memory_controller_waitrequest") continue; */ if (propSignalCopy.stopsPropagatingAtFunction(Fp)) { // TODO: Account for multiple propagating signals that stop at the // same function and have the same name // What if two have the same name but one of them doesn't stop here? _rtl->addWire(propSignalCopy.getName(), propSignalCopy.getWidth()); continue; } bool isPthreadsMemSignal = propSignalCopy.isMemory() && usesPthreads; string propSignalCopyName; if (isPthreadsMemSignal) { propSignalCopyName = propSignalCopy.getPthreadsMemSignalName(); propSignalCopy.setShouldConnectToPthreadsMemName(true); } else { propSignalCopyName = propSignalCopy.getName(); } if (propSignalCopy.getType() == "input") { signal = _rtl->addIn(propSignalCopyName, propSignalCopy.getWidth()); } else if (propSignalCopy.getType() == "output") { signal = _rtl->addOut(propSignalCopyName, propSignalCopy.getWidth()); } if (!isPthreadsMemSignal && (propSignalCopy.isMerged() || propSignalCopy.isMemory())) signal->setDefaultDriver(ZERO); // RTLSignal *previousSignal = propSignal->getSignal(); propSignalCopy.setSignal(signal); ps->addPropagatingSignalToFunctionNamed(functionName, propSignalCopy); // if one of the propagating signals is memory_controller_enable_a // then an instantiated module uses memory and we don't need to // manually add the memory. // if (!propagatingMemoryAdded && propSignalCopy.isMemory()) propagatingMemoryAdded = true; } bool requiresMemorySignals = false; if (!propagatingMemoryAdded) requiresMemorySignals = functionRequiresMemory(Fp); // Add the memory signals if the function needs memory and if the signals // were not already added. // if (!propagatingMemoryAdded && requiresMemorySignals && !usesPthreads) { // MATHEW TODO: generalize this for waitrequest signal RTLSignal *waitrequest = _rtl->addIn("memory_controller_waitrequest"); waitrequest->setDefaultDriver(ZERO); PropagatingSignal propWaitrequest(waitrequest, true, true); ps->addPropagatingSignalToFunctionNamed(functionName, propWaitrequest); if (!(LEGUP_CONFIG->getParameterInt("LOCAL_RAMS") && alloc->fctOnlyUsesLocalRAMs(Fp))) { std::vector<PropagatingSignal> aSignals, bSignals; aSignals = addPropagatingMemorySignalsToModuleWithPostfix(_rtl, "_a"); bSignals = addPropagatingMemorySignalsToModuleWithPostfix(_rtl, "_b"); ps->addPropagatingSignalsToFunctionNamed(functionName, aSignals); ps->addPropagatingSignalsToFunctionNamed(functionName, bSignals); } } } void GenerateRTL::addDefaultPortsToModule(RTLModule *_rtl) { _rtl->addIn("clk"); _rtl->addIn("clk2x"); _rtl->addIn("clk1x_follower"); _rtl->addIn("reset"); _rtl->addIn("start"); _rtl->addOutReg("finish"); } void GenerateRTL::generateVariableDeclarationsSignalsMemory( RTLModule *t, Function *F, const std::string fctName, const std::string postfix, const std::string instanceName) { RTLSignal *en = rtl->find(fctName + "_memory_controller_enable" + postfix + instanceName); RTLSignal *addr = rtl->addWire(fctName + "_memory_controller_address" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); RTLSignal *we = rtl->find(fctName + "_memory_controller_write_enable" + postfix + instanceName); RTLSignal *in = rtl->addWire(fctName + "_memory_controller_in" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); RTLSignal *out = rtl->addReg(fctName + "_memory_controller_out" + postfix + instanceName, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); const RTLSignal *defaultDriver = out->getDefaultDriver(); if (!defaultDriver) { out->setDefaultDriver(ZERO); } t->addOut("memory_controller_enable" + postfix)->connect(en); t->addOut("memory_controller_address" + postfix)->connect(addr); t->addOut("memory_controller_write_enable" + postfix)->connect(we); t->addOut("memory_controller_in" + postfix)->connect(in); if (alloc->usesGenericRAMs()) { RTLSignal *size = rtl->addWire(fctName + "_memory_controller_size" + postfix + instanceName, RTLWidth(2)); t->addOut("memory_controller_size" + postfix)->connect(size); } t->addOut("memory_controller_out" + postfix)->connect(out); } void GenerateRTL::generatePropagatingSignalDeclarations(RTLModule *t, Function *F) { std::string fctName = F->getName(); // Get a pointer to the PropagatingSignals singleton // PropagatingSignals *ps = alloc->getPropagatingSignals(); std::vector<PropagatingSignal *> signals = ps->getPropagatingSignalsForFunctionNamed(F->getName().str()); // Iterate through propagating signals and add them to the variable declarations // for (std::vector<PropagatingSignal *>::iterator si = signals.begin(); si != signals.end(); ++si) { PropagatingSignal *propSignal = *si; std::string signalType = propSignal->getType(); RTLSignal *signal; RTLSignal * wire; // For connecting the propagating signal to the current module // Add the propagating signal as either an input or an output // std::string propSignalName; if (propSignal->shouldConnectToPthreadsMemName()) { propSignal->setShouldConnectToPthreadsMemName(false); propSignalName = propSignal->getPthreadsMemSignalName(); } else { propSignalName = propSignal->getName(); } if (signalType == "input") { signal = t->addIn(propSignalName, propSignal->getWidth()); std::string existingSignalName; existingSignalName = propSignal->getName(); wire = rtl->find(existingSignalName); // For inputs we can connect // the signal directly } else { // Propagating signals can only be inputs or outputs, so this // is an output signal = t->addOut(propSignalName, propSignal->getWidth()); wire = rtl->find(fctName + "_" + propSignal->getName()); // Outputs must be // connected through the // state machine } signal->connect(wire); } } void GenerateRTL::addTagOffsetParamToModule(Function *F, const int numThreads, const int instanceNum, RTLModule *t) { // add a defparam for the tag // used to steer memory accesses to correct instance of RAM // for arrays (allocas) in parallel functions std::string tag_offset = "tag_offset"; if (numThreads) { std::string totalThreads; if (F->hasFnAttribute("totalNumThreads")) { tag_offset += "*" + F->getFnAttribute("totalNumThreads").getValueAsString().str(); } tag_offset += "+" + utostr(instanceNum); } t->addParam("tag_offset", tag_offset); } void GenerateRTL::generateModuleInstantiation(Function *F, CallInst *CI, const int numThreads, const std::string fctName, const std::string functionType, int loopIndex) { std::string instanceName = getInstanceName(CI, loopIndex); RTLSignal *start = rtl->addReg(fctName + "_start" + instanceName); RTLSignal *finish = rtl->addWire(fctName + "_finish" + instanceName); RTLModule *t = rtl->addModule(fctName, fctName + instanceName); if (!numThreads) { calledModulesToRtlMap[F] = t; generatePropagatingSignalDeclarations(t, F); } t->addIn("clk")->connect(rtl->find("clk")); t->addIn("clk2x")->connect(rtl->find("clk2x")); t->addIn("clk1x_follower")->connect(rtl->find("clk1x_follower")); t->addIn("reset")->connect(rtl->find("reset")); t->addIn("start")->connect(start); t->addOut("finish")->connect(finish); if (!LEGUP_CONFIG->isCustomVerilog(*F)) { addTagOffsetParamToModule(F, numThreads, getInstanceNum(CI, loopIndex), t); } const Type *rT = F->getReturnType(); // if it is a non-void function, or it is a pthread call wrapper with a // return value // insert the return_val output port and connect to the return_val wire // for the instance if (rT->getTypeID() != Type::VoidTyID) { RTLWidth T(rT); RTLSignal *ret = rtl->addWire(fctName + "_return_val" + instanceName, T); t->addOut("return_val", T)->connect(ret); } // MATHEW: this is commented out for sequential functions // can you generalize generatePropagatingSignalDeclarations // for parallel functions? if (numThreads) { generateVariableDeclarationsSignalsMemory(t, F, fctName, "_a", instanceName); generateVariableDeclarationsSignalsMemory(t, F, fctName, "_b", instanceName); RTLSignal *wait = rtl->addReg( fctName + "_memory_controller_waitrequest" + instanceName); wait->setDefaultDriver(ZERO); t->addOut("memory_controller_waitrequest")->connect(wait); } for (Function::arg_iterator i = F->arg_begin(), e = F->arg_end(); i != e; ++i) { //// TODO: fix this std::string argName = alloc->verilogNameFunction(i, F); std::string name = fctName + "_" + argName + instanceName; // if argument name is threadID and there are parallel instances // this means that it's using OpenMP threads // as the threadID pass in induction variable i // this assigns a threadID for each thread // for when they are accessing mutexes, // just using i will make threadID the same when they are from different // avalon accelerators // hence we use threadMutexID (which is equal to base address of that // avalon accelerator) + i if (numThreads && argName == "arg_threadID" && functionType == "omp_function") { // for OpenMP t->addOut(argName, RTLWidth(i->getType())) ->connect(rtl->addConst(utostr(loopIndex), 32)); } else if (numThreads && argName == "arg_threadMutexID") { RTLSignal *arg = rtl->addWire(name, RTLWidth(i->getType())); t->addOut(argName, RTLWidth(i->getType())) ->connect(rtl->addOp(RTLOp::Add)->setOperands( arg, rtl->addConst(utostr(loopIndex), 32))); } else { RTLSignal *arg = rtl->addWire(name, RTLWidth(i->getType())); t->addOut(argName, RTLWidth(i->getType()))->connect(arg); } } } void GenerateRTL::generateVariableDeclarations(CallInst *CI, const std::string functionType) { // get the number of threads int numThreads = getNumThreads(CI); Function *F = getCalledFunction(CI); if (calledModules.find(F) != calledModules.end() && !numThreads) return; calledModules.insert(F); std::string fctName = verilogName(F); if (numThreads) { for (int index = 0; index < numThreads; index++) { generateModuleInstantiation(F, CI, numThreads, fctName, functionType, index); } } else { generateModuleInstantiation(F, CI, numThreads, fctName, functionType); } // create arbiter instance to arbitrate between memory signals // from parallel functions if (numThreads > 1 && functionType != "legup_wrapper_pthreadcall") { generateRoundRobinArbiterDeclaration(fctName, numThreads); } } // generate memory controller signals for the master thread (main FSM) // i.e., waitrequest and readdata logic void GenerateRTL::generatePthreadMasterThreadLogic() { std::string name = Fp->getName().str(); RTLSignal *gnt = rtl->find(name + "_memory_controller_gnt_0"); RTLSignal *wait = rtl->find("memory_controller_waitrequest"); RTLSignal *waitParent = rtl->find("memory_controller_waitrequest_arbiter"); RTLSignal *req = rtl->addOp(RTLOp::Or) ->setOperands(rtl->find("memory_controller_enable_a"), rtl->find("memory_controller_enable_b")); RTLSignal *notGnt = rtl->addOp(RTLOp::Not)->setOperands(gnt); wait->connect( rtl->addOp(RTLOp::Or)->setOperands(waitParent, rtl->addOp(RTLOp::And)->setOperands(req, notGnt))); // create the logic to take in the readdata coming from the memory controller std::string funcName = "memory_controller"; createMemoryReaddataLogicForParallelInstance(gnt, funcName, "_a"); createMemoryReaddataLogicForParallelInstance(gnt, funcName, "_b"); } //create arbiter instance for pthread parallel functions void GenerateRTL::generatePthreadArbiter( const std::set<CallInst*> pthreadFunctions) { // set arbiter usage LEGUP_CONFIG->setArbiterUsage(true); std::string arbiterName = "round_robin_arbiter"; std::string parentFctName = (*(pthreadFunctions.begin()))->getParent()->getParent()->getName(); RTLModule *t = rtl->addModule(arbiterName, arbiterName + "_" + parentFctName + "_inst"); t->addIn("clk")->connect(rtl->find("clk")); t->addIn("rst_an") ->connect(rtl->addOp(RTLOp::Not)->setOperands(rtl->find("reset"))); // only connect the waitrequest signal to the arbiter in the hybrid case // you only need to stall the arbiter when waiting for off-chip memory if (LEGUP_CONFIG->isHybridFlow()) t->addIn("waitrequest") ->connect(rtl->find("memory_controller_waitrequest")); else t->addIn("waitrequest")->connect(ZERO); // connect memory controller enable signals to arbiter request input // connect arbiter grant output to memory controller grant signals connectMemoryControllerSignalsToArbiter(t, pthreadFunctions, parentFctName); // connect all other memory controller signals to // module ouput depending on the grant signal connectMemoryControllerSignalsToModuleOutputWithArbiterGrant( pthreadFunctions, parentFctName, "_a"); connectMemoryControllerSignalsToModuleOutputWithArbiterGrant( pthreadFunctions, parentFctName, "_b"); } void GenerateRTL::connectMemoryControllerSignalsToArbiter( RTLModule *t, const std::set<CallInst *> pthreadFunctions, const std::string parentFctName) { // need to concatenate memory_controller_enable signals from each parallel // function instance // and connect to the request input of arbiter RTLSignal *req, *gnt, *en; std::vector<RTLSignal *> reqVector, gntVector; std::string instanceName, pthreadFuncName; int numThreads, arbiterSize = 0; CallInst *CI; int index; // build a vector of signals for (std::set<CallInst *>::const_iterator it = pthreadFunctions.begin(); it != pthreadFunctions.end(); it++) { CI = *it; numThreads = getNumThreads(CI); for (int i = 0; i < numThreads; i++) { instanceName = getInstanceName(CI, i); index = getInstanceNum(CI, i); pthreadFuncName = CI->getCalledFunction()->getName(); en = rtl->addOp(RTLOp::Or)->setOperands( rtl->find(pthreadFuncName + "_memory_controller_enable_a" + instanceName), rtl->find(pthreadFuncName + "_memory_controller_enable_b" + instanceName)); req = en; // add the memory controller enable signals // from each pthread instance reqVector.push_back(req); gnt = rtl->find(pthreadFuncName + "_memory_controller_gnt_" + utostr(index)); // add the memory controller grant signals // from each pthread instance gntVector.push_back(gnt); } arbiterSize += numThreads; } // add the main thread's memory controller enable signals en = rtl->addOp(RTLOp::Or) ->setOperands(rtl->find("memory_controller_enable_a"), rtl->find("memory_controller_enable_b")); reqVector.push_back(en); // increment arbiterSize since for main thread's // memory controller signals arbiterSize++; // build the operation out of the vector of // memory_controller_enable signals RTLOp *reqOp = rtl->recursivelyAddOp(RTLOp::Concat, reqVector, arbiterSize); assert(reqOp); // connect to the request input t->addIn("req_in", RTLWidth(arbiterSize))->connect(reqOp); // add the gnt signal for main thread gnt = rtl->addWire(parentFctName + "_memory_controller_gnt_0"); gntVector.push_back(gnt); // build the operation out of the vector of // memory_controller_gnt signals RTLOp *gntOp = rtl->recursivelyAddOp(RTLOp::Concat, gntVector, arbiterSize); assert(gntOp); // connect to grant output from arbiter t->addOut("grant_final", RTLWidth(arbiterSize))->connect(gntOp); // set the number of threads (number of inputs) for arbiter t->addParam("N", utostr(arbiterSize)); } void GenerateRTL::connectMemoryControllerSignalsToModuleOutputWithArbiterGrant( const std::set<CallInst *> pthreadFunctions, const std::string parentFctName, const std::string postfix) { // get the memory controller output ports for this module RTLSignal *en = rtl->find("memory_controller_enable_arbiter" + postfix); RTLSignal *we = rtl->find("memory_controller_write_enable_arbiter" + postfix); RTLSignal *addr = rtl->find("memory_controller_address_arbiter" + postfix); RTLSignal *in = rtl->find("memory_controller_in_arbiter" + postfix); RTLSignal *size = rtl->find("memory_controller_size_arbiter" + postfix); // for parallel instances // connect memory controller signals of parallel instance to // parent memory controller signals if gnt signal is asserted for that // instance for (std::set<CallInst *>::const_iterator it = pthreadFunctions.begin(); it != pthreadFunctions.end(); it++) { CallInst *CI = *it; int numThreads = getNumThreads(CI); for (int i = 0; i < numThreads; i++) { std::string instanceName = getInstanceName(CI, i); int index = getInstanceNum(CI, i); std::string pthreadFuncName = CI->getCalledFunction()->getName(); RTLSignal *gnt_inst = rtl->find( pthreadFuncName + "_memory_controller_gnt_" + utostr(index)); RTLSignal *en_inst = rtl->find(pthreadFuncName + "_memory_controller_enable" + postfix + instanceName); RTLSignal *we_inst = rtl->find(pthreadFuncName + "_memory_controller_write_enable" + postfix + instanceName); RTLSignal *addr_inst = rtl->find(pthreadFuncName + "_memory_controller_address" + postfix + instanceName); RTLSignal *in_inst = rtl->find(pthreadFuncName + "_memory_controller_in" + postfix + instanceName); RTLSignal *size_inst = rtl->find(pthreadFuncName + "_memory_controller_size" + postfix + instanceName); en->addCondition(gnt_inst, en_inst); we->addCondition(gnt_inst, we_inst); addr->addCondition(gnt_inst, addr_inst); in->addCondition(gnt_inst, in_inst); size->addCondition(gnt_inst, size_inst); } } // grant signal for main thread RTLSignal *gnt_main = rtl->find(parentFctName + "_memory_controller_gnt_0"); // memory controller signals for main thread RTLSignal *en_main = rtl->find("memory_controller_enable" + postfix); RTLSignal *we_main = rtl->find("memory_controller_write_enable" + postfix); RTLSignal *addr_main = rtl->find("memory_controller_address" + postfix); RTLSignal *in_main = rtl->find("memory_controller_in" + postfix); RTLSignal *size_main = rtl->find("memory_controller_size" + postfix); // connect main thread's memory controller signals // to module output en->addCondition(gnt_main, en_main); we->addCondition(gnt_main, we_main); addr->addCondition(gnt_main, addr_main); in->addCondition(gnt_main, in_main); size->addCondition(gnt_main, size_main); } // create arbiter instance for when parallel functions are used void GenerateRTL::generateRoundRobinArbiterDeclaration(const std::string fctName, const int parallelInstances) { // set arbiter usage LEGUP_CONFIG->setArbiterUsage(true); std::string arbiterName = "round_robin_arbiter"; RTLModule *t = rtl->addModule(arbiterName, arbiterName + "_" + fctName + "_inst"); t->addIn("clk")->connect(rtl->find("clk")); //t->addIn("rst_an")->connect(rtl->find("reset")); t->addIn("rst_an")->connect( rtl->addOp(RTLOp::Not)->setOperands(rtl->find("reset"))); // if (LEGUP_CONFIG->isHybridFlow()) t->addIn("waitrequest")->connect( rtl->find("memory_controller_waitrequest")); // else // t->addIn("waitrequest")->connect(ZERO); //need to concatenate memory_controller_enable signals from each parallel function instance //and connect to the request signal //build a vector of signals RTLSignal *req, *en; std::vector<RTLSignal*> sigVector, bramAccessVector; std::string instanceNum, instanceNum2; for (int i = 0; i < parallelInstances; i++) { instanceNum = "_inst" + utostr(i); /* sdram_sdram_stall = rtl->find("sdram_sdram_stall" + instanceNum); //if other instances accessed BRAM in previous cycle and this instance wants to access SDRAM in current cycle bram_sdram_stall = rtl->find("bram_sdram_stall" + instanceNum); //if other instances accessed BRAM in previous cycle and this instance wants to access BRAM in current cycle bram_bram_stall = rtl->find("bram_bram_stall" + instanceNum); sdram_bram_stall = rtl->find("sdram_bram_stall" + instanceNum); */ en = rtl->addOp(RTLOp::Or)->setOperands( rtl->find( fctName + "_memory_controller_enable_a_inst" + utostr(i)), rtl->find( fctName + "_memory_controller_enable_b_inst" + utostr(i))); //if (LEGUP_CONFIG->numAccelerators() > 0) { if (LEGUP_CONFIG->isHybridFlow()) { req = en; // gnt_stall = rtl->find("gnt_stall" + instancenum); // req = rtl->addop(rtlop::and)->setoperands(en, // rtl->addop(rtlop::not)->setoperands(gnt_stall)); } else { req = en; } sigVector.push_back(req); } //build the operation out of the vector of signals RTLOp *reqOp = rtl->recursivelyAddOp(RTLOp::Concat, sigVector, parallelInstances); //connect to the request input t->addIn("req_in", RTLWidth(parallelInstances))->connect(reqOp); //connecting the grant output sigVector.clear(); for (int i = 0; i < parallelInstances; i++) { // RTLSignal *sig = rtl->addWire("gnt_" + utostr(i)); RTLSignal *sig = rtl->find(fctName + "_memory_controller_gnt_" + utostr(i)); sigVector.push_back(sig); } // build the operation out of the vector of signals RTLOp *gntOp = rtl->recursivelyAddOp(RTLOp::Concat, sigVector, parallelInstances); //connect to grant output from arbiter t->addOut("grant_final", RTLWidth(parallelInstances))->connect(gntOp); t->addParam("N", utostr(parallelInstances)); } RTLSignal *GenerateRTL::getFloatingPointConstantSignal(const ConstantFP *c) { SmallString<40> E; c->getValueAPF().bitcastToAPInt().toStringUnsigned(E, 16); std::string str = utostr(getBitWidth(c->getType())) + "'h"; str = str.append(E.str()); RTLSignal *ret = rtl->addConst(str, RTLWidth(c->getType())); return ret; } RTLSignal *GenerateRTL::getConstantSignal(const ConstantInt *c) { std::string str; // I can't use the abs() method because it doesn't work // when the APInt is the maximum negative value // ie. abs(-2^63) = -2^63 for a 64-bit number APInt val = c->getValue(); std::string numStr = val.toString(10, true); //for some reason, when we have //i1 true, this returns -1 when you getValue() //so we add a case for when it is one and the bitwidth is 1 //then remove the - sign from the front if (c->isOne() && c->getBitWidth() == 1) { // remove '-' sig assert(numStr[0] == '-'); numStr.erase(0, 1); } else if (val.isNegative()) { // remove '-' sig assert(numStr[0] == '-'); numStr.erase(0, 1); str = "-"; } // needed for integers bigger than 32 bits (otherwise // Modelsim gives an error) str += utostr(getBitWidth(c->getType())) + "'d" + numStr; RTLSignal *ret = rtl->addConst(str, RTLWidth(c, MBW)); return ret; } //NC changes... wrapper RTLSignal* GenerateRTL::getOpConstant(State *state, Constant *op) { int value = 0; return getOpConstant(state, op, value); } RTLSignal* GenerateRTL::getOpConstant(State *state, Constant *op, int &value) { //std::cout << "getOpConstant - value: " << value << std::endl; std::string str; if (const ConstantInt *c = dyn_cast<ConstantInt>(op)) { value = c->getSExtValue(); return getConstantSignal(c); } else if (const ConstantFP *c = dyn_cast<ConstantFP>(op)) { //value is not important here.... I only use value for index which has to be integer.... return getFloatingPointConstantSignal(c); } else if (isa<ConstantPointerNull>(op)) { RTLSignal *ret = rtl->addConst("0", RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); value = 0; //std::cout << "getOpConstant - constantPointerNull - value set to: " << value << std::endl; return ret; } else if (ConstantExpr *ce = dyn_cast<ConstantExpr>(op)) { // ie. %st.04.i = getelementptr i64* bitcast (%struct.point* @p1 to i64*), i32 %indvar.i ; // where bitcast (%struct.point* @p1 to i64*) is the operand assert(ce->isCast()); int opValue = 0; RTLSignal* r = getOp(state, ce->getOperand(0), opValue); value = opValue; //std::cout << "getOpConstant - ConstantExpr - value set to: " << value << std::endl; return r; // TODO LLVM 3.4 update: a case we _may_ need to deal with? } else if (ConstantVector *ca = dyn_cast<ConstantVector>(op)) { errs() << "ConstantVector: " << *ca << "\n"; llvm_unreachable("ConstantVector support not implemented"); // TODO LLVM 3.4 update: a new case we need to deal with (exhibited in chstone/adpcm) } else if (ConstantDataVector *ca = dyn_cast<ConstantDataVector>(op)) { errs() << "ConstantDataVector: " << *ca << "\n"; llvm_unreachable("ConstantDataVector support not implemented"); // TODO LLVM 3.4 update: a new case we need to deal with (exhibited in chstone/gsm, mandelbrot) } else if (ConstantAggregateZero *cz = dyn_cast<ConstantAggregateZero>(op)) { errs() << "ZeroInitializer: " << *cz << "\n"; llvm_unreachable("ZeroInitializer support not implemented"); } else if (isa<UndefValue>(op)) { std::cout << "Warning: Used undefined value. Setting to 0.\n"; RTLSignal *ret = rtl->addConst("0", RTLWidth(op->getType())); value = 0; //std::cout << "getOpConstant - UndefValue - value set to: " << value << std::endl; return ret; } else if (isa<Function>(op)) { errs() << "Function pointer to: " << op->getName() << "\n"; llvm_unreachable("Function pointers are unsupported"); } else { errs() << *op << "\n"; llvm_unreachable("Unknown constant operand"); } } RTLSignal* GenerateRTL::getOpNonConstant(State *state, Value *op) { assert(!isa<Constant>(op)); std::string wire = verilogName(op); std::string reg = wire + "_reg"; if (state->isWaitingForPipeline() && isPipelined(op)) { BasicBlock *BB = state->getBasicBlock(); assert(BB); std::string label = getPipelineLabel(BB); const Instruction *inductionVar = getInductionVar(BB); if (op == inductionVar) { wire = label + "_i_stage" + utostr(this->stage); //} else if (PHINode *phi = dyn_cast<PHINode>(op)) { /* } else if (isa<PHINode>(op)) { RTLSignal *phi = rtl->find(reg); return phi; */ } else { RTLSignal *sig = getPipelineSignal(op, this->time); //errs() << "time: " << this->time << " op: " << *op << "\n"; assert(sig); return sig; } reg = wire; } Instruction *I = dyn_cast<Instruction>(op); if (!I) return rtl->find(wire); //errs() << *I << "\n"; //errs() << "type: " << verilogName(I) << " " << // rtl->find(verilogName(I))->getType() << "\n"; // Temporary solution: For compare instructions, we don't need // an output register. This is supposed to be done by // remove_conditional_register but it doesn't remove all reg. // Also true for operands to function args.. not sure how else to // remove these registers if ((isa<ICmpInst>(*I) || multi_cycle_force_wire_operand(I)) && LEGUP_CONFIG->mc_remove_reg_from_icmp_instructions()) { return rtl->find(wire); } RTLSignal *signal = NULL; if (fromOtherState(op, state)) { signal = rtl->find(reg); } else { signal = rtl->find(wire); } return signal; } //NC changes... wrapper RTLSignal *GenerateRTL::getOp(State *state, Value *op) { int value = 0; return getOp(state, op, value); } RTLSignal *GenerateRTL::getOp(State *state, Value *op, int &value) { RTLSignal *ret = NULL; //std::cout << "start-getOp - input value: " << value << std::endl; ConstantExpr *CE = dyn_cast<ConstantExpr>(op); if (CE && CE->getOpcode() == Instruction::GetElementPtr) { int gepValue = 0; ret = getGEP(state, CE, gepValue); value = gepValue; //std::cout << "getOp - GEP - value set to: " << value << std::endl; } else { if (isa<GlobalVariable>(op) || isa<AllocaInst>(op)) { RAM *ram = getRam(op); if (LEGUP_CONFIG->getParameterInt("LOCAL_RAMS") && alloc->isRAMLocaltoFct(Fp, ram)) { // no TAGs - base address is always 0 ret = ZERO; value = 0; } else { // if there are multiple instances of this RAM // due to parallel threads // add an offset to the tag RTLSignal *tag; RTLSignal *originalTag = rtl->addConst("`" + ram->getTagAddrName(), RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); if (ram->getNumInstances() > 1) { tag = rtl->addOp(RTLOp::Add)->setOperands( originalTag, rtl->addConst("tag_addr_offset", RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1"))); } else { tag = originalTag; } ret = tag; } } else if (Constant *c = dyn_cast<Constant>(op)) { int opConstantValue = 0; ret = getOpConstant(state, c, opConstantValue); value = opConstantValue; //std::cout << "getOp - constant - value set to: " << value << std::endl; } else { ret = getOpNonConstant(state, op); } } return ret; } // taken from CBackend // For every branch between basic blocks we call this function. // 'CurBlock' is the last state (terminating state) of the basic block with the // branch, while 'Successor' is the first state of the successor basic block. // 'condition' is the RTL condition for transitioning from states // CurBlock->Successor // For every phi node in the successor basic block, we must assign the phi nodes // phi_temp register in the 'CurBlock' state // For instance, if the successor basic block has the phi: // %23 = phi i32 [ %37, %legup_memset_4.exit ], // [ 0, %legup_memset_4.exit.preheader ] // And the state 'CurBlock' is from basic block %legup_memset_4.exit // Then this function will connect the phi_temp register // verilogName(%23)_phi_temp to %37 during state 'CurBlock', if 'condition' // is true (so we are actually transitioning from from CurBlock->Successor) void GenerateRTL::generatePHICopiesForSuccessor(RTLSignal* condition, State *CurBlock, State *Successor) { assert(CurBlock); assert(Successor); if (!CurBlock->isTerminating()) return; if (CurBlock->isWaitingForPipeline() && Successor->isWaitingForPipeline()) return; const BasicBlock *incomingBB = CurBlock->getBasicBlock(); assert(incomingBB); if (Successor->isWaitingForPipeline()) { // start the pipeline // TODO: this probably should be moved out of this function as it's not // really related to phi instructions, just we have access to the // 'condition' signal here std::string label = getPipelineLabel(Successor->getBasicBlock()); rtl->find(label + "_pipeline_start")->addCondition(condition, ONE); } // check for phi nodes in successor for (State::const_iterator instr = Successor->begin(), ie = Successor->end(); instr != ie; ++instr) { Instruction *I = *instr; if (const PHINode *phi = dyn_cast<PHINode>(I)) { Value *IV = phi->getIncomingValueForBlock(incomingBB); RTLWidth width(I, MBW); RTLSignal *signal = NULL; if (CurBlock->isWaitingForPipeline()) { Instruction *IVinst = dyn_cast<Instruction>(IV); assert(IVinst); this->time = getMetadataInt(IVinst, "legup.pipeline.avail_time"); } signal = getOp(CurBlock, IV); RTLSignal *phiWire = rtl->addWire(verilogName(I), width); RTLSignal *phiReg = rtl->addReg(verilogName(I) + "_reg", width); phiWire->addCondition(condition, signal, I); phiReg->addCondition(condition, phiWire, I); } } } RTLSignal *GenerateRTL::getTransitionOp(State *s) { RTLSignal *op = s->getTransitionSignal(); if (op) { // ie. finish signal for functions return op; } else { return getOp(s, s->getTransitionVariable()); } } // There are three types of transitions: // switch, branch, unconditional void GenerateRTL::generateTransition(RTLSignal *condition, State* s) { assert(s->getDefaultTransition()); RTLSignal *curState = rtl->find("cur_state"); // uncond if (s->getNumTransitions() == 1) { generatePHICopiesForSuccessor(condition, s, s->getDefaultTransition()); curState->addCondition(condition, getStateSignal(s->getDefaultTransition())); // cond branch } else if (s->getNumTransitions() == 2) { RTLOp *trueBranch = rtl->addOp(RTLOp::EQ); trueBranch->setOperand(0, getTransitionOp(s)); trueBranch->setOperand(1, ONE); RTLOp *trueCond = rtl->addOp(RTLOp::And); trueCond->setOperand(0, condition); trueCond->setOperand(1, trueBranch); generatePHICopiesForSuccessor(trueCond, s, s->getTransitionState(0)); curState->addCondition(trueCond, getStateSignal(s->getTransitionState(0))); RTLOp *falseBranch = rtl->addOp(RTLOp::EQ); falseBranch->setOperand(0, getTransitionOp(s)); falseBranch->setOperand(1, ZERO); RTLOp *falseCond = rtl->addOp(RTLOp::And); falseCond->setOperand(0, condition); falseCond->setOperand(1, falseBranch); generatePHICopiesForSuccessor(falseCond, s, s->getDefaultTransition()); curState->addCondition(falseCond, getStateSignal(s->getDefaultTransition())); // switch } else { assert(s->getNumTransitions() > 0); RTLOp *defaultCond = NULL; for (unsigned i = 0, e = s->getNumTransitions() - 1; i != e; ++i) { RTLOp *varEq = rtl->addOp(RTLOp::EQ); varEq->setOperand(0, getTransitionOp(s)); varEq->setOperand(1, getOp(s, s->getTransitionValue(i))); RTLOp *eqCond = rtl->addOp(RTLOp::And); eqCond->setOperand(0, condition); eqCond->setOperand(1, varEq); generatePHICopiesForSuccessor(eqCond, s, s->getTransitionState(i)); curState->addCondition(eqCond, getStateSignal(s->getTransitionState(i))); RTLOp *varNe = rtl->addOp(RTLOp::NE); varNe->setOperand(0, getTransitionOp(s)); varNe->setOperand(1, getOp(s, s->getTransitionValue(i))); if (!defaultCond) { defaultCond = rtl->addOp(RTLOp::And); defaultCond->setOperand(0, condition); defaultCond->setOperand(1, varNe); } else { RTLOp *newCond = rtl->addOp(RTLOp::And); newCond->setOperand(0, defaultCond); newCond->setOperand(1, varNe); defaultCond = newCond; } } // default case generatePHICopiesForSuccessor(defaultCond, s, s->getDefaultTransition()); curState->addCondition(defaultCond, getStateSignal(s->getDefaultTransition())); } } void GenerateRTL::generateDatapath() { std::string indent = std::string(1, '\t'); FiniteStateMachine *fsm = sched->getFSM(Fp); assert(fsm->getNumStates() > 0); RTLSignal *curState = rtl->find("cur_state"); PropagatingSignals *ps = alloc->getPropagatingSignals(); bool shouldConnectMemorySignals = usesPthreads || ps->functionUsesMemory(Fp->getName()); for (FiniteStateMachine::iterator state = fsm->begin(), se = fsm->end(); state != se; ++state) { //const BasicBlock *b = state->getBasicBlock(); //Out << indent << "/* " << b->getParent()->getName() << ": " << // b->getName() << "*/\n"; RTLOp *transition; RTLOp *inState = rtl->addOp(RTLOp::EQ); inState->setOperand(0, curState); inState->setOperand(1, getStateSignal(state)); if (shouldConnectMemorySignals) { RTLOp *waitReqHigh = rtl->addOp(RTLOp::EQ); waitReqHigh->setOperand(0, rtl->find("memory_controller_waitrequest")); waitReqHigh->setOperand(1, ONE); RTLOp *waitReqLow = rtl->addOp(RTLOp::EQ); waitReqLow->setOperand(0, rtl->find("memory_controller_waitrequest")); waitReqLow->setOperand(1, ZERO); RTLOp *waitReq = rtl->addOp(RTLOp::And); waitReq->setOperand(0, inState); waitReq->setOperand(1, waitReqHigh); transition = rtl->addOp(RTLOp::And); transition->setOperand(0, inState); transition->setOperand(1, waitReqLow); curState->addCondition(waitReq, getStateSignal(state)); } else { transition = inState; } // print finishing multi-cycle instructions for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { Instruction *I = *instr; // find the verilog command for this instruction this->state = state; // call appropriate visitXXXX() function visit(*I); // declare usage of instruction to Timing/Area estimator setOperationUsageFunction(I); } // generate loop pipeline basic block instructions if (state->isWaitingForPipeline()) { BasicBlock *BB = state->getBasicBlock(); assert(BB); pipeRTLFile() << "Generating datapath for loop pipeline state: " << state->getName() << "\n"; this->state = state; for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { this->stage = getMetadataInt(I, "legup.pipeline.stage"); this->time = getMetadataInt(I, "legup.pipeline.start_time"); visit(*I); setOperationUsageFunction(I); } generateTransition(transition, state); // these member variables shouldn't be used anymore this->time = -1; this->stage = -1; } generateTransition(transition, state); } RTLOp *reset = rtl->addOp(RTLOp::EQ); reset->setOperand(0, rtl->find("reset")); reset->setOperand(1, ONE); curState->addCondition(reset, rtl->addConst("0", curState->getWidth())); } void GenerateRTL::generateModuleDeclarationSignals(State *wait, std::string postfix) { // print memory controller instantiation RTLSignal *mem_enable, *addr, *we, *in, *size; RTLSignal *mem_enable_wire, *addr_wire, *we_wire, *in_wire, *size_wire; RTLWidth wa("`MEMORY_CONTROLLER_ADDR_SIZE-1"); RTLWidth wd("`MEMORY_CONTROLLER_DATA_SIZE-1"); RTLWidth ws(2); // if this module uses Pthreads, add postfix _arbiter to the ports // but add a wire without _arbiter which will be used in the main FSM (same // as in without pthreads) // postfix _arbiter is needed since the normal memory controller signals // (without _arbiter) // which are assigned in the FSM are used as request signals to the arbiter if (usesPthreads) { mem_enable = rtl->find("memory_controller_enable_arbiter" + postfix); // rtl->addOut("memory_controller_enable_arbiter" + postfix); mem_enable_wire = rtl->addWire("memory_controller_enable" + postfix); mem_enable_wire->setDefaultDriver(ZERO); connectSignalToDriverInState(mem_enable_wire, ZERO, wait); addr = rtl->find("memory_controller_enable_arbiter" + postfix); // rtl->addOut("memory_controller_address_arbiter" + postfix, wa); addr_wire = rtl->addWire("memory_controller_address" + postfix, wa); addr_wire->setDefaultDriver(rtl->addConst("0", wa)); connectSignalToDriverInState(addr_wire, rtl->addConst("0", wa), wait); we = rtl->find("memory_controller_enable_arbiter" + postfix); // rtl->addOut("memory_controller_write_enable_arbiter" + postfix); we_wire = rtl->addWire("memory_controller_write_enable" + postfix); we_wire->setDefaultDriver(ZERO); connectSignalToDriverInState(we_wire, ZERO, wait); in = rtl->find("memory_controller_enable_arbiter" + postfix); // rtl->addOut("memory_controller_in_arbiter" + postfix, wd); in_wire = rtl->addWire("memory_controller_in" + postfix, wd); in_wire->setDefaultDriver(rtl->addConst("0", wd)); connectSignalToDriverInState(in_wire, rtl->addConst("0", wd), wait); if (alloc->usesGenericRAMs()) { size = rtl->find("memory_controller_size_arbiter" + postfix); // rtl->addOut("memory_controller_size_arbiter" + postfix, ws); size_wire = rtl->addWire("memory_controller_size" + postfix, ws); size_wire->setDefaultDriver(rtl->addConst("0", ws)); connectSignalToDriverInState(size_wire, rtl->addConst("0", ws), wait); } // rtl->addIn("memory_controller_out_arbiter" + postfix, wd); rtl->addWire("memory_controller_out" + postfix, wd); // set default drivers and connect them to each state mem_enable->setDefaultDriver(ZERO); connectSignalToDriverInState(mem_enable, ZERO, wait); addr->setDefaultDriver(ZERO); connectSignalToDriverInState(addr, rtl->addConst("0", wa), wait); we->setDefaultDriver(ZERO); connectSignalToDriverInState(we, ZERO, wait); in->setDefaultDriver(ZERO); connectSignalToDriverInState(in, rtl->addConst("0", wd), wait); if (alloc->usesGenericRAMs()) { size->setDefaultDriver(ZERO); connectSignalToDriverInState(size, rtl->addConst("0", ws), wait); } } } void GenerateRTL::generateModuleDeclaration() { ZERO = rtl->addConst("0"); ONE = rtl->addConst("1"); // initialize state signals FiniteStateMachine::iterator stateIter = fsm->begin(); for (; stateIter != fsm->end(); stateIter++) { State *s = stateIter; // we will fix the name/value later - after generating function calls stateSignals[s] = rtl->addParam("state_placeholder", "placeholder"); } // add parameters for tag offset // which is used if there are multiple instances of a RAM // for pthreads/openmp addTagOffsetParameterToModule(); addDefaultPortsToModule(rtl); // width will be set later rtl->addReg("cur_state"); addPropagatingPortsToModule(rtl); FiniteStateMachine *fsm = sched->getFSM(Fp); State *waitState = fsm->begin(); const Type *ret = Fp->getReturnType(); if (ret->getTypeID() != Type::VoidTyID) { rtl->addOutReg("return_val", RTLWidth(ret)); // initialize the return_val to 0 in the wait state RTLSignal *ret = rtl->find("return_val"); connectSignalToDriverInState(ret, rtl->addConst("0", ret->getWidth()), waitState); } // function arguments are inputs for (Function::arg_iterator i = Fp->arg_begin(), e = Fp->arg_end(); i != e; ++i) { rtl->addIn(verilogName(i), RTLWidth(i->getType())); } // TODO:MATHEW // should default memory signals to 0 generateModuleDeclarationSignals(waitState, "_a"); generateModuleDeclarationSignals(waitState, "_b"); // if Pthreads are used if (usesPthreads) { // the waitrequest signal is OR'ed with logic from arbiter // memory_controller_waitrequest = memory_controller_waitrequest_arbiter // || request is made but not granted by arbiter // rtl->addIn("memory_controller_waitrequest_arbiter"); rtl->addWire("memory_controller_waitrequest"); } // wait state waits until start signal is asserted waitState->setTransitionSignal(rtl->find("start")); connectSignalToDriverInState(rtl->find("finish"), ZERO, waitState); } bool ignoreInstruction(const Instruction *I) { // ignore stores (don't need a wire/reg) if (I->getType()->getTypeID() == Type::VoidTyID) return true; // ignore allocations if (isa<AllocaInst>(I)) return true; // ignore printf calls if (isaDummyCall(I)) return true; return false; } // For every instruction create: // 1) wire named verilogName(I) // 2) register named verilogName(I) + "_reg" void GenerateRTL::createRTLSignals() { // create signals for each instruction createRTLSignalsForInstructions(); // create signals for local RAMs if (LEGUP_CONFIG->getParameterInt("LOCAL_RAMS")) { createRTLSignalsForLocalRams(); } } void GenerateRTL::createRTLSignalsForInstructions() { for (inst_iterator i = inst_begin(Fp), e = inst_end(Fp); i != e; ++i) { const Instruction *I = &*i; if (ignoreInstruction(I)) continue; if (I->hasNUses(0)) continue; // ignore instructions with no uses std::string wire = verilogName(*I); std::string reg = wire + "_reg"; RTLWidth w(I, MBW); if (!rtl->exists(wire)) rtl->addWire(wire, w); if (!rtl->exists(reg)) rtl->addReg(reg, w); } } void GenerateRTL::createRTLSignalsForLocalRams() { for (Allocation::const_ram_iterator i = alloc->ram_begin(), e = alloc->ram_end(); i != e; ++i) { const char* portNames[2] = { "a", "b" }; std::vector<std::string> ports(portNames, portNames + 2); for (std::vector<std::string>::iterator p = ports.begin(), pe = ports.end(); p != pe; ++p) { std::string port = *p; const RAM *R = *i; std::string name = R->getName(); RTLSignal *s; s = rtl->addWire(name + "_address_" + port, RTLWidth(R->getAddrWidth())); s->setDefaultDriver(ZERO); s = rtl->addWire(name + "_write_enable_" + port); s->setDefaultDriver(ZERO); s = rtl->addWire(name + "_in_" + port, RTLWidth(R->getDataWidth())); s->setDefaultDriver(ZERO); rtl->addWire(name + "_out_" + port, RTLWidth(R->getDataWidth())); } } } // this function is used to create memory_controller_storage_port signal // inside a parallel function, which is used to store the data from memory // in the correct cycle (two state after memory read) // For parallel functions, loads are taken from // memory_controller_storage_port signal instead of the regular // memory_controller_out_port signal void GenerateRTL::createMemoryReaddataStorageForParallelFunction() { // create shift register to indicate when the data is valid // the data is valid in the first cycle // of the finish state of the load // i.e two states after load when memory access latency = 2 RTLSignal *firstStateAfterMemoryRead = rtl->addReg("first_state_after_memory_read"); RTLSignal *secondStateAfterMemoryRead = rtl->addReg("second_state_after_memory_read"); RTLSignal *wait = rtl->find("memory_controller_waitrequest"); // invert the waitrequest and register it // this gives the signal that is asserted high // in the very first cycle of a state RTLOp *notWait = rtl->addOp(RTLOp::Not)->setOperands(wait); RTLSignal *notWait_reg = rtl->addReg("memory_controller_waitrequest_inverted_reg"); notWait_reg->connect(notWait); // port A read (but not write) RTLSignal *memRead_portA = rtl->addOp(RTLOp::And)->setOperands( rtl->find("memory_controller_enable_a"), rtl->addOp(RTLOp::Not)->setOperands( rtl->find("memory_controller_write_enable_a"))); // port B read (but not write) RTLSignal *memRead_portB = rtl->addOp(RTLOp::And)->setOperands( rtl->find("memory_controller_enable_b"), rtl->addOp(RTLOp::Not)->setOperands( rtl->find("memory_controller_write_enable_b"))); // when there is a read (port A read or port B read) RTLSignal *memRead = rtl->addOp(RTLOp::Or)->setOperands( memRead_portA, memRead_portB); // make 2 bit-shift register // this signal is asserted high // in the first state after memory access RTLSignal *reset = rtl->find("reset"); firstStateAfterMemoryRead->addCondition(reset, ZERO); firstStateAfterMemoryRead->addCondition(notWait, memRead); // this signal is asserted high // in the second state after memory access secondStateAfterMemoryRead->addCondition(reset, ZERO); secondStateAfterMemoryRead->addCondition(notWait, firstStateAfterMemoryRead); // create a memory readdata valid signal // which is asserted in the first cycle of // two states after a memory read RTLSignal *memReaddataValid = rtl->addWire("memory_readdata_valid"); memReaddataValid = rtl->addOp(RTLOp::And)->setOperands( secondStateAfterMemoryRead, notWait_reg); createMemoryReaddataStorageForPort(memReaddataValid, secondStateAfterMemoryRead, "_a"); createMemoryReaddataStorageForPort(memReaddataValid, secondStateAfterMemoryRead, "_b"); } void GenerateRTL::createMemoryReaddataStorageForPort(RTLSignal *memReaddataValid, RTLSignal *secondStateAfterMemoryRead, std::string postfix) { RTLSignal *reset = rtl->find("reset"); // create registers to store memory readdata // on memory readdata valid RTLSignal *memReaddata_stored = rtl-> addWire("memory_controller_out_stored_on_datavalid" + postfix, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); RTLSignal *memReaddata_stored_reg = rtl-> addReg("memory_controller_out_stored_on_datavalid_reg" + postfix, RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1")); RTLSignal *memReaddata = rtl->find("memory_controller_out" + postfix); // the logic is // memReaddata_stored = 0; (needs to be set to 0 esp. for loop pipelining) // if (memReaddataValid) // memReaddata_stored = memReaddata; (actual valid data) // if (secondStateAfterMemoryRead) // memReaddata_stored = memReaddata_stored_reg; (needs to retain data if waitrequest is asserted) memReaddata_stored->setDefaultDriver(rtl->addConst("0", RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); memReaddata_stored->addCondition(secondStateAfterMemoryRead, memReaddata_stored_reg); memReaddata_stored->addCondition(memReaddataValid, memReaddata); // registered value created to retain valid data memReaddata_stored_reg->addCondition(reset, rtl->addConst("0", RTLWidth("`MEMORY_CONTROLLER_DATA_SIZE-1"))); memReaddata_stored_reg->addCondition(memReaddataValid, memReaddata); } // connect all registers to wires // the FSM must be finalized before doing this void GenerateRTL::connectRegistersToWires() { for (inst_iterator i = inst_begin(Fp), e = inst_end(Fp); i != e; ++i) { Instruction *I = &*i; if (ignoreInstruction(I) || isa<PHINode>(I)) continue; if (I->hasNUses(0)) continue; // ignore instructions with no uses std::string wire = verilogName(*I); std::string reg = wire + "_reg"; // errs() << "Adding " << reg << " to state: " << // sched->getFSM(Fp)->getEndState(I)->getName() << "\n"; connectSignalToDriverInState(rtl->find(reg), rtl->find(wire), sched->getFSM(Fp)->getEndState(I), I, OUTPUT_READY); } } /* //this returns true if function F is a Pthread calling wrapper function //returns false otherwise //pthreadF is stored a pointer to the pthread function bool GenerateRTL::isaPthreadCallWrapper(Function *F, Function **pthreadF) { for (Function::const_iterator BB = F->begin(), EE = F->end(); BB != EE; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), EE = BB->end(); I != EE; ++I) { if (const CallInst *CI = dyn_cast<CallInst>(I)) { if (getMetadataStr(CI, "TYPE") == "pthread_function") { *pthreadF = CI->getCalledFunction(); return true; } } } } return false; } */ // this returns true if function F is a Pthread calling wrapper function // which should have a return value (pthread function has a returnval) // returns false otherwise // // each pthread calling wrapper with a returnVal has a call to __legup_preserve_value // which has a metadata set as legup_wrapper_pthreadcall bool GenerateRTL::isaPthreadCallWrapperWithReturnVal(Function *F) { std::string funcName; for (Function::const_iterator BB = F->begin(), EE = F->end(); BB != EE; ++BB) { for (BasicBlock::const_iterator I = BB->begin(), EE = BB->end(); I != EE; ++I) { if (const CallInst *CI = dyn_cast<CallInst>(I)) { Function *calledFunction = CI->getCalledFunction(); // ignore indirect function calls if (!calledFunction) continue; funcName = calledFunction->getName(); if (funcName == "__legup_preserve_value" && getMetadataStr(CI, "TYPE") == "dummyCallforPthreadReturnVal") { return true; } } /* if (const ReturnInst *retInst = dyn_cast<ReturnInst>(I)) { if (getMetadataStr(retInst, "TYPE") == "legup_wrapper_pthreadcall") { return true; } }*/ } } return false; } //this returns true if function F has a return value //returns false otherwise bool GenerateRTL::hasReturnVal(Function *F) { if (!(F->getReturnType()->isVoidTy())) { return true; } else { return false; } } // the FSM used by binding needs to be modified to handle pipelining // in the default FSM, all the instructions in a pipeline are added // to one state, the pipeline_wait state. Instead, we would like to // create a new FSM that includes a states for 0 to II-1 of the pipeline void GenerateRTL::createBindingFSM() { assert(fsm); if (!LEGUP_CONFIG->getParameterInt("PIPELINE_RESOURCE_SHARING")) { this->bindingFSM = this->fsm; return; } // first clone FSM this->bindingFSM = new FiniteStateMachine(); this->fsm->cloneFSM(this->bindingFSM); for (FiniteStateMachine::iterator state = this->bindingFSM->begin(); state != this->bindingFSM->end(); state++) { if (!state->isWaitingForPipeline()) continue; modifyPipelineState(state); } std::string fileName = "fsm.pipeline." + getLabel(Fp) + ".dot"; printFSMDotFile(this->bindingFSM, fileName); } void GenerateRTL::modifyPipelineState(State *state) { assert(state->isWaitingForPipeline()); // Note: the pipeline wait state has no instructions in it, except for // phi nodes. // get rid of loop back State *nextStateAfterBB = getStateAfterLoop(state); BasicBlock *BB = state->getBasicBlock(); assert(BB); state->setName("pipeline_time_0"); int II = getPipelineII(BB); assert(II >= 1); std::map<int, State*> newStates; newStates[0] = state; State *prevState = state; for (int time = 1; time < II; time++) { std::string name = "pipeline_time_" + utostr(time); State *newState = this->bindingFSM->newState(prevState, name); newState->setName(name); newState->setBasicBlock(BB); if (prevState) { prevState->setDefaultTransition(newState); } newStates[time] = newState; prevState = newState; } assert((int )newStates.size() == II); int lastTime = II - 1; if (lastTime != 0) { newStates[lastTime]->setTerminating(true); newStates[lastTime]->setDefaultTransition(nextStateAfterBB); // clear original wait state state->setTerminating(false); State::Transition blank; state->setTransition(blank); state->setDefaultTransition(newStates[1]); assert(state->getNumTransitions() == 1); } for (BasicBlock::iterator I = BB->begin(), ie = BB->end(); I != ie; ++I) { int startTime = getMetadataInt(I, "legup.pipeline.start_time"); int timeAvail = getMetadataInt(I, "legup.pipeline.avail_time"); startTime = startTime % II; timeAvail = startTime % II; // how do i handle arrival times / LVA for pipelining? newStates[startTime]->push_back(I); this->bindingFSM->setEndState(I, newStates[timeAvail]); } } void delete_multicycle_files() { static bool first_visit = true; if (!first_visit) { return; } std::vector<std::string> file_list; file_list.push_back("llvm_prof_multicycle_constraints.sdc"); file_list.push_back("llvm_prof_multicycle_constraints.qsf"); file_list.push_back("src_dst_pairs_with_through_constraints.txt"); file_list.push_back("pairs_whose_through_constraints_must_be_removed.txt"); for (std::vector<std::string>::const_iterator it = file_list.begin(); it != file_list.end(); ++it) { std::ofstream file; file.open(it->c_str()); file << std::endl; } first_visit = false; } RTLModule* GenerateRTL::generateRTL(MinimizeBitwidth *_MBW) { EXPLICIT_LPM_MULTS = LEGUP_CONFIG->getParameterInt("EXPLICIT_LPM_MULTS"); MULTIPUMPING = LEGUP_CONFIG->getParameterInt("MULTIPUMPING"); USE_MB = LEGUP_CONFIG->getParameterInt("MB_MINIMIZE_HW"); MBW = _MBW; assert(!rtl); rtl = new RTLModule(Fp->getName()); // check if this function uses Pthreads usesPthreads = checkforPthreads(Fp); // add to phreadfunctions if (usesPthreads) LEGUP_CONFIG->addPthreadFunction(Fp->getName()); generateModuleDeclaration(); createRTLSignals(); // function calls are a special case because they can modify the // finite state machine. Do these first: generateAllCallInsts(); // loop pipelines (which also modifies fsm) generateAllLoopPipelines(); updateStatesAfterCallInsts(); printFSMDot(); connectRegistersToWires(); binding = new BipartiteWeightedMatchingBinding(alloc, bindingFSM, Fp, this->MBW); // Patterns is used for binding graphs PatternMap * Patterns = new PatternMap(fsm); // InstructionsInGraphs is a set of all instructions in graphs, used in // visitInstruction this->InstructionsInGraphs.clear(); this->GraphPairs.clear(); this->binding->operatorAssignment(); for (Binding::iterator i = this->binding->begin(), ie = this->binding->end(); i != ie; ++i) { Instruction *instr = i->first; std::string fuId = i->second; instructionsAssignedToFU[fuId].insert(instr); } PatternBinding *patterns = new PatternBinding(alloc, fsm, Fp, this->MBW); patterns->PatternAnalysis(*Patterns, this->AllBindingPairs, this->GraphPairs, this->InstructionsInGraphs); createBindingSignals(); if (MULTIPUMPING) { createMultipumpSignals(); } // for parallel functions // create a register to store the data from memory // in the correct cycle bool isParallelFunction = Fp->hasFnAttribute("totalNumThreads"); if (isParallelFunction) { createMemoryReaddataStorageForParallelFunction(); } generateDatapath(); updateRTLWithPatterns(); shareRegistersFromBinding(); delete Patterns; Patterns = NULL; printSchedulingInfo(); // Delete/clear multi-cycle files from previous builds delete_multicycle_files(); printSDCMultiCycleConstraints(); printScheduleGanttChart(); // must be run after the above because the FSM can be modified by // modifyFSMForLoopPipeline() timingAnalysis(dag); std::string functionType; std::set<CallInst *> pthreadFunctions; // Module instances for (Function::iterator b = Fp->begin(), be = Fp->end(); b != be; ++b) { for (BasicBlock::iterator instr = b->begin(), ie = b->end(); instr != ie; ++instr) { if (isaDummyCall(instr)) continue; if (CallInst *CI = dyn_cast<CallInst>(instr)) { functionType = getMetadataStr(CI, "TYPE"); // don't generate instances for pthread poll wrapper if (functionType != "legup_wrapper_pthreadpoll") { // push pthread functions into vector // to be used for creating arbiter if (getMetadataStr(CI, "TYPE") == "legup_wrapper_pthreadcall") pthreadFunctions.insert(CI); // instantiate module generateVariableDeclarations(CI, functionType); } } } } // create arbiter for pthreads if (!pthreadFunctions.empty()) { generatePthreadArbiter(pthreadFunctions); generatePthreadMasterThreadLogic(); } // debugging: display cur_state each cycle if (LEGUP_CONFIG->getParameterInt("PRINT_STATES")) { std::string old_body = rtl->getBody(); raw_string_ostream body(old_body); body << "always @(posedge clk)" << "\n"; body << "\t$display(\"Cycle: %d Time: %d " << Fp->getName() << " cur_state: %d\", ($time-50)/20, $time, cur_state);\n"; rtl->setBody(body.str()); } // add local rams for (std::map<RAM*, Function*>::iterator i = alloc->isLocalFunctionRam.begin(), e = alloc->isLocalFunctionRam.end(); i != e; ++i) { RAM *r = i->first; Function *f = i->second; if (Fp == f) { // RAM is local to this function assert(rtl->localRamList.find(r) == rtl->localRamList.end()); rtl->localRamList.insert(r); } } return rtl; } // Get the number of succcessors that are in the same state int GenerateRTL::getNumSuccInState(Instruction *I, FiniteStateMachine *fsm) { State *currS = fsm->getStartState(I); int numSuccInState = 0; for (Value::user_iterator i = I->user_begin(), e = I->user_end(); i != e; ++i) { Instruction *successor = dyn_cast<Instruction>(*i); if (!successor) continue; State *succS = fsm->getStartState(successor); if (succS == currS) numSuccInState++; } return numSuccInState; } // Check if an instruction is the start of a path bool GenerateRTL::isStartOfPath(SchedulerDAG *dag, Instruction *I, FiniteStateMachine *fsm) { State *beginS = fsm->getStartState(I); InstructionNode *IN = dag->getInstructionNode(I); int numPreInState = 0; int numAllPre = 0; for (InstructionNode::iterator i = IN->dep_begin(), e = IN->dep_end(); i != e; ++i) { // dependency from dep -> IN Instruction *dep = (*i)->getInst(); State *endS = fsm->getStartState(dep); numAllPre++; if (endS == beginS) numPreInState++; } int numPreOutOfState = numAllPre - numPreInState; // An instruction is the start of a path in two cases // either it doesn't has any predecessor in the same state or it has some predecessor out of the state if (numPreInState == 0 || numPreOutOfState != 0) return true; else return false; } // calculate the delay of all paths starting from the beginning of a state and ending with Instruction *Root // Store the paths in func_path // gets called for every root instruction void GenerateRTL::calculateDelay(SchedulerDAG *dag, Instruction *Curr, float partialDelay, State *rootState, FiniteStateMachine *fsm, std::list<GenerateRTL::PATH*> *func_path, std::vector<Instruction *> instrs, std::vector<float> instrDelays) { int ifNotIgnoreGetelementptrAndStore = LEGUP_CONFIG->getParameterInt( "TIMING_NO_IGNORE_GETELEMENTPTR_AND_STORE"); InstructionNode *CurrNode = dag->getInstructionNode(Curr); float dl; // Ignore getelementptr and store instructions if (ifNotIgnoreGetelementptrAndStore == 0) if (isa<GetElementPtrInst>(Curr) || isa<StoreInst>(*Curr)) return; dl = partialDelay + CurrNode->getDelay(); // Add the instruction into the Path instrs.push_back(Curr); instrDelays.push_back(CurrNode->getDelay()); // Walk through the dependencies for (InstructionNode::iterator i = CurrNode->dep_begin(), e = CurrNode->dep_end(); i != e; ++i) { // dependency from dep -> CurrNode Instruction *dep = (*i)->getInst(); State *currState = fsm->getStartState(dep); // recursive call to discover other instructions if dep is in the same state if (currState == rootState) calculateDelay(dag, dep, dl, rootState, fsm, func_path, instrs, instrDelays); } bool ifAddToPath = isStartOfPath(dag, Curr, fsm); // Add the path into the list if current node is the start of the path if (ifAddToPath) { PATH *temp; temp = new PATH; temp->pathDelay = dl; temp->state = rootState; temp->instructions = instrs; temp->instrDelay = instrDelays; temp->func = Fp; func_path->push_back(temp); } } // Print out the n longest paths void GenerateRTL::printPath(raw_ostream &report, list<PATH*> *path) { int num_paths = LEGUP_CONFIG->getParameterInt("TIMING_NUM_PATHS"); int pathNum = 0; for (std::list<GenerateRTL::PATH*>::iterator i = path->begin(), e = path->end(); i != e; ++i) { pathNum++; if (pathNum > num_paths) break; PATH *curr = *i; report << "-----------------Function: " << curr->func->getName() << "---------------\n"; report << "-------------------------" << pathNum << "---------------------------\n"; report << "-----------------Delay of path:" << ftostr(curr->pathDelay) << " ns---------------\n"; report << "-----------------State:" << curr->state->getName() << "-----------------\n"; float partialDelay = 0; int instrNum = curr->instrDelay.size(); for (std::vector<Instruction *>::reverse_iterator i = curr->instructions.rbegin(), e = curr->instructions.rend(); i != e; ++i) { instrNum--; Instruction *currInstr = *i; float currDelay = curr->instrDelay[instrNum]; partialDelay += currDelay; report << "(" << ftostr(currDelay) << " ns) --- (" << ftostr(partialDelay) << " ns) --- " << *currInstr << "\n"; } report << "\n"; } report << "\n"; } void GenerateRTL::addToOverallPathList() { int num_paths = LEGUP_CONFIG->getParameterInt("TIMING_NUM_PATHS"); list<GenerateRTL::PATH*> *pathList = alloc->getOverallLongestPaths(); int pathNum = 0; for (std::list<GenerateRTL::PATH*>::iterator i = func_path.begin(), e = func_path.end(); i != e; ++i) { pathNum++; // In worst case, the overall n longest paths are all from the same function if (pathNum > num_paths) break; pathList->push_front(*i); } pathList->sort(pathComp); } // Calculates the n longest paths and stores in func_path // Gets called once for each function void GenerateRTL::timingAnalysis(SchedulerDAG *dag) { vector<Instruction *> instrs; vector<float> instrDelay; for (FiniteStateMachine::iterator state = fsm->begin(), se = fsm->end(); state != se; ++state) { for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { Instruction *I = *instr; State *rootState = fsm->getStartState(I); int numSuccInState = getNumSuccInState(I, fsm); if (!numSuccInState) calculateDelay(dag, I, 0, rootState, fsm, &func_path, instrs, instrDelay); } } formatted_raw_ostream report(alloc->getTimingReportFile()); func_path.sort(pathComp); printPath(report, &func_path); addToOverallPathList(); } // print out the data flow graph for each basic block void GenerateRTL::printSchedulingDFGDot(SchedulerDAG &dag) { for (Function::iterator bb = Fp->begin(), be = Fp->end(); bb != be; ++bb) { std::string FileError; std::string fileName = "dfg." + getLabel(Fp) + "_" + getLabel(bb) + ".dot"; raw_fd_ostream dfgFile(fileName.c_str(), FileError, llvm::sys::fs::F_None); assert(FileError.empty() && "Error opening dot files"); formatted_raw_ostream out(dfgFile); dag.printDFGDot(out, bb); } } void GenerateRTL::printSchedulingInfo() { formatted_raw_ostream out(alloc->getSchedulingFile()); out << "Target Family: " << LEGUP_CONFIG->getDeviceFamily() << "\n"; out << "Clock period constraint: " << sched->getClockPeriodConstraint() << "ns\n"; std::map<BasicBlock*, unsigned> bbCount; out << "Start Function: " << Fp->getName() << "\n"; //std::ofstream out("scheduling.legup.rpt", std::ios::app); for (FiniteStateMachine::iterator state = fsm->begin(), se = fsm->end(); state != se; ++state) { out << "state: " << state->getName() << "\n"; BasicBlock *bb = state->getBasicBlock(); bbCount[bb]++; for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { Instruction *I = *instr; if (bb && I == bb->getTerminator()) continue; assert(fsm->getStartState(I) == state); out << " " << getValueStr(I) << " (endState: " << fsm->getEndState(I)->getName() << ")\n"; } // print out branch: if (bb && state->isTerminating()) { out << " " << getValueStr(bb->getTerminator()) << "\n"; } out << " "; state->printTransition(out); out << "\n"; } out << "\n"; for (std::map<BasicBlock*, unsigned>::iterator i = bbCount.begin(), e = bbCount.end(); i != e; ++i) { BasicBlock *bb = i->first; if (!bb) continue; unsigned count = i->second; out << "Basic Block: " << getLabel(bb) << " Num States: " << count << "\n"; } out << "End Function: " << Fp->getName() << "\n"; out << "--------------------------------------------------------------------------------\n\n"; } void GenerateRTL::printScheduleGanttChart() { std::string Filename = "gantt." + Fp->getName().str() + ".tex"; //errs() << "Writing '" << Filename << "'..."; std::string ErrorInfo; raw_fd_ostream file(Filename.c_str(), ErrorInfo, llvm::sys::fs::F_None); if (!ErrorInfo.empty()) { errs() << "Error opening file: " << Filename << " for writing!\n"; assert(0); } file << "\\documentclass[landscape]{article}\n"; //file << "\\usepackage{fullpage}\n"; file << "\\usepackage{gantt}\n"; file << "\\pagestyle{empty}\n"; file << "\\begin{document}\n"; //file << "\\setlength{\\pdfpagewidth}{100in}\n"; //file << "\\setlength{\\pdfpageheight}{200in}\n"; //file << "Function: " << verilogName(Fp) << "\n"; std::vector<GanttBar> gantt; std::map<Instruction *, GanttBar> instructions; FiniteStateMachine *fsm = sched->getFSM(Fp); int instNum = 1; int stateNum = 1; for (FiniteStateMachine::iterator state = ++fsm->begin(), se = fsm->end(); state != se; ++state) { for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { GanttBar bar; bar.inst = *instr; bar.x = stateNum; bar.y = instNum; bar.duration = Scheduler::getNumInstructionCycles(bar.inst); if (bar.duration == 0) { bar.duration = 1; } gantt.push_back(bar); instructions[*instr] = bar; //errs() << *bar.inst << "\n"; instNum++; } stateNum++; if (state->isTerminating() && !gantt.empty()) { printGantt(file, gantt, instructions, stateNum); instNum = 1; stateNum = 1; gantt.clear(); instructions.clear(); } } file << "\\end{document}\n"; } void GenerateRTL::printGantt(raw_fd_ostream &file, std::vector<GanttBar> &gantt, std::map<Instruction *, GanttBar> &instructions, int stateNum) { unsigned rows = gantt.size() + 1; unsigned cols = stateNum; unsigned start = 0; unsigned increment = 1; unsigned span = 1; unsigned end = cols - 1; file << "\\begin{figure}\n"; file << "\\begin{gantt}[fontsize=\\scriptsize]{" << rows << "}{" << cols << "}\n"; file << "\\begin{ganttitle}\n"; file << "\\numtitle{" << start << "}{" << increment << "}{" << end << "}{" << span << "}\n"; file << "\\end{ganttitle}\n"; //errs() << "gantt: " << gantt.size() << "\n"; for (std::vector<GanttBar>::iterator bar = gantt.begin(), bare = gantt.end(); bar != bare; ++bar) { std::string stripped; raw_string_ostream stream(stripped); Instruction *I = bar->inst; stream << *I; replaceAll(stripped, "%", "\\%"); replaceAll(stripped, "_", "\\_"); // limit the size of the instruction string unsigned limit = 80; if (stripped.length() > limit) { stripped.erase(limit); stripped = stripped + "..."; } file << "\\ganttbar{" << stripped << "}{" << bar->x << "}{" << bar->duration << "}\n"; for (Value::user_iterator i = I->user_begin(), e = I->user_end(); i != e; ++i) { Instruction *use = dyn_cast<Instruction>(*i); if (!use) continue; //assert(instructions.find(use) != instructions.end()); if (instructions.find(use) == instructions.end()) continue; GanttBar useGantt = instructions[use]; file << "\\ganttcon{" << bar->x + bar->duration << "}{" << bar->y << "}{" << useGantt.x << "}{" << useGantt.y << "}\n"; } } /* \ganttbar{\%i.04 = phi i32 [ 0, \%bb.nph ], [ \%3, \%bb ]}{1}{0} \ganttbarcon{\%scevgep5 = getelementptr \%b, \%i.04}{1}{1} \ganttbarcon{\%0 = load \%scevgep5}{2}{2} \ganttbar{\%scevgep6 = getelementptr \%c, \%i.04}{1}{1} \ganttbarcon{\%1 = load \%scevgep6}{3}{2} \ganttbarcon{\%2 = add nsw i32 \%1, \%0}{5}{1} \ganttbar{\%scevgep = getelementptr \%a, \%i.04}{1}{1} \ganttbarcon{store \%2, \%scevgep}{6}{1} \ganttcon{1}{1}{1}{7} \ganttcon{1}{1}{1}{4} \ganttcon{4}{3}{5}{6} % x, y x, y \ganttcon{6}{6}{6}{8} \ganttbar{\%3 = add \%i.04, 1}{1}{1} \ganttcon{1}{1}{1}{9} \ganttbarcon{\%exitcond = eq \%3, 100}{2}{1} \ganttbarcon{br \%exitcond, \%bb2, \%bb}{7}{0} */ file << "\\end{gantt}\n"; assert(!gantt.empty()); //file << "\\caption{" << "Function: " << verilogName(Fp) << " " //<< *gantt[0].inst->getParent() << "}\n"; file << "\\end{figure}\n"; } void GenerateRTL::scheduleOperations() { dag = new SchedulerDAG; dag->runOnFunction(*Fp, alloc); if (!LEGUP_CONFIG->getParameterInt("NO_DFG_DOT_FILES")) { printSchedulingDFGDot(*dag); } sched = new SDCScheduler(alloc); sched->schedule(Fp, dag); fsm = sched->getFSM(Fp); modifyFSMForAllLoopPipelines(); // Warning: the FSM at this point is missing a few TransitionVariables. // these will be added later when we have access to the RTLModule createBindingFSM(); } void GenerateRTL::addTagOffsetParameterToModule() { RTLSignal *tag_offset = rtl->addParam("tag_offset", "0"); tag_offset->setWidth(RTLWidth(utostr(alloc->getTagSize() - 1))); std::string bottomBits = utostr((int)alloc->getDataLayout()->getPointerSizeInBits() - alloc->getTagSize()) + "'d0"; std::string tag_addr_offset_value = "{tag_offset, " + bottomBits + "}"; RTLSignal *tag_addr_offset = rtl->addParam("tag_addr_offset", tag_addr_offset_value); tag_addr_offset->setWidth(RTLWidth("`MEMORY_CONTROLLER_ADDR_SIZE-1")); } void GenerateRTL::addDebugRtl() { RTLSignal *sigCurState; RTLSignal *sigActiveInst; // outs() << "Adding debug instrumentation to " << Fp->getName().str() << // "\n"; fsm->buildStatePredecessors(); // Add output for the instance Id sigActiveInst = rtl->addOut(DEBUG_SIGNAL_NAME_ACTIVE_INST, alloc->getDbgInfo()->getInstanceIdBits()); // Add output for the current state (in encoded, or one-hot) if (alloc->getDbgInfo()->getOptionPreserveOneHot()) { string sigCurStateName = DEBUG_SIGNAL_NAME_CURRENT_STATE; sigCurState = rtl->addWire(sigCurStateName, fsm->size()); } else { string sigCurStateName = DEBUG_SIGNAL_NAME_CURRENT_STATE; sigCurState = rtl->addOut(sigCurStateName, alloc->getDbgInfo()->getStateBits()); } // Add Parent Instance Parameter RTLSignal *parentInstanceParam = rtl->addParam(DEBUG_PARAM_NAME_PARENT_INST, "0"); parentInstanceParam->setWidth(alloc->getDbgInfo()->getInstanceIdBits()); // Add Instance Parameter string instanceParamVal = DEBUG_VERILOG_FUNC_NAME_INSTANCE_MAPPING; instanceParamVal += "("; instanceParamVal += DEBUG_PARAM_NAME_PARENT_INST; instanceParamVal += ")"; RTLSignal *instanceParam = rtl->addParam(DEBUG_PARAM_NAME_INST, instanceParamVal); instanceParam->setWidth(alloc->getDbgInfo()->getInstanceIdBits()); // Create logic to drive the current state output. // For one-hot encoding, each bit of the output will be driven by some logic // (state == XXX) // For fully encoded, the output will be driven by a series of statements // such as: if (state == S_XXX) then out = 1 vector<RTLSignal *> statesOneHot; int stateCount = 0; for (FiniteStateMachine::iterator state = fsm->begin(), state_end = fsm->end(); state != state_end; ++state) { Function *calledFunc = state->getCalledFunction(); if (calledFunc) { // outs() << "Called function: " << //calledFunc->getName().str() << "\n"; // The debugger outputs the active instance/state to the top-level // The instance/state wires need to be driven by the child module // during // a function call. string calledFuncName = verilogName(calledFunc); string dbgActiveInstanceSigName = calledFuncName + "_" + DEBUG_SIGNAL_NAME_ACTIVE_INST; string dbgCurrentStateSigName = calledFuncName + "_" + DEBUG_SIGNAL_NAME_CURRENT_STATE; RTLSignal *sigActiveInstChild = rtl->addWire( dbgActiveInstanceSigName, RTLWidth(alloc->getDbgInfo()->getInstanceIdBits())); connectSignalToDriverInState(sigActiveInst, sigActiveInstChild, state); if (!alloc->getDbgInfo()->getOptionPreserveOneHot()) { RTLSignal *sigCurStateChild = rtl->addWire(dbgCurrentStateSigName, RTLWidth(alloc->getDbgInfo()->getStateBits())); connectSignalToDriverInState(sigCurState, sigCurStateChild, state); } } else { // For every state (except function calls), the state number // needs to be connected to a wire, which goes out to the // debugger if (!alloc->getDbgInfo()->getOptionPreserveOneHot()) { RTLConst *constVal = new RTLConst( getStateSignal(state)->getValue(), sigCurState->getWidth()); connectSignalToDriverInState(sigCurState, constVal, state); } } if (alloc->getDbgInfo()->getOptionPreserveOneHot()) { string tempStateName = "stateOneHot"; tempStateName += std::to_string(stateCount); RTLSignal *tempState = rtl->addWire(tempStateName, RTLWidth(1)); statesOneHot.push_back(tempState); if (LEGUP_CONFIG->getParameterInt("CASEX")) { RTLOp *op = rtl->addOp(RTLOp::Trunc); string stateStr = std::to_string(stateCount); op->setCastWidth(RTLWidth(stateStr, stateStr)); op->setOperand(0, rtl->find("cur_state")); tempState->connect(op, NULL); } else { tempState->setDefaultDriver(ZERO); connectSignalToDriverInState(tempState, ONE, state); } } stateCount += 1; } if (alloc->getDbgInfo()->getOptionPreserveOneHot()) { RTLSignal *concated = NULL; for (vector<RTLSignal *>::iterator s_it = statesOneHot.begin(), s_end = statesOneHot.end(); s_it != s_end; ++s_it) { if (!concated) { concated = *s_it; } else { RTLOp *concat = rtl->addOp(RTLOp::Concat); concat->setOperand(0, *s_it); concat->setOperand(1, concated); concated = concat; } } sigCurState->connect(concated); string statePortName = Fp->getName().str() + DEBUG_HIERARCHY_PATH_SEP + sigCurState->getName(); RTLSignal *sigCurStatePort = rtl->addOut(statePortName, sigCurState->getWidth()); sigCurStatePort->connect(sigCurState, NULL); dbgStatePorts.push_back( new RTLDebugPort(sigCurStatePort, this, sigCurState)); } // Forward registers that need to be traced to top-level ports if (alloc->getDbgInfo()->getOptionTraceRegs()) addDebugTraceOutputs(); for (std::map<Function *, RTLModule *>::iterator child_it = calledModulesToRtlMap.begin(), child_end = calledModulesToRtlMap.end(); child_it != child_end; ++child_it) { Function *childFp = child_it->first; GenerateRTL *childGenRtl = alloc->getGenerateRTL(childFp); RTLModule *childRtl = child_it->second; // Adds top-level outputs for the signals in the // instantiated child modules that need to be traced if (alloc->getDbgInfo()->getOptionTraceRegs()) { vector<RTLDebugPort *> *childPorts = &(childGenRtl->dbgTracePorts); // Connect up each signal for (vector<RTLDebugPort *>::iterator port_it = childPorts->begin(), port_end = childPorts->end(); port_it != port_end; ++port_it) { RTLDebugPort *port = *port_it; RTLSignal *signal = port->getSignal(); RTLSignal *newOut = rtl->addOut(Fp->getName().str() + DEBUG_HIERARCHY_PATH_SEP + signal->getName(), signal->getWidth()); childRtl->addOut(signal->getName(), signal->getWidth()) ->connect(newOut); dbgTracePorts.push_back(new RTLDebugPort(port, newOut)); } } if (alloc->getDbgInfo()->getOptionPreserveOneHot()) { // Adds top-level outputs for the state signals in the instantiated // child modules vector<RTLDebugPort *> *childPorts = &(childGenRtl->dbgStatePorts); // Connect up each signal for (vector<RTLDebugPort *>::iterator port_it = childPorts->begin(), port_end = childPorts->end(); port_it != port_end; ++port_it) { RTLDebugPort *port = *port_it; RTLSignal *signal = port->getSignal(); RTLSignal *newOut = rtl->addOut(Fp->getName().str() + DEBUG_HIERARCHY_PATH_SEP + signal->getName(), signal->getWidth()); childRtl->addOut(signal->getName(), signal->getWidth()) ->connect(newOut); dbgStatePorts.push_back(new RTLDebugPort(port, newOut)); } } childRtl->addParam(DEBUG_PARAM_NAME_PARENT_INST, DEBUG_PARAM_NAME_INST); string activeInstanceSigName = verilogName(childFp) + "_" + DEBUG_SIGNAL_NAME_ACTIVE_INST; RTLSignal *activeInstanceSig = rtl->find(activeInstanceSigName); childRtl->addOut(DEBUG_SIGNAL_NAME_ACTIVE_INST) ->connect(activeInstanceSig); if (!alloc->getDbgInfo()->getOptionPreserveOneHot()) { string currentStateSigName = verilogName(childFp) + "_" + DEBUG_SIGNAL_NAME_CURRENT_STATE; RTLSignal *currentStateSig = rtl->find(currentStateSigName); childRtl->addOut(DEBUG_SIGNAL_NAME_CURRENT_STATE) ->connect(currentStateSig); } } // By default, drive the active instance by the instance parameter sigActiveInst->setDefaultDriver(instanceParam); // If reset, active instance should be 0 RTLOp *cond; cond = rtl->addOp(RTLOp::EQ); cond->setOperand(0, rtl->find("reset")); cond->setOperand(1, ONE); sigActiveInst->addCondition( cond, new RTLConst("0", sigActiveInst->getWidth()), NULL); } // Find all registers that need to be traced from within this module // and output them to top-level ports void GenerateRTL::addDebugTraceOutputs() { set<RTLSignal *> sigTraced; // Find all registers that need to be traced from this module for (vector<DebugVariableLocal *>::iterator var_iter = dbgVars.begin(), var_end = dbgVars.end(); var_iter != var_end; ++var_iter) { DebugVariableLocal *var = *var_iter; for (vector<DebugValue *>::iterator dv_it = var->getDbgValues()->begin(), dv_end = var->getDbgValues()->end(); dv_it != dv_end; ++dv_it) { DebugValue *val = *dv_it; RTLSignal *sigToTrace = NULL; if (val->requiresSignalTracing()) { sigToTrace = rtl->find(val->getSignalName()); assert(sigToTrace); if (sigTraced.find(sigToTrace) == sigTraced.end()) sigTraced.insert(sigToTrace); else continue; string traceName = Fp->getName().str() + DEBUG_HIERARCHY_PATH_SEP + sigToTrace->getName(); RTLSignal *s = rtl->addOut(traceName, sigToTrace->getWidth()); s->connect(sigToTrace, NULL); RTLDebugPort *newDbgPort = new RTLDebugPort(s, this, sigToTrace); dbgTracePorts.push_back(newDbgPort); } } } } // This recursive function creates a unique ID for each *instance* of each // module. // The same GenerateRTL module can be instantiated from multiple parent // modules, and each parent could be instantiated from different parents, and so // forth, // So, this function registers an instanceId with the debugging info for this // GenerateRTL module, given its parent instance ID. void GenerateRTL::generateInstances(int parentInstanceId) { RTLModuleInstance *myInst = alloc->getDbgInfo()->newInstance(this, parentInstanceId); instances.push_back(myInst); rtl->dbgAddInstanceMapping(parentInstanceId, myInst->getId()); for (set<Function *>::iterator fp_it = calledModules.begin(), fp_end = calledModules.end(); fp_it != fp_end; ++fp_it) { Function *childFp = *fp_it; GenerateRTL *childGenRtl = alloc->getGenerateRTL(childFp); childGenRtl->generateInstances(myInst->getId()); } } // This function returns the Debugging info class for a variable, // specified by the MDNode. DebugVariableLocal *GenerateRTL::dbgGetVariable(MDNode *metaNode) { // Check if this variable has already been allocated for (auto var_it = dbgVars.begin(), e = dbgVars.end(); var_it != e; ++var_it) { if ((*var_it)->getMetaNode() == metaNode) return *var_it; } // If the variable is not already added, allocate a new one DebugVariableLocal *v = new DebugVariableLocal(metaNode, this); dbgVars.push_back(v); return v; } GenerateRTL::~GenerateRTL() { assert(sched); assert(sched->getFSM(Fp)); delete sched->getFSM(Fp); delete sched; assert(rtl); delete rtl; assert(binding); delete binding; assert(dag); delete dag; } } // End legup namespace
35.235718
118
0.645329
[ "object", "vector" ]
0892b2a16673567877a2c568196288fc854e43ba
27,526
cpp
C++
examples/IBFE/explicit/ex0/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
examples/IBFE/explicit/ex0/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
examples/IBFE/explicit/ex0/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2002-2013, Boyce Griffith // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // Config files #include <IBAMR_prefix_config.h> #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for basic SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for basic libMesh objects #include <libmesh/equation_systems.h> #include <libmesh/exodusII_io.h> #include <libmesh/mesh.h> #include <libmesh/mesh_generation.h> #include <libmesh/periodic_boundary.h> // Headers for application-specific algorithm/data structure objects #include <ibamr/IBExplicitHierarchyIntegrator.h> #include <ibamr/IBFEMethod.h> #include <ibamr/INSCollocatedHierarchyIntegrator.h> #include <ibamr/INSStaggeredHierarchyIntegrator.h> #include <ibamr/app_namespaces.h> #include <ibtk/AppInitializer.h> #include <ibtk/libmesh_utilities.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/muParserRobinBcCoefs.h> // Elasticity model data. namespace ModelData { // Problem parameters. static const double R = 0.25; static const double w = 0.0625; static const double gamma = 0.0; static const double mu = 1.0; // Coordinate mapping function. void coordinate_mapping_function( Point& X, const Point& s, void* /*ctx*/) { X(0) = (R+ s(1))*cos(s(0)/R)+0.5; X(1) = (R+gamma+s(1))*sin(s(0)/R)+0.5; return; }// coordinate_mapping_function // Stress tensor function. bool smooth_case = false; void PK1_stress_function( TensorValue<double>& PP, const TensorValue<double>& FF, const Point& /*X*/, const Point& /*s*/, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const std::vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { PP = (mu/w)*FF; if (smooth_case) { PP(0,1) = 0.0; PP(1,1) = 0.0; } return; }// PK1_stress_function } using namespace ModelData; // Function prototypes void output_data( Pointer<PatchHierarchy<NDIM> > patch_hierarchy, Pointer<INSHierarchyIntegrator> navier_stokes_integrator, Mesh& mesh, EquationSystems* equation_systems, const int iteration_num, const double loop_time, const string& data_dump_dirname); /******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main( int argc, char* argv[]) { // Initialize libMesh, PETSc, MPI, and SAMRAI. LibMeshInit init(argc, argv); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty(); const string exodus_filename = app_initializer->getExodusIIFilename(); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_postproc_data = app_initializer->dumpPostProcessingData(); const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval(); const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory(); if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty()) { Utilities::recursiveMkdir(postproc_data_dump_dirname); } const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Create a simple FE mesh with periodic boundary conditions in the "x" // direction. // // Note that boundary condition data must be registered with each FE // system before calling IBFEMethod::initializeFEData(). Mesh mesh(NDIM); const double R = 0.25; const double w = 0.0625; const double dx0 = 1.0/64.0; const double dx = input_db->getDouble("DX"); const double ds0 = input_db->getDouble("MFAC")*dx0; string elem_type = input_db->getString("ELEM_TYPE"); MeshTools::Generation::build_square(mesh, 4*static_cast<int>((dx0/dx)*ceil(2.0*M_PI*R/ds0/4.0)), static_cast<int>((dx0/dx)*ceil(w/ds0)), 0.0, 2.0*M_PI*R, 0.0, w, Utility::string_to_enum<ElemType>(elem_type)); VectorValue<double> boundary_translation(2.0*M_PI*R, 0.0, 0.0); PeriodicBoundary pbc(boundary_translation); pbc.myboundary = 3; pbc.pairedboundary = 1; // Configure stress tensor options. smooth_case = input_db->getBool("SMOOTH_CASE"); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<INSHierarchyIntegrator> navier_stokes_integrator; const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type"); if (solver_type == "STAGGERED") { navier_stokes_integrator = new INSStaggeredHierarchyIntegrator( "INSStaggeredHierarchyIntegrator", app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator")); } else if (solver_type == "COLLOCATED") { navier_stokes_integrator = new INSCollocatedHierarchyIntegrator( "INSCollocatedHierarchyIntegrator", app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator")); } else { TBOX_ERROR("Unsupported solver type: " << solver_type << "\n" << "Valid options are: COLLOCATED, STAGGERED"); } Pointer<IBFEMethod> ib_method_ops = new IBFEMethod( "IBFEMethod", app_initializer->getComponentDatabase("IBFEMethod"), &mesh, app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")); Pointer<IBHierarchyIntegrator> time_integrator = new IBExplicitHierarchyIntegrator( "IBHierarchyIntegrator", app_initializer->getComponentDatabase("IBHierarchyIntegrator"), ib_method_ops, navier_stokes_integrator); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>( "PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>( "StandardTagAndInitialize", time_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>( "LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>( "GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Configure the IBFE solver. ib_method_ops->registerInitialCoordinateMappingFunction(&coordinate_mapping_function); ib_method_ops->registerPK1StressTensorFunction(&PK1_stress_function); EquationSystems* equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems(); for (unsigned int k = 0; k < equation_systems->n_systems(); ++k) { System& system = equation_systems->get_system(k); system.get_dof_map().add_periodic_boundary(pbc); } // Create Eulerian initial condition specification objects. These // objects also are used to specify exact solution values for error // analysis. Pointer<CartGridFunction> u_init = new muParserCartGridFunction( "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry); navier_stokes_integrator->registerVelocityInitialConditions(u_init); Pointer<CartGridFunction> p_init = new muParserCartGridFunction( "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry); navier_stokes_integrator->registerPressureInitialConditions(p_init); // Create Eulerian boundary condition specification objects (when necessary). const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift(); vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM); if (periodic_shift.min() > 0) { for (unsigned int d = 0; d < NDIM; ++d) { u_bc_coefs[d] = NULL; } } else { for (unsigned int d = 0; d < NDIM; ++d) { ostringstream bc_coefs_name_stream; bc_coefs_name_stream << "u_bc_coefs_" << d; const string bc_coefs_name = bc_coefs_name_stream.str(); ostringstream bc_coefs_db_name_stream; bc_coefs_db_name_stream << "VelocityBcCoefs_" << d; const string bc_coefs_db_name = bc_coefs_db_name_stream.str(); u_bc_coefs[d] = new muParserRobinBcCoefs( bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry); } navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs); } // Create Eulerian body force function specification objects. if (input_db->keyExists("ForcingFunction")) { Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction( "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry); time_integrator->registerBodyForceFunction(f_fcn); } // Set up visualization plot file writers. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) { time_integrator->registerVisItDataWriter(visit_data_writer); } AutoPtr<ExodusII_IO> exodus_io(uses_exodus ? new ExodusII_IO(mesh) : NULL); // Initialize hierarchy configuration and data on all patches. ib_method_ops->initializeFEData(); time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm); // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Setup data used to determine the accuracy of the computed solution. VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); const Pointer<hier::Variable<NDIM> > u_var = navier_stokes_integrator->getVelocityVariable(); const Pointer<VariableContext> u_ctx = navier_stokes_integrator->getCurrentContext(); const int u_idx = var_db->mapVariableAndContextToIndex(u_var, u_ctx); const int u_cloned_idx = var_db->registerClonedPatchDataIndex(u_var, u_idx); const Pointer<hier::Variable<NDIM> > p_var = navier_stokes_integrator->getPressureVariable(); const Pointer<VariableContext> p_ctx = navier_stokes_integrator->getCurrentContext(); const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx); const int p_cloned_idx = var_db->registerClonedPatchDataIndex(p_var, p_idx); visit_data_writer->registerPlotQuantity("P error", "SCALAR", p_cloned_idx); const int coarsest_ln = 0; const int finest_ln = patch_hierarchy->getFinestLevelNumber(); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { patch_hierarchy->getPatchLevel(ln)->allocatePatchData(u_cloned_idx); patch_hierarchy->getPatchLevel(ln)->allocatePatchData(p_cloned_idx); } // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data) { pout << "\n\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { exodus_io->write_timestep(exodus_filename, *equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } // Open streams to save volume of structure. ofstream volume_stream; if (SAMRAI_MPI::getRank() == 0) { volume_stream.open("volume.curve", ios_base::out | ios_base::trunc); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); double dt = 0.0; while (!MathUtilities<double>::equalEps(loop_time,loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; dt = time_integrator->getMaximumTimeStepSize(); time_integrator->advanceHierarchy(dt); loop_time += dt; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // print out timer data, and store hierarchy data for post // processing. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && (iteration_num%viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { exodus_io->write_timestep(exodus_filename, *equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } if (dump_restart_data && (iteration_num%restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\n"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num%timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } if (dump_postproc_data && (iteration_num%postproc_data_dump_interval == 0 || last_step)) { pout << "\nWriting state data...\n\n"; output_data(patch_hierarchy, navier_stokes_integrator, mesh, equation_systems, iteration_num, loop_time, postproc_data_dump_dirname); } // Compute velocity and pressure error norms. const int coarsest_ln = 0; const int finest_ln = patch_hierarchy->getFinestLevelNumber(); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); if (!level->checkAllocated(u_cloned_idx)) level->allocatePatchData(u_cloned_idx); if (!level->checkAllocated(p_cloned_idx)) level->allocatePatchData(p_cloned_idx); } pout << "\n" << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n" << "Computing error norms.\n\n"; u_init->setDataOnPatchHierarchy(u_cloned_idx, u_var, patch_hierarchy, loop_time); p_init->setDataOnPatchHierarchy(p_cloned_idx, p_var, patch_hierarchy, loop_time-0.5*dt); HierarchyMathOps hier_math_ops("HierarchyMathOps", patch_hierarchy); hier_math_ops.setPatchHierarchy(patch_hierarchy); hier_math_ops.resetLevels(coarsest_ln, finest_ln); const double volume = hier_math_ops.getVolumeOfPhysicalDomain(); const int wgt_cc_idx = hier_math_ops.getCellWeightPatchDescriptorIndex(); const int wgt_sc_idx = hier_math_ops.getSideWeightPatchDescriptorIndex(); Pointer<CellVariable<NDIM,double> > u_cc_var = u_var; if (u_cc_var) { HierarchyCellDataOpsReal<NDIM,double> hier_cc_data_ops(patch_hierarchy, coarsest_ln, finest_ln); hier_cc_data_ops.subtract(u_cloned_idx, u_idx, u_cloned_idx); pout << "Error in u at time " << loop_time << ":\n" << " L1-norm: " << hier_cc_data_ops. L1Norm(u_cloned_idx,wgt_cc_idx) << "\n" << " L2-norm: " << hier_cc_data_ops. L2Norm(u_cloned_idx,wgt_cc_idx) << "\n" << " max-norm: " << hier_cc_data_ops.maxNorm(u_cloned_idx,wgt_cc_idx) << "\n"; } Pointer<SideVariable<NDIM,double> > u_sc_var = u_var; if (u_sc_var) { HierarchySideDataOpsReal<NDIM,double> hier_sc_data_ops(patch_hierarchy, coarsest_ln, finest_ln); hier_sc_data_ops.subtract(u_cloned_idx, u_idx, u_cloned_idx); pout << "Error in u at time " << loop_time << ":\n" << " L1-norm: " << hier_sc_data_ops. L1Norm(u_cloned_idx,wgt_sc_idx) << "\n" << " L2-norm: " << hier_sc_data_ops. L2Norm(u_cloned_idx,wgt_sc_idx) << "\n" << " max-norm: " << hier_sc_data_ops.maxNorm(u_cloned_idx,wgt_sc_idx) << "\n"; } HierarchyCellDataOpsReal<NDIM,double> hier_cc_data_ops(patch_hierarchy, coarsest_ln, finest_ln); const double p_mean = (1.0/volume)*hier_cc_data_ops.integral(p_idx, wgt_cc_idx); hier_cc_data_ops.addScalar(p_idx, p_idx, -p_mean); const double p_cloned_mean = (1.0/volume)*hier_cc_data_ops.integral(p_cloned_idx, wgt_cc_idx); hier_cc_data_ops.addScalar(p_cloned_idx, p_cloned_idx, -p_cloned_mean); hier_cc_data_ops.subtract(p_cloned_idx, p_idx, p_cloned_idx); pout << "Error in p at time " << loop_time-0.5*dt << ":\n" << " L1-norm: " << hier_cc_data_ops. L1Norm(p_cloned_idx,wgt_cc_idx) << "\n" << " L2-norm: " << hier_cc_data_ops. L2Norm(p_cloned_idx,wgt_cc_idx) << "\n" << " max-norm: " << hier_cc_data_ops.maxNorm(p_cloned_idx,wgt_cc_idx) << "\n" << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; // Compute the volume of the structure. double J_integral = 0.0; System& X_system = equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME); NumericVector<double>* X_vec = X_system.solution.get(); NumericVector<double>* X_ghost_vec = X_system.current_local_solution.get(); X_vec->localize(*X_ghost_vec); DofMap& X_dof_map = X_system.get_dof_map(); blitz::Array<std::vector<unsigned int>,1> X_dof_indices(NDIM); AutoPtr<FEBase> fe(FEBase::build(NDIM, X_dof_map.variable_type(0))); AutoPtr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH); fe->attach_quadrature_rule(qrule.get()); const std::vector<double>& JxW = fe->get_JxW(); const std::vector<std::vector<VectorValue<double> > >& dphi = fe->get_dphi(); TensorValue<double> FF; blitz::Array<double,2> X_node; const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end(); for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it) { Elem* const elem = *el_it; fe->reinit(elem); for (unsigned int d = 0; d < NDIM; ++d) { X_dof_map.dof_indices(elem, X_dof_indices(d), d); } const int n_qp = qrule->n_points(); get_values_for_interpolation(X_node, *X_ghost_vec, X_dof_indices); for (int qp = 0; qp < n_qp; ++qp) { jacobian(FF,qp,X_node,dphi); J_integral += abs(FF.det())*JxW[qp]; } } J_integral = SAMRAI_MPI::sumReduction(J_integral); if (SAMRAI_MPI::getRank() == 0) { volume_stream.precision(12); volume_stream.setf(ios::fixed,ios::floatfield); volume_stream << loop_time << " " << J_integral << endl; } } // Close the logging streams. if (SAMRAI_MPI::getRank() == 0) { volume_stream.close(); } // Cleanup Eulerian boundary condition specification objects (when // necessary). for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d]; }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); return 0; }// main void output_data( Pointer<PatchHierarchy<NDIM> > patch_hierarchy, Pointer<INSHierarchyIntegrator> navier_stokes_integrator, Mesh& mesh, EquationSystems* equation_systems, const int iteration_num, const double loop_time, const string& data_dump_dirname) { plog << "writing hierarchy data at iteration " << iteration_num << " to disk" << endl; plog << "simulation time is " << loop_time << endl; // Write Cartesian data. string file_name = data_dump_dirname + "/" + "hier_data."; char temp_buf[128]; sprintf(temp_buf, "%05d.samrai.%05d", iteration_num, SAMRAI_MPI::getRank()); file_name += temp_buf; Pointer<HDFDatabase> hier_db = new HDFDatabase("hier_db"); hier_db->create(file_name); VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); ComponentSelector hier_data; hier_data.setFlag(var_db->mapVariableAndContextToIndex(navier_stokes_integrator->getVelocityVariable(), navier_stokes_integrator->getCurrentContext())); hier_data.setFlag(var_db->mapVariableAndContextToIndex(navier_stokes_integrator->getPressureVariable(), navier_stokes_integrator->getCurrentContext())); patch_hierarchy->putToDatabase(hier_db->putDatabase("PatchHierarchy"), hier_data); hier_db->putDouble("loop_time", loop_time); hier_db->putInteger("iteration_num", iteration_num); hier_db->close(); // Write Lagrangian data. file_name = data_dump_dirname + "/" + "fe_mesh."; sprintf(temp_buf, "%05d", iteration_num); file_name += temp_buf; file_name += ".xda"; mesh.write(file_name); file_name = data_dump_dirname + "/" + "fe_equation_systems."; sprintf(temp_buf, "%05d", iteration_num); file_name += temp_buf; equation_systems->write(file_name, (EquationSystems::WRITE_DATA | EquationSystems::WRITE_ADDITIONAL_DATA)); return; }// output_data
48.038394
172
0.625954
[ "mesh", "vector", "model" ]
089516ce2736caa09083abf715b8af06316f4d08
6,449
hh
C++
src/gpu-compute/register_file.hh
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/gpu-compute/register_file.hh
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
30
2015-01-01T21:49:38.000Z
2021-04-20T19:01:54.000Z
src/gpu-compute/register_file.hh
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
/* * Copyright (c) 2015-2017 Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __REGISTER_FILE_HH__ #define __REGISTER_FILE_HH__ #include <limits> #include <vector> #include "base/statistics.hh" #include "base/types.hh" #include "gpu-compute/misc.hh" #include "sim/sim_object.hh" namespace gem5 { class ComputeUnit; class Shader; class PoolManager; class Wavefront; struct RegisterFileParams; // Abstract Register File // This register file class can be inherited from to create both // scalar and vector register files. class RegisterFile : public SimObject { public: RegisterFile(const RegisterFileParams &p); virtual ~RegisterFile(); virtual void setParent(ComputeUnit *_computeUnit); int numRegs() const { return _numRegs; } // State functions // Scoreboard functions virtual bool operandsReady(Wavefront *w, GPUDynInstPtr ii) const; virtual bool regBusy(int idx) const; virtual void markReg(int regIdx, bool value); // Abstract Register Event class RegisterEvent : public Event { protected: RegisterFile *rf; int regIdx; public: RegisterEvent(RegisterFile *_rf, int _regIdx) : rf(_rf), regIdx(_regIdx) { setFlags(AutoDelete); } }; // Register Event to mark a register as free in the scoreboard/busy vector class MarkRegFreeScbEvent : public RegisterEvent { public: MarkRegFreeScbEvent(RegisterFile *_rf, int _regIdx) : RegisterEvent(_rf, _regIdx) { } void process(); }; // Register Event to mark a register as busy in the scoreboard/busy vector class MarkRegBusyScbEvent : public RegisterEvent { public: MarkRegBusyScbEvent(RegisterFile *_rf, int _regIdx) : RegisterEvent(_rf, _regIdx) { } void process(); }; // Schedule an event to mark a register as free/busy in // the scoreboard/busy vector. Delay is already in Ticks virtual void enqRegFreeEvent(uint32_t regIdx, uint64_t delay); virtual void enqRegBusyEvent(uint32_t regIdx, uint64_t delay); // Schedule functions // The following functions are called by the SCH stage when attempting // to move a wave from the readyList to the schList. // canSchedule* checks if the RF is ready to provide operands for // the instruction, while schedule* requests the RF to begin reading // and writing of operands. Calling schedule* may only occur // immediately after canSchedule* was called and returned True virtual bool canScheduleReadOperands(Wavefront *w, GPUDynInstPtr ii); virtual bool canScheduleWriteOperands(Wavefront *w, GPUDynInstPtr ii); virtual void scheduleReadOperands(Wavefront *w, GPUDynInstPtr ii); virtual void scheduleWriteOperands(Wavefront *w, GPUDynInstPtr ii); // The following function is called to check if all operands // have been read for the given instruction virtual bool operandReadComplete(Wavefront *w, GPUDynInstPtr ii); // The following two functions are only called by returning loads to // check if the register file can support the incoming writes virtual bool canScheduleWriteOperandsFromLoad(Wavefront *w, GPUDynInstPtr ii); // Queue the register writes. Assumes canScheduleWriteOperandsFromLoad // was called immediately prior and returned True virtual void scheduleWriteOperandsFromLoad(Wavefront *w, GPUDynInstPtr ii); // ExecRF is invoked every cycle by the compute unit and may be // used to model detailed timing of the register file. virtual void exec(); // Called to inform RF that an instruction is executing // to schedule events for writeback, etc., as needed virtual void waveExecuteInst(Wavefront *w, GPUDynInstPtr ii); // Debug functions virtual std::string dump() const; virtual void dispatchInstruction(GPUDynInstPtr ii); protected: ComputeUnit* computeUnit; int simdId; // flag indicating if a register is busy std::vector<bool> busy; // numer of registers in this register file int _numRegs; struct RegisterFileStats : public statistics::Group { RegisterFileStats(statistics::Group *parent); // Total number of register reads per DWORD per thread statistics::Scalar registerReads; // Total number of register writes per DWORD per thread statistics::Scalar registerWrites; // Number of register file SRAM activations for reads. // The register file may be implemented with multiple SRAMs. This stat // tracks how many times the SRAMs are accessed for reads. statistics::Scalar sramReads; // Number of register file SRAM activations for writes statistics::Scalar sramWrites; } stats; }; } // namespace gem5 #endif // __REGISTER_FILE_HH__
36.642045
79
0.71608
[ "vector", "model" ]
089c783c1ac9f69c79be14d28fc9f3a16ac01390
4,269
cc
C++
newnnfw/runtimes/pure_arm_compute/src/internal/layers/SimpleEmbeddingLookup.cc
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
8
2018-09-10T01:32:26.000Z
2020-05-13T06:05:40.000Z
newnnfw/runtimes/pure_arm_compute/src/internal/layers/SimpleEmbeddingLookup.cc
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
28
2018-09-10T05:01:09.000Z
2021-03-04T10:07:12.000Z
newnnfw/runtimes/pure_arm_compute/src/internal/layers/SimpleEmbeddingLookup.cc
kosslab-kr/Tizen-NN-Framework
132fc98ed57e4b19ad1f4cb258ad79fa9df1db7a
[ "Apache-2.0" ]
4
2018-09-13T04:16:08.000Z
2018-12-03T07:34:44.000Z
#include "internal/layers/SimpleEmbeddingLookup.h" #include <arm_compute/runtime/CL/CLScheduler.h> void SimpleEmbeddingLookup::configure(::arm_compute::ITensor *lookups, ::arm_compute::ITensor *values, ::arm_compute::ITensor *output) { // Assume that verification of operands are already done at Planner::visit() _lookups = lookups; _values = values; _output = output; } void SimpleEmbeddingLookup::run() { if (::internal::arm_compute::isGpuMode()) { auto &q = ::arm_compute::CLScheduler::get().queue(); CAST_CL(_lookups)->map(q); CAST_CL(_values)->map(q); CAST_CL(_output)->map(q); } // type of elements of lookups is always integer const int32_t *lookups_buf = reinterpret_cast<int32_t *>(_lookups->buffer()); const auto values_buf = _values->buffer(); auto output_buf = _output->buffer(); const auto lookups_info = _lookups->info(); const auto values_info = _values->info(); const auto output_info = _output->info(); // TODO Refactor below duplicated code! const auto values_rank = values_info->num_dimensions(); switch (values_rank) { case 2: // (H,W) in nnapi -> (W,H) in acl { const size_t row_size = values_info->dimension(1); const size_t row_bytes = values_info->total_size() / row_size; for (size_t i = 0; i < lookups_info->dimension(0); ++i) { if (lookups_buf[i] < 0 || lookups_buf[i] >= row_size) throw std::runtime_error("Embedding Lookup: index out of bounds."); size_t idx = lookups_buf[i]; size_t row_offset_by_idx = values_info->offset_element_in_bytes({0, idx}); size_t row_offset_by_i = output_info->offset_element_in_bytes({0, i}); unsigned char *sink_addr = output_buf + row_offset_by_i; unsigned char *source_addr = values_buf + row_offset_by_idx; memcpy(sink_addr, source_addr, row_bytes); } } break; case 3: // (B,H,W) in nnapi -> (W,H,B) in acl { const size_t row_size = values_info->dimension(2); const size_t row_bytes = values_info->total_size() / row_size; for (size_t i = 0; i < lookups_info->dimension(0); ++i) { if (lookups_buf[i] < 0 || lookups_buf[i] >= row_size) throw std::runtime_error("Embedding Lookup: index out of bounds."); size_t idx = lookups_buf[i]; size_t row_offset_by_idx = values_info->offset_element_in_bytes({0, 0, idx}); size_t row_offset_by_i = output_info->offset_element_in_bytes({0, 0, i}); unsigned char *sink_addr = output_buf + row_offset_by_i; unsigned char *source_addr = values_buf + row_offset_by_idx; memcpy(sink_addr, source_addr, row_bytes); } } break; case 4: // (N,H,W,C) in nnapi -> (N,C,H,W) in acl { const size_t row_size = values_info->dimension(3); const size_t row_bytes = values_info->total_size() / row_size; for (size_t i = 0; i < lookups_info->dimension(0); ++i) { if (lookups_buf[i] < 0 || lookups_buf[i] >= row_size) throw std::runtime_error("Embedding Lookup: index out of bounds."); size_t idx = lookups_buf[i]; size_t row_offset_by_idx = values_info->offset_element_in_bytes({0, 0, 0, idx}); size_t row_offset_by_i = output_info->offset_element_in_bytes({0, 0, 0, i}); unsigned char *sink_addr = output_buf + row_offset_by_i; unsigned char *source_addr = values_buf + row_offset_by_idx; memcpy(sink_addr, source_addr, row_bytes); } } break; case 1: // In this case, shape of values actually is matrix but the height(row size) is 1 in acl. If // row size is 1, this op is not needed and it means this situtation could be wrong. throw std::runtime_error("Wrong usage of EmbeddingLookup op!"); default: throw std::runtime_error("Not supported rank!"); } if (::internal::arm_compute::isGpuMode()) { auto &q = ::arm_compute::CLScheduler::get().queue(); CAST_CL(_lookups)->unmap(q); CAST_CL(_values)->unmap(q); CAST_CL(_output)->unmap(q); } }
36.801724
98
0.625908
[ "shape" ]
089e343ae53f1ee8be86ad866db2f1bdd0fcb3c1
6,340
hpp
C++
xr3/h/xr/AABB.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
7
2018-11-13T09:44:56.000Z
2022-01-12T02:22:41.000Z
xr3/h/xr/AABB.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
2
2018-10-30T08:19:02.000Z
2018-12-31T18:48:13.000Z
xr3/h/xr/AABB.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
null
null
null
#ifndef XR_AABB_HPP #define XR_AABB_HPP //============================================================================== // // XRhodes // // copyright (c) Gyorgy Straub. All rights reserved. // // License: https://github.com/zyndor/xrhodes#License-bsd-2-clause // //============================================================================== #include <algorithm> namespace xr { //============================================================================== ///@brief Axis Aligned Bounding Box class with (world) coordinates of sizes. /// Supports Import()ing from / Export()ing to position & halfsize representation /// and HitTest()s vs other AABBs, points and line segments (swept points). ///@note Assumes the positive Y axis pointing upwards. class AABB { public: // types ///@brief Information about a HitTest() between two AABBs. ///@note When removing an object from a collision, you will need to add the /// overlap to the relevant coordinate of its position, or subtract from it /// if the object is on the far side of the other object. struct HitTestInfo { ///@brief Whether a hit has occurred. bool hit; ///@brief The amount of overlap along the X axis. float xOverlap; ///@brief The amount of overlap along the Y axis. float yOverlap; ///@return Whether the collision happened along the x axis so that you will /// work with xOverlap. ///@note Only makes sense if there was a collision, i.e. hit is true. bool IsXCollision() const; ///@return Whether the collision happened along the y axis so that you will /// work with yOverlap. ///@note Only makes sense if there was a collision, i.e. hit is true. bool IsYCollision() const; }; // data ///@brief The left side of the AABB. float left; ///@brief The top side of the AABB. float top; ///@brief The right side of the AABB. float right; ///@brief The bottom side of the AABB. float bottom; // general use ///@brief Converts position and halfsize information into world coordinates /// of the four sides of the AABB. void Import(float x, float y, float hs); ///@brief Converts position and halfsize information into world coordinates /// of the four sides of the AABB. void Import(float x, float y, float hw, float hh); ///@brief Converts world coordinates of the four sides of the AABB /// to position and halfsize information. void Export(float& x, float& y, float& hw, float& hh) const; ///@return The object's presence on the X axis. You can use the this to compare /// the relative position of AABBs. float CalculateXness() const; ///@return The object's presence on the Y axis. You can use the this to compare /// the relative position of AABBs. float CalculateYness() const; ///@brief Tests for overlap between this AABB and a 2D point. ///@return If there was an overlap. bool HitTest(float x, float y) const; ///@brief Tests for overlap between this AABB and a 2D point. /// The overlap information is stored in the HitTestInfo object. ///@return If there was an overlap. bool HitTest(float x, float y, HitTestInfo& inf) const; ///@brief Tests for overlap between this AABB and an @a other one. ///@return If there was an overlap. bool HitTest(const AABB& other) const; ///@brief Tests for overlap between this AABB and an @a other one. /// The overlap information is stored in @a inf. ///@return If there was an overlap. bool HitTest(const AABB& other, HitTestInfo& inf) const; ///@brief Tests for intersection between this AABB and a 2D line segment /// defined by start coordinates @a x0, @a y0 and extents @a dx and @a dy. ///@return If there was an overlap. bool HitTest(float x0, float y0, float dx, float dy) const; ///@brief Tests for intersection between this AABB and a 2D line segment /// defined by start coordinates @a x0, @a y0 and extents @a dx and @a dy. /// The parameter of the intersection, if any, is stored in @a t. @a x0 + /// @a t * @a dx, @a y0 + @a y * @a dy yields the intersection point in such /// case. ///@return If there was an overlap. bool HitTest(float x0, float y0, float dx, float dy, float& t) const; }; //============================================================================== // implementation //============================================================================== inline bool AABB::HitTestInfo::IsXCollision() const { return xOverlap > yOverlap; } //============================================================================== inline bool AABB::HitTestInfo::IsYCollision() const { return yOverlap > xOverlap; } //============================================================================== inline void AABB::Import(float x, float y, float hs) { Import(x, y, hs, hs); } //============================================================================== inline float AABB::CalculateXness() const { return left + right; } //============================================================================== inline float AABB::CalculateYness() const { return bottom + top; } //============================================================================== inline bool AABB::HitTest(float x, float y) const { return std::max(x - right, left - x) < .0f && std::max(y - top, bottom - y) < .0f; } //============================================================================== inline bool AABB::HitTest(float x, float y, HitTestInfo& inf) const { inf.xOverlap = std::max(x - right, left - x); inf.yOverlap = std::max(y - top, bottom - y); inf.hit = inf.xOverlap < .0f && inf.yOverlap < .0f; return inf.hit; } //============================================================================== inline bool AABB::HitTest(const AABB& other) const { return std::max(other.left - right, left - other.right) < .0f && std::max(other.bottom - top, bottom - other.top) < .0f; } //============================================================================== inline bool AABB::HitTest(const AABB& other, HitTestInfo& inf) const { inf.xOverlap = std::max(other.left - right, left - other.right); inf.yOverlap = std::max(other.bottom - top, bottom - other.top); inf.hit = inf.xOverlap < .0f && inf.yOverlap < .0f; return inf.hit; } } // xr #endif //XR_AABB_HPP
33.723404
84
0.567035
[ "object" ]
08a77e4f65b140ccb8eb0be538101ac4b2251d51
7,085
cpp
C++
copasi/UI/CQLayoutsDM.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
copasi/UI/CQLayoutsDM.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
copasi/UI/CQLayoutsDM.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <QtCore/QString> #include "CQMessageBox.h" #include "CQLayoutsDM.h" #include "qtUtilities.h" #include "copasi/CopasiDataModel/CDataModel.h" #include "copasi/core/CRootContainer.h" #include "copasi/layout/CListOfLayouts.h" CQLayoutsDM::CQLayoutsDM(QObject *parent) : CQBaseDataModel(parent, NULL), mpListOfLayouts(NULL), mNewName("layout") {} CQLayoutsDM::~CQLayoutsDM() {} size_t CQLayoutsDM::size() const { if (mpListOfLayouts != NULL) return mpListOfLayouts->size(); return 0; } int CQLayoutsDM::rowCount(const QModelIndex& C_UNUSED(parent)) const { return mFetched; } // virtual void CQLayoutsDM::resetCacheProtected() { mpListOfLayouts = mpDataModel->getListOfLayouts(); } bool CQLayoutsDM::clear() { return removeRows(0, rowCount()); } int CQLayoutsDM::columnCount(const QModelIndex & /* parent */) const { return TOTAL_COLS_LAYOUT; } Qt::ItemFlags CQLayoutsDM::flags(const QModelIndex &index) const { if (!index.isValid()) return QAbstractItemModel::flags(index); switch (index.column()) { case COL_ROW_NUMBER: return QAbstractItemModel::flags(index) & ~Qt::ItemIsEditable; break; case COL_NAME: case COL_SHOW: return QAbstractItemModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsEnabled; break; } return QAbstractItemModel::flags(index); } QVariant CQLayoutsDM::data(const QModelIndex &index, int role) const { if (mpListOfLayouts == NULL) return QVariant(); if (!index.isValid()) return QVariant(); if (index.row() >= rowCount()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case COL_ROW_NUMBER: return QVariant(index.row() + 1); break; case COL_NAME: return QVariant(FROM_UTF8(mpListOfLayouts->operator[](index.row()).getObjectName())); break; case COL_SHOW: return (role == Qt::EditRole) ? QVariant("Show") : QVariant(); break; } } return QVariant(); } QVariant CQLayoutsDM::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case COL_ROW_NUMBER: return QVariant(QString("#")); break; case COL_NAME: return QVariant(QString("Name")); break; case COL_SHOW: return QVariant("Show"); break; default: return QVariant(); break; } } return QString("%1").arg(section + 1); } bool CQLayoutsDM::setData(const QModelIndex &index, const QVariant &value, int role) { if (mpListOfLayouts == NULL) return false; if (!index.isValid()) return false; if (index.row() >= rowCount()) return false; if (index.isValid() && role == Qt::EditRole) { switch (index.column()) { case COL_ROW_NUMBER: return false; break; case COL_NAME: return mpListOfLayouts->operator[](index.row()).setObjectName(TO_UTF8(createNewName(value.toString(), COL_NAME))); break; case COL_SHOW: return true; break; default: return false; break; } } return true; } // virtual bool CQLayoutsDM::isDefaultRow(const QModelIndex & /* index */) const { return false; } bool CQLayoutsDM::insertRows(int position, int rows, const QModelIndex & parent) { if (mpListOfLayouts == NULL) return false; bool valid = parent.isValid(); int Position = valid ? parent.row() : position; if (Position + rows > (int) mpListOfLayouts->size()) return false; beginInsertRows(QModelIndex(), position, position + rows - 1); for (int row = 0; row < rows; ++row) { ++mFetched; emit notifyGUI(ListViews::ObjectType::LAYOUT, ListViews::ADD, mpListOfLayouts->operator[](Position + row).getCN()); } endInsertRows(); return true; } bool CQLayoutsDM::removeRows(int position, int rows, const QModelIndex & parent) { if (rows <= 0) return true; if (mpListOfLayouts == NULL) return false; beginRemoveRows(parent, position, position + rows - 1); std::vector< CLayout * > DeletedLayouts; DeletedLayouts.resize(rows); std::vector< CLayout * >::iterator itDeletedLayout; std::vector< CLayout * >::iterator endDeletedLayout = DeletedLayouts.end(); CListOfLayouts::iterator itRow = mpListOfLayouts->begin() + position; for (itDeletedLayout = DeletedLayouts.begin(); itDeletedLayout != endDeletedLayout; ++itDeletedLayout, ++itRow) { *itDeletedLayout = itRow; } for (itDeletedLayout = DeletedLayouts.begin(); itDeletedLayout != endDeletedLayout; ++itDeletedLayout) { --mFetched; std::string cn = (*itDeletedLayout)->getCN(); pdelete(*itDeletedLayout); emit notifyGUI(ListViews::ObjectType::LAYOUT, ListViews::DELETE, cn); } endRemoveRows(); return true; } bool CQLayoutsDM::removeRows(QModelIndexList rows, const QModelIndex & /* index */) { if (rows.isEmpty()) return false; if (mpListOfLayouts == NULL) return false; // Build the list of pointers to items to be deleted // before actually deleting any item. QList< CLayout * > Layouts; QModelIndexList::const_iterator i; for (i = rows.begin(); i != rows.end(); ++i) { Layouts.append(&mpListOfLayouts->operator[](i->row())); } QList< CLayout * >::const_iterator j; for (j = Layouts.begin(); j != Layouts.end(); ++j) { CLayout *pLayout = *j; size_t delRow = mpListOfLayouts->CDataVector< CLayout >::getIndex(pLayout); if (delRow != C_INVALID_INDEX) { QMessageBox::StandardButton choice = CQMessageBox::confirmDelete(ListViews::ancestor(this), "layout", FROM_UTF8(pLayout->getObjectName()), pLayout); if (choice == QMessageBox::Ok) removeRow((int) delRow); } } return true; } void CQLayoutsDM::setListOfLayouts(CListOfLayouts *pListOfLayouts) { if (mpListOfLayouts != pListOfLayouts) { beginResetModel(); mpListOfLayouts = pListOfLayouts; mFetched = std::min(mFetchLimit, size()); endResetModel(); //reset(); } }
25.035336
126
0.632604
[ "vector" ]