commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
d0d67849eeaccc6ca6959bc7a36208accdda3499
src/adblock_engine/ad_filter_manager.cpp
src/adblock_engine/ad_filter_manager.cpp
/* @ 0xCCCCCCCC */ #include "adblock_engine/ad_filter_manager.h" namespace abe { void AdFilterManager::LoadAdFilter(const kbase::Path& filter_file_path) { // Yeah, we don't check if there was duplicate adfilters. ad_filters_.push_back(AdFilterPair(filter_file_path, AdFilter(filter_file_path))); } void AdFilterManager::UnloadAdFilter(const kbase::Path& filter_file_path) { auto it = std::remove_if(ad_filters_.begin(), ad_filters_.end(), [&filter_file_path](const auto& filter_pair) { return filter_file_path == filter_pair.first; }); ad_filters_.erase(it, ad_filters_.end()); } bool AdFilterManager::ShouldBlockRequest(const std::string& request_url, const std::string& request_domain, unsigned content_type, bool third_party) const { bool blocking_rule_hit = false; for (const auto& filter_pair : ad_filters_) { // Logically, filter here is still constness, with respect the manager; // but we have to cast its bitwise constness away. AdFilter& filter = const_cast<AdFilter&>(filter_pair.second); auto result = filter.MatchAny(request_url, request_domain, content_type, third_party); if (result == MatchResult::BLOCKING_MATCHED) { blocking_rule_hit = true; } else if (result == MatchResult::EXCEPTION_MATCHED) { return false; } } return blocking_rule_hit; } } // namespace abe
/* @ 0xCCCCCCCC */ #include "adblock_engine/ad_filter_manager.h" #include "kbase/string_util.h" namespace abe { void AdFilterManager::LoadAdFilter(const kbase::Path& filter_file_path) { // Yeah, we don't check if there was duplicate adfilters. ad_filters_.push_back(AdFilterPair(filter_file_path, AdFilter(filter_file_path))); } void AdFilterManager::UnloadAdFilter(const kbase::Path& filter_file_path) { auto it = std::remove_if(ad_filters_.begin(), ad_filters_.end(), [&filter_file_path](const auto& filter_pair) { return filter_file_path == filter_pair.first; }); ad_filters_.erase(it, ad_filters_.end()); } bool AdFilterManager::ShouldBlockRequest(const std::string& request_url, const std::string& request_domain, unsigned content_type, bool third_party) const { bool blocking_rule_hit = false; for (const auto& filter_pair : ad_filters_) { // Logically, filter here is still constness, with respect the manager; // but we have to cast its bitwise constness away. AdFilter& filter = const_cast<AdFilter&>(filter_pair.second); auto result = filter.MatchAny(request_url, request_domain, content_type, third_party); if (result == MatchResult::BLOCKING_MATCHED) { blocking_rule_hit = true; } else if (result == MatchResult::EXCEPTION_MATCHED) { return false; } } return blocking_rule_hit; } std::string AdFilterManager::GetElementHideContent(const std::string& request_domain) const { std::set<ElemHideRule> rules; std::set<ElemHideRule> exception_rules; for (const auto& filter_pair : ad_filters_) { filter_pair.second.FetchElementHideRules(request_domain, rules, exception_rules); } std::string element_hide_rule; for (auto it = rules.begin(); it != rules.end(); ++it) { if (exception_rules.count(*it) == 0) { element_hide_rule.append(it->text).append(", "); } } return element_hide_rule; } } // namespace abe
add implementation of GetElementHideContent().
AdFilterManager: add implementation of GetElementHideContent().
C++
mit
kingsamchen/KAdBlockEngine
c32166c71fa970b409630c3efe40dd35154abf43
utils/shapeindex/shapeindex.cpp
utils/shapeindex/shapeindex.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <iostream> #include <vector> #include <string> #include <mapnik/util/fs.hpp> #include <mapnik/quad_tree.hpp> #include "shapefile.hpp" #include "shape_io.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop const int DEFAULT_DEPTH = 8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; std::vector<std::string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<std::vector<std::string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::clog << "version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { std::clog << desc << std::endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< std::vector<std::string> >(); } } catch (std::exception const& ex) { std::clog << "Error: " << ex.what() << std::endl; return -1; } std::clog << "max tree depth:" << depth << std::endl; std::clog << "split ratio:" << ratio << std::endl; if (shape_files.size() == 0) { std::clog << "no shape files to index" << std::endl; return 0; } for (auto const& filename : shape_files) { std::clog << "processing " << filename << std::endl; std::string shapename (filename); boost::algorithm::ireplace_last(shapename,".shp",""); std::string shapename_full (shapename + ".shp"); std::string shxname(shapename + ".shx"); if (! mapnik::util::exists (shapename_full)) { std::clog << "Error : file " << shapename_full << " does not exist" << std::endl; continue; } if (! mapnik::util::exists(shxname)) { std::clog << "Error : shapefile index file (*.shx) " << shxname << " does not exist" << std::endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { std::clog << "Error : cannot open " << shapename_full << std::endl; continue; } shape_file shx (shxname); if (!shx.is_open()) { std::clog << "Error : cannot open " << shxname << std::endl; continue; } int code = shx.read_xdr_integer(); //file_code == 9994 std::clog << code << std::endl; shx.skip(5*4); int file_length=shx.read_xdr_integer(); int version=shx.read_ndr_integer(); int shape_type=shx.read_ndr_integer(); box2d<double> extent; shx.read_envelope(extent); std::clog << "length=" << file_length << std::endl; std::clog << "version=" << version << std::endl; std::clog << "type=" << shape_type << std::endl; std::clog << "extent:" << extent << std::endl; int pos = 50; shx.seek(pos * 2); mapnik::quad_tree<int> tree(extent, depth, ratio); int count = 0; while (true) { int offset = shx.read_xdr_integer(); int content_length = shx.read_xdr_integer(); pos += 4; box2d<double> item_ext; shp.seek(offset * 2); int record_number = shp.read_xdr_integer(); if (content_length != shp.read_xdr_integer()) { std::clog << "Content length mismatch for record number " << record_number << std::endl; continue; } shape_type = shp.read_ndr_integer(); if (shape_type==shape_io::shape_point || shape_type==shape_io::shape_pointm || shape_type == shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); } tree.insert(offset * 2,item_ext); if (verbose) { std::clog << "record number " << record_number << " box=" << item_ext << std::endl; } ++count; if (pos >= file_length) break; } std::clog << " number shapes=" << count << std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << std::endl; } else { tree.trim(); std::clog << " number nodes=" << tree.count() << std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } std::clog << "done!" << std::endl; return 0; }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <iostream> #include <vector> #include <string> #include <mapnik/util/fs.hpp> #include <mapnik/quad_tree.hpp> #include "shapefile.hpp" #include "shape_io.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #pragma GCC diagnostic pop const int DEFAULT_DEPTH = 8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; std::vector<std::string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<std::vector<std::string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::clog << "version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { std::clog << desc << std::endl; return 1; } if (vm.count("verbose")) { verbose = true; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< std::vector<std::string> >(); } } catch (std::exception const& ex) { std::clog << "Error: " << ex.what() << std::endl; return -1; } std::clog << "max tree depth:" << depth << std::endl; std::clog << "split ratio:" << ratio << std::endl; if (shape_files.size() == 0) { std::clog << "no shape files to index" << std::endl; return 0; } for (auto const& filename : shape_files) { std::clog << "processing " << filename << std::endl; std::string shapename (filename); boost::algorithm::ireplace_last(shapename,".shp",""); std::string shapename_full (shapename + ".shp"); std::string shxname(shapename + ".shx"); if (! mapnik::util::exists (shapename_full)) { std::clog << "Error : file " << shapename_full << " does not exist" << std::endl; continue; } if (! mapnik::util::exists(shxname)) { std::clog << "Error : shapefile index file (*.shx) " << shxname << " does not exist" << std::endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { std::clog << "Error : cannot open " << shapename_full << std::endl; continue; } shape_file shx (shxname); if (!shx.is_open()) { std::clog << "Error : cannot open " << shxname << std::endl; continue; } int code = shx.read_xdr_integer(); //file_code == 9994 std::clog << code << std::endl; shx.skip(5*4); int file_length=shx.read_xdr_integer(); int version=shx.read_ndr_integer(); int shape_type=shx.read_ndr_integer(); box2d<double> extent; shx.read_envelope(extent); std::clog << "length=" << file_length << std::endl; std::clog << "version=" << version << std::endl; std::clog << "type=" << shape_type << std::endl; std::clog << "extent:" << extent << std::endl; int pos = 50; shx.seek(pos * 2); mapnik::quad_tree<int> tree(extent, depth, ratio); int count = 0; while (shx.is_good() && pos <= file_length + 4) { int offset = shx.read_xdr_integer(); int content_length = shx.read_xdr_integer(); pos += 4; box2d<double> item_ext; shp.seek(offset * 2); int record_number = shp.read_xdr_integer(); if (content_length != shp.read_xdr_integer()) { std::clog << "Content length mismatch for record number " << record_number << std::endl; continue; } shape_type = shp.read_ndr_integer(); if (shape_type==shape_io::shape_point || shape_type==shape_io::shape_pointm || shape_type == shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); } if (verbose) { std::clog << "record number " << record_number << " box=" << item_ext << std::endl; } if (item_ext.valid()) { tree.insert(offset * 2,item_ext); ++count; } } if (count > 0) { std::clog << " number shapes=" << count << std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << std::endl; } else { tree.trim(); std::clog << " number nodes=" << tree.count() << std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } else { std::clog << "No non-empty geometries in shapefile" << std::endl; } } std::clog << "done!" << std::endl; return 0; }
move loop terminatiion condition to the top and avoid potential infinite loop when `if (content_length != shp.read_xdr_integer())` + Track `empty` shapes and don't create *.index when there is no non-empty geometries (#3184)
move loop terminatiion condition to the top and avoid potential infinite loop when `if (content_length != shp.read_xdr_integer())` + Track `empty` shapes and don't create *.index when there is no non-empty geometries (#3184)
C++
lgpl-2.1
naturalatlas/mapnik,naturalatlas/mapnik,lightmare/mapnik,mapycz/mapnik,mapycz/mapnik,pnorman/mapnik,pnorman/mapnik,zerebubuth/mapnik,mapnik/mapnik,naturalatlas/mapnik,naturalatlas/mapnik,mapycz/mapnik,mapnik/mapnik,CartoDB/mapnik,tomhughes/mapnik,tomhughes/mapnik,CartoDB/mapnik,lightmare/mapnik,CartoDB/mapnik,tomhughes/mapnik,zerebubuth/mapnik,lightmare/mapnik,zerebubuth/mapnik,tomhughes/mapnik,lightmare/mapnik,mapnik/mapnik,pnorman/mapnik,mapnik/mapnik,pnorman/mapnik
4b19bd1b0f5bbe3208a3496690917978815e6424
src/condor_submit.V6/submit_simulate.cpp
src/condor_submit.V6/submit_simulate.cpp
#include "condor_common.h" #include "condor_config.h" #include "condor_debug.h" #include "condor_network.h" #include "spooled_job_files.h" #include "subsystem_info.h" #include "env.h" #include "basename.h" #include "condor_getcwd.h" #include <time.h> #include "write_user_log.h" #include "condor_classad.h" #include "condor_attributes.h" #include "condor_adtypes.h" #include "condor_io.h" #include "condor_distribution.h" #include "condor_ver_info.h" #if !defined(WIN32) #include <pwd.h> #include <sys/stat.h> #else // WINDOWS only #include "store_cred.h" #endif #include "internet.h" #include "my_hostname.h" #include "domain_tools.h" #include "condor_qmgr.h" #include "sig_install.h" #include "access.h" #include "daemon.h" #include "match_prefix.h" #include "extArray.h" #include "MyString.h" #include "string_list.h" #include "which.h" #include "sig_name.h" #include "print_wrapped_text.h" #include "dc_schedd.h" #include "dc_collector.h" #include "my_username.h" #include "globus_utils.h" #include "enum_utils.h" #include "setenv.h" #include "directory.h" #include "filename_tools.h" #include "fs_util.h" #include "dc_transferd.h" #include "condor_ftp.h" #include "condor_crontab.h" #include <scheduler.h> #include "condor_holdcodes.h" #include "condor_url.h" #include "condor_version.h" #include "list.h" #include "condor_vm_universe_types.h" #include "vm_univ_utils.h" #include "condor_md.h" #include "submit_internal.h" #include <algorithm> #include <string> #include <set> //==================================================================================== // functions for a simulate schedd q //==================================================================================== SimScheddQ::SimScheddQ(int starting_cluster) : cluster(starting_cluster) , proc(-1) , close_file_on_disconnect(false) , log_all_communication(false) , fp(NULL) { } SimScheddQ::~SimScheddQ() { if (fp && close_file_on_disconnect) { fclose(fp); } fp = NULL; } bool SimScheddQ::Connect(FILE* _fp, bool close_on_disconnect, bool log_all) { ASSERT(! fp); fp = _fp; close_file_on_disconnect = close_on_disconnect; log_all_communication = log_all; return fp != NULL; } bool SimScheddQ::disconnect(bool /*commit_transaction*/, CondorError & /*errstack*/) { if (fp && close_file_on_disconnect) { fclose(fp); } fp = NULL; return true; } int SimScheddQ::get_NewCluster() { proc = -1; if (log_all_communication) fprintf(fp, "::get_newCluster\n"); return ++cluster; } int SimScheddQ::get_NewProc(int cluster_id) { ASSERT(cluster == cluster_id); if (fp) { if (log_all_communication) fprintf(fp, "::get_newProc\n"); fprintf(fp, "\n"); } return ++proc; } int SimScheddQ::destroy_Cluster(int cluster_id, const char * /*reason*/) { ASSERT(cluster_id == cluster); return 0; } int SimScheddQ::get_Capabilities(ClassAd & caps) { caps.Assign("LateMaterialize", true); return GetScheddCapabilites(0, caps); } // hack for 8.7.8 testing extern int attr_chain_depth; int SimScheddQ::set_Attribute(int cluster_id, int proc_id, const char *attr, const char *value, SetAttributeFlags_t /*flags*/) { ASSERT(cluster_id == cluster); ASSERT(proc_id == proc || proc_id == -1); if (fp) { if (attr_chain_depth) fprintf(fp, "%d", attr_chain_depth - 1); if (log_all_communication) fprintf(fp, "::set(%d,%d) ", cluster_id, proc_id); fprintf(fp, "%s=%s\n", attr, value); } return 0; } int SimScheddQ::set_AttributeInt(int cluster_id, int proc_id, const char *attr, int value, SetAttributeFlags_t /*flags*/) { ASSERT(cluster_id == cluster); ASSERT(proc_id == proc || proc_id == -1); if (fp) { if (log_all_communication) fprintf(fp, "::int(%d,%d) ", cluster_id, proc_id); fprintf(fp, "%s=%d\n", attr, value); } return 0; } int SimScheddQ::set_Factory(int cluster_id, int qnum, const char * filename, const char * text) { ASSERT(cluster_id == cluster); if (fp) { if (log_all_communication) { fprintf(fp, "::setFactory(%d,%d,%s,%s) ", cluster_id, qnum, filename ? filename : "NULL", text ? "<text>" : "NULL"); if (text) { fprintf(fp, "factory_text=%s\n", text); } else if (filename) { fprintf(fp, "factory_file=%s\n", filename); } else { fprintf(fp, "\n"); } } } return 0; } bool SimScheddQ::echo_Itemdata(const char * filename) { echo_itemdata_filepath = filename; return true; } int SimScheddQ::send_Itemdata(int cluster_id, SubmitForeachArgs & o) { ASSERT(cluster_id == cluster); if (fp && ! log_all_communication) { // normally get_NewProc would terminate the previous line, but if we get here // we know that we are doing a DashDryRun and get_NewProc will never be called // and we have just printed Dry-Run jobs(s) without a \n, so print the \n now. fprintf(fp, "\n"); } if (o.items.number() > 0) { if (log_all_communication) { fprintf(fp, "::sendItemdata(%d) %d items", cluster_id, o.items.number()); } if (!echo_itemdata_filepath.empty()) { int fd = safe_open_wrapper_follow(echo_itemdata_filepath.c_str(), O_WRONLY | _O_BINARY | O_CREAT | O_TRUNC | O_APPEND, 0644); if (fd == -1) { fprintf(stderr, "failed to open itemdata echo file %s : error %d - %s\n", echo_itemdata_filepath.c_str(), errno, strerror(errno)); } else { o.foreach_mode = foreach_from; o.items_filename = echo_itemdata_filepath; // read and canonicalize the items and write them in 64k (ish) chunks // because that's what SendMaterializeData does const size_t cbAlloc = 0x10000; unsigned char buf[cbAlloc]; int ix = 0; std::string item; int rval = 0; o.items.rewind(); while (AbstractScheddQ::next_rowdata(&o, item) == 1) { if (item.size() + ix > cbAlloc) { if (ix == 0) { // single item > 64k !!! rval = -1; break; } int wrote = write(fd, buf, ix); if (wrote != ix) { fprintf(stderr, "write failure %d: %s\n", errno, strerror(errno)); } ix = 0; } memcpy(buf + ix, item.data(), item.size()); ix += (int)item.size(); } // write the remainder, if any if ((rval == 0) && ix) { int wrote = write(fd, buf, ix); if (wrote != ix) { fprintf(stderr, "write failure %d: %s\n", errno, strerror(errno)); } } close(fd); } } } return 0; } int SimScheddQ::send_SpoolFileIfNeeded(ClassAd& ad) { if (fp) { fprintf(fp, "::send_SpoolFileIfNeeded\n"); fPrintAd(fp, ad); } return 0; } int SimScheddQ::send_SpoolFile(char const * filename) { if (fp) { fprintf(fp, "::send_SpoolFile: %s\n", filename); } return 0; } int SimScheddQ::send_SpoolFileBytes(char const * filename) { if (fp) { fprintf(fp, "::send_SpoolFileBytes: %s\n", filename); } return 0; }
#include "condor_common.h" #include "condor_config.h" #include "condor_debug.h" #include "condor_network.h" #include "spooled_job_files.h" #include "subsystem_info.h" #include "env.h" #include "basename.h" #include "condor_getcwd.h" #include <time.h> #include "write_user_log.h" #include "condor_classad.h" #include "condor_attributes.h" #include "condor_adtypes.h" #include "condor_io.h" #include "condor_distribution.h" #include "condor_ver_info.h" #if !defined(WIN32) #include <pwd.h> #include <sys/stat.h> #else // WINDOWS only #include "store_cred.h" #endif #include "internet.h" #include "my_hostname.h" #include "domain_tools.h" #include "condor_qmgr.h" #include "sig_install.h" #include "access.h" #include "daemon.h" #include "match_prefix.h" #include "extArray.h" #include "MyString.h" #include "string_list.h" #include "which.h" #include "sig_name.h" #include "print_wrapped_text.h" #include "dc_schedd.h" #include "dc_collector.h" #include "my_username.h" #include "globus_utils.h" #include "enum_utils.h" #include "setenv.h" #include "directory.h" #include "filename_tools.h" #include "fs_util.h" #include "dc_transferd.h" #include "condor_ftp.h" #include "condor_crontab.h" #include <scheduler.h> #include "condor_holdcodes.h" #include "condor_url.h" #include "condor_version.h" #include "list.h" #include "condor_vm_universe_types.h" #include "vm_univ_utils.h" #include "condor_md.h" #include "submit_internal.h" #include <algorithm> #include <string> #include <set> //==================================================================================== // functions for a simulate schedd q //==================================================================================== SimScheddQ::SimScheddQ(int starting_cluster) : cluster(starting_cluster) , proc(-1) , close_file_on_disconnect(false) , log_all_communication(false) , fp(NULL) { } SimScheddQ::~SimScheddQ() { if (fp && close_file_on_disconnect) { fclose(fp); } fp = NULL; } bool SimScheddQ::Connect(FILE* _fp, bool close_on_disconnect, bool log_all) { ASSERT(! fp); fp = _fp; close_file_on_disconnect = close_on_disconnect; log_all_communication = log_all; return fp != NULL; } bool SimScheddQ::disconnect(bool /*commit_transaction*/, CondorError & /*errstack*/) { if (fp && close_file_on_disconnect) { fclose(fp); } fp = NULL; return true; } int SimScheddQ::get_NewCluster() { proc = -1; if (log_all_communication) fprintf(fp, "::get_newCluster\n"); return ++cluster; } int SimScheddQ::get_NewProc(int cluster_id) { ASSERT(cluster == cluster_id); if (fp) { if (log_all_communication) fprintf(fp, "::get_newProc\n"); fprintf(fp, "\n"); } return ++proc; } int SimScheddQ::destroy_Cluster(int cluster_id, const char * /*reason*/) { ASSERT(cluster_id == cluster); return 0; } int SimScheddQ::get_Capabilities(ClassAd & caps) { caps.Assign("LateMaterialize", true); return GetScheddCapabilites(0, caps); } // hack for 8.7.8 testing extern int attr_chain_depth; int SimScheddQ::set_Attribute(int cluster_id, int proc_id, const char *attr, const char *value, SetAttributeFlags_t /*flags*/) { ASSERT(cluster_id == cluster); ASSERT(proc_id == proc || proc_id == -1); if (fp) { if (attr_chain_depth) fprintf(fp, "%d", attr_chain_depth - 1); if (log_all_communication) fprintf(fp, "::set(%d,%d) ", cluster_id, proc_id); fprintf(fp, "%s=%s\n", attr, value); } return 0; } int SimScheddQ::set_AttributeInt(int cluster_id, int proc_id, const char *attr, int value, SetAttributeFlags_t /*flags*/) { ASSERT(cluster_id == cluster); ASSERT(proc_id == proc || proc_id == -1); if (fp) { if (log_all_communication) fprintf(fp, "::int(%d,%d) ", cluster_id, proc_id); fprintf(fp, "%s=%d\n", attr, value); } return 0; } int SimScheddQ::set_Factory(int cluster_id, int qnum, const char * filename, const char * text) { ASSERT(cluster_id == cluster); if (fp) { if (log_all_communication) { fprintf(fp, "::setFactory(%d,%d,%s,%s) ", cluster_id, qnum, filename ? filename : "NULL", text ? "<text>" : "NULL"); if (text) { fprintf(fp, "factory_text=%s\n", text); } else if (filename) { fprintf(fp, "factory_file=%s\n", filename); } else { fprintf(fp, "\n"); } } } return 0; } bool SimScheddQ::echo_Itemdata(const char * filename) { echo_itemdata_filepath = filename; return true; } int SimScheddQ::send_Itemdata(int cluster_id, SubmitForeachArgs & o) { ASSERT(cluster_id == cluster); if (fp && ! log_all_communication) { // normally get_NewProc would terminate the previous line, but if we get here // we know that we are doing a DashDryRun and get_NewProc will never be called // and we have just printed Dry-Run jobs(s) without a \n, so print the \n now. fprintf(fp, "\n"); } if (o.items.number() > 0) { if (log_all_communication && fp) { fprintf(fp, "::sendItemdata(%d) %d items", cluster_id, o.items.number()); } if (!echo_itemdata_filepath.empty()) { int fd = safe_open_wrapper_follow(echo_itemdata_filepath.c_str(), O_WRONLY | _O_BINARY | O_CREAT | O_TRUNC | O_APPEND, 0644); if (fd == -1) { fprintf(stderr, "failed to open itemdata echo file %s : error %d - %s\n", echo_itemdata_filepath.c_str(), errno, strerror(errno)); } else { o.foreach_mode = foreach_from; o.items_filename = echo_itemdata_filepath; // read and canonicalize the items and write them in 64k (ish) chunks // because that's what SendMaterializeData does const size_t cbAlloc = 0x10000; unsigned char buf[cbAlloc]; int ix = 0; std::string item; int rval = 0; o.items.rewind(); while (AbstractScheddQ::next_rowdata(&o, item) == 1) { if (item.size() + ix > cbAlloc) { if (ix == 0) { // single item > 64k !!! rval = -1; break; } int wrote = write(fd, buf, ix); if (wrote != ix) { fprintf(stderr, "write failure %d: %s\n", errno, strerror(errno)); } ix = 0; } memcpy(buf + ix, item.data(), item.size()); ix += (int)item.size(); } // write the remainder, if any if ((rval == 0) && ix) { int wrote = write(fd, buf, ix); if (wrote != ix) { fprintf(stderr, "write failure %d: %s\n", errno, strerror(errno)); } } close(fd); } } } return 0; } int SimScheddQ::send_SpoolFileIfNeeded(ClassAd& ad) { if (fp) { fprintf(fp, "::send_SpoolFileIfNeeded\n"); fPrintAd(fp, ad); } return 0; } int SimScheddQ::send_SpoolFile(char const * filename) { if (fp) { fprintf(fp, "::send_SpoolFile: %s\n", filename); } return 0; } int SimScheddQ::send_SpoolFileBytes(char const * filename) { if (fp) { fprintf(fp, "::send_SpoolFileBytes: %s\n", filename); } return 0; }
Check for null ptr before deref #6992
Check for null ptr before deref #6992
C++
apache-2.0
htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor
011791b4c6793b8bb04698cebc33a550d16ae72a
src/cpp/core/system/PosixSystemTests.cpp
src/cpp/core/system/PosixSystemTests.cpp
/* * PosixSystemTests.cpp * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef _WIN32 #include <core/system/PosixSystem.hpp> #include <signal.h> #include <tests/TestThat.hpp> namespace rstudio { namespace core { namespace system { namespace tests { context("PosixSystemTests") { test_that("No subprocess detected correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocesses(pid)); expect_true(::kill(pid, SIGKILL) == 0); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocesses(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("No subprocess detected correctly with pgrep method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesViaPgrep(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with pgrep method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesViaPgrep(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #ifdef __APPLE__ // Mac-specific subprocess detection test_that("No subprocess detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesMac(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesMac(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess list correctly empty with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess std::vector<SubprocInfo> children = getSubprocessesMac(pid); expect_true(children.empty()); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess count and pid detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess std::vector<SubprocInfo> children = getSubprocessesMac(getpid()); expect_true(children.size() == 1); expect_true(children.at(0).pid == pid); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess name detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); std::string exe = "sleep"; if (pid == 0) { execlp(exe.c_str(), exe.c_str(), "100", NULL); expect_true(false); // shouldn't get here! } else { // we now have a subprocess, need a slight pause to allow system tables to // catch up ::sleep(1); std::vector<SubprocInfo> children = getSubprocessesMac(getpid()); expect_true(children.size() == 1); if (children.size() == 1) expect_true(children[0].exe.compare(exe) == 0); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // __APPLE__ #ifdef HAVE_PROCSELF test_that("No subprocess detected correctly with procfs method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesViaProcFs(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with procfs method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesViaProcFs(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // HAVE_PROCSELF test_that("Empty list of subprocesses returned correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess std::vector<SubprocInfo> children = getSubprocesses(pid); expect_true(children.empty()); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Current working directory determined correctly with generic method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDir(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Current working directory determined correctly with lsof method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDirViaLsof(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #ifdef HAVE_PROCSELF test_that("Current working directory determined correctly with procfs method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDirViaProcFs(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // HAVE_PROCSELF } } // end namespace tests } // end namespace system } // end namespace core } // end namespace rstudio #endif // !_WIN32
/* * PosixSystemTests.cpp * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef _WIN32 #include <core/system/PosixSystem.hpp> #include <signal.h> #include <sys/wait.h> #include <tests/TestThat.hpp> namespace rstudio { namespace core { namespace system { namespace tests { context("PosixSystemTests") { test_that("No subprocess detected correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocesses(pid)); expect_true(::kill(pid, SIGKILL) == 0); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocesses(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("No subprocess detected correctly with pgrep method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesViaPgrep(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with pgrep method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesViaPgrep(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #ifdef __APPLE__ // Mac-specific subprocess detection test_that("No subprocess detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesMac(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesMac(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess list correctly empty with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess std::vector<SubprocInfo> children = getSubprocessesMac(pid); expect_true(children.empty()); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess count and pid detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess std::vector<SubprocInfo> children = getSubprocessesMac(getpid()); expect_true(children.size() == 1); expect_true(children.at(0).pid == pid); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess name detected correctly with Mac method") { pid_t pid = fork(); expect_false(pid == -1); std::string exe = "sleep"; if (pid == 0) { execlp(exe.c_str(), exe.c_str(), "100", NULL); expect_true(false); // shouldn't get here! } else { // we now have a subprocess, need a slight pause to allow system tables to // catch up ::sleep(1); std::vector<SubprocInfo> children = getSubprocessesMac(getpid()); expect_true(children.size() == 1); if (children.size() == 1) expect_true(children[0].exe.compare(exe) == 0); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // __APPLE__ #ifdef HAVE_PROCSELF test_that("No subprocess detected correctly with procfs method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess expect_false(hasSubprocessesViaProcFs(pid)); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Subprocess detected correctly with procfs method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess expect_true(hasSubprocessesViaProcFs(getpid())); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // HAVE_PROCSELF test_that("Empty list of subprocesses returned correctly with generic method") { pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // process we started doesn't have a subprocess std::vector<SubprocInfo> children = getSubprocesses(pid); expect_true(children.empty()); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Current working directory determined correctly with generic method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDir(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } test_that("Current working directory determined correctly with lsof method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDirViaLsof(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #ifdef HAVE_PROCSELF test_that("Current working directory determined correctly with procfs method") { FilePath emptyPath; FilePath startingDir = FilePath::safeCurrentPath(emptyPath); pid_t pid = fork(); expect_false(pid == -1); if (pid == 0) { ::sleep(1); _exit(0); } else { // we now have a subprocess FilePath cwd = currentWorkingDirViaProcFs(pid); expect_false(cwd.empty()); expect_true(cwd.exists()); expect_true(startingDir == cwd); ::kill(pid, SIGKILL); ::waitpid(pid, NULL, 0); } } #endif // HAVE_PROCSELF } } // end namespace tests } // end namespace system } // end namespace core } // end namespace rstudio #endif // !_WIN32
Fix linux build
Fix linux build
C++
agpl-3.0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
51f6afe5709ee4e7a5c5d37bd2a9a53bfffa774b
src/demos/fea/demo_FEAelectrostatics.cpp
src/demos/fea/demo_FEAelectrostatics.cpp
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code about // // - FEA visualization using Irrlicht // Include some headers used by this tutorial... #include "chrono/physics/ChSystem.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono_fea/ChElementSpring.h" #include "chrono_fea/ChElementBar.h" #include "chrono_fea/ChElementTetra_4.h" #include "chrono_fea/ChElementTetra_10.h" #include "chrono_fea/ChElementHexa_8.h" #include "chrono_fea/ChElementHexa_20.h" #include "chrono_fea/ChContinuumElectrostatics.h" #include "chrono_fea/ChNodeFEAxyzP.h" #include "chrono_fea/ChMesh.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChVisualizationFEAmesh.h" #include "chrono_irrlicht/ChIrrApp.h" // Remember to use the namespace 'chrono' because all classes // of Chrono::Engine belong to this namespace and its children... using namespace chrono; using namespace fea; using namespace irr; int main(int argc, char* argv[]) { // Create a Chrono::Engine physical system ChSystem my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"FEM electrostatics", core::dimension2d<u32>(800, 600), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(core::vector3df(20, 20, 20), core::vector3df(-20, 20, -20), 90, 90, irr::video::SColorf(0.5, 0.5, 0.5)); application.AddTypicalCamera(core::vector3df(0.f, 0.2f, -0.3f), core::vector3df(0.0f, 0.0f, 0.0f)); // Create a mesh, that is a container for groups // of elements and their referenced nodes. ChSharedPtr<ChMesh> my_mesh(new ChMesh); // Create a material, that must be assigned to each element, // and set its parameters ChSharedPtr<ChContinuumElectrostatics> mmaterial(new ChContinuumElectrostatics); mmaterial->SetPermittivity(1); // mmaterial->SetRelativePermettivity(1000.01); // // Add some TETAHEDRONS: // // Load a .node file and a .ele file from disk, defining a complicate tetahedron mesh. // This is much easier than creating all nodes and elements via C++ programming. // You can generate these files using the TetGen tool. std::vector<std::vector<ChSharedPtr<ChNodeFEAbase> > > node_sets; try { my_mesh->LoadFromAbaqusFile(GetChronoDataFile("fea/electrostatics.INP").c_str(), mmaterial, node_sets); } catch (ChException myerr) { GetLog() << myerr.what(); return 0; } // // Set some BOUNDARY CONDITIONS on nodes: // // Impose potential on all nodes of 1st nodeset (see *NSET section in .imp file) int nboundary = 0; for (unsigned int inode = 0; inode < node_sets[nboundary].size(); ++inode) { if (node_sets[nboundary][inode].IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(node_sets[nboundary][inode].DynamicCastTo<ChNodeFEAxyzP>()); // downcast mnode->SetFixed(true); mnode->SetP(0); // field: potential [V] } } // Impose potential on all nodes of 2nd nodeset (see *NSET section in .imp file) nboundary = 1; for (unsigned int inode = 0; inode < node_sets[nboundary].size(); ++inode) { if (node_sets[nboundary][inode].IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(node_sets[nboundary][inode].DynamicCastTo<ChNodeFEAxyzP>()); // downcast mnode->SetFixed(true); mnode->SetP(21); // field: potential [V] } } // This is necessary in order to precompute the // stiffness matrices for all inserted elements in mesh my_mesh->SetupInitial(); // Remember to add the mesh to the system! my_system.Add(my_mesh); // ==Asset== attach a visualization of the FEM mesh. // This will automatically update a triangle mesh (a ChTriangleMeshShape // asset that is internally managed) by setting proper // coordinates and vertex colours as in the FEM elements. // Such triangle mesh can be rendered by Irrlicht or POVray or whatever // postprocessor that can handle a coloured ChTriangleMeshShape). // Do not forget AddAsset() at the end! // This will paint the colored mesh with temperature scale (E_PLOT_NODE_P is the scalar field of the Poisson // problem) ChSharedPtr<ChVisualizationFEAmesh> mvisualizemesh(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemesh->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NODE_P); // plot V, potential field mvisualizemesh->SetColorscaleMinMax(-0.1, 24); my_mesh->AddAsset(mvisualizemesh); // This will paint the wireframe ChSharedPtr<ChVisualizationFEAmesh> mvisualizemeshB(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemeshB->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_SURFACE); mvisualizemeshB->SetColorscaleMinMax(-0.1, 24); mvisualizemeshB->SetWireframe(true); my_mesh->AddAsset(mvisualizemeshB); // This will paint the E vector field as line vectors ChSharedPtr<ChVisualizationFEAmesh> mvisualizemeshC(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemeshC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE); mvisualizemeshC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_ELEM_VECT_DP); mvisualizemeshC->SetSymbolsScale(0.00002); mvisualizemeshC->SetDefaultSymbolsColor(ChColor(1.0f, 1.0f, 0.4f)); mvisualizemeshC->SetZbufferHide(false); my_mesh->AddAsset(mvisualizemeshC); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. // If you need a finer control on which item really needs a visualization proxy in // Irrlicht, just use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! application.AssetUpdateAll(); // // THE SOFT-REAL-TIME CYCLE // my_system.SetLcpSolverType( ChSystem::LCP_ITERATIVE_MINRES); // <- NEEDED because other solvers can't handle stiffness matrices my_system.SetIterLCPwarmStarting(false); // this helps a lot to speedup convergence in this class of problems my_system.SetIterLCPmaxItersSpeed(538); chrono::ChLcpIterativeMINRES* msolver = (chrono::ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed(); msolver->SetRelTolerance(1e-20); msolver->SetTolerance(1e-20); msolver->SetVerbose(true); msolver->SetDiagonalPreconditioning(true); my_system.SetTolForce(1e-20); my_system.SetParallelThreadNumber(1); // Note: if you are interested only in a single LINEAR STATIC solution // (not a transient thermal solution, but rather the steady-state solution), // at this point you can do: my_system.DoStaticLinear(); // Also, in the following while() loop, remove application.DoStep(); // so the loop is used just to keep the 3D view alive, to spin & look at the solution. application.SetTimestep(0.01); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.EndScene(); } // Print some node potentials V.. for (unsigned int inode = 0; inode < my_mesh->GetNnodes(); ++inode) { if (my_mesh->GetNode(inode).IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(my_mesh->GetNode(inode).DynamicCastTo<ChNodeFEAxyzP>()); // downcast if (mnode->GetP() < 6.2) { // GetLog() << "Node at y=" << mnode->GetPos().y << " has V=" << mnode->GetP() << "\n"; } } } return 0; }
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code about // // - FEA visualization using Irrlicht // Include some headers used by this tutorial... #include "chrono/physics/ChSystem.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono_fea/ChElementSpring.h" #include "chrono_fea/ChElementBar.h" #include "chrono_fea/ChElementTetra_4.h" #include "chrono_fea/ChElementTetra_10.h" #include "chrono_fea/ChElementHexa_8.h" #include "chrono_fea/ChElementHexa_20.h" #include "chrono_fea/ChContinuumElectrostatics.h" #include "chrono_fea/ChNodeFEAxyzP.h" #include "chrono_fea/ChMesh.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChVisualizationFEAmesh.h" #include "chrono_irrlicht/ChIrrApp.h" // Remember to use the namespace 'chrono' because all classes // of Chrono::Engine belong to this namespace and its children... using namespace chrono; using namespace fea; using namespace irr; int main(int argc, char* argv[]) { // Create a Chrono::Engine physical system ChSystem my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"FEM electrostatics", core::dimension2d<u32>(800, 600), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(core::vector3df(20, 20, 20), core::vector3df(-20, 20, -20), 90, 90, irr::video::SColorf(0.5, 0.5, 0.5)); application.AddTypicalCamera(core::vector3df(0.f, 0.2f, -0.3f), core::vector3df(0.0f, 0.0f, 0.0f)); // Create a mesh, that is a container for groups // of elements and their referenced nodes. ChSharedPtr<ChMesh> my_mesh(new ChMesh); // Create a material, that must be assigned to each element, // and set its parameters ChSharedPtr<ChContinuumElectrostatics> mmaterial(new ChContinuumElectrostatics); mmaterial->SetPermittivity(1); // mmaterial->SetRelativePermettivity(1000.01); // // Add some TETAHEDRONS: // // Load an Abaqus .INP tetahedron mesh file from disk, defining a complicate tetahedron mesh. // This is much easier than creating all nodes and elements via C++ programming. // Ex. you can generate these .INP files using Abaqus or exporting from SolidWorks simulation. std::vector<std::vector<ChSharedPtr<ChNodeFEAbase> > > node_sets; try { my_mesh->LoadFromAbaqusFile(GetChronoDataFile("fea/electrostatics.INP").c_str(), mmaterial, node_sets); } catch (ChException myerr) { GetLog() << myerr.what(); return 0; } // // Set some BOUNDARY CONDITIONS on nodes: // // Impose potential on all nodes of 1st nodeset (see *NSET section in .imp file) int nboundary = 0; for (unsigned int inode = 0; inode < node_sets[nboundary].size(); ++inode) { if (node_sets[nboundary][inode].IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(node_sets[nboundary][inode].DynamicCastTo<ChNodeFEAxyzP>()); // downcast mnode->SetFixed(true); mnode->SetP(0); // field: potential [V] } } // Impose potential on all nodes of 2nd nodeset (see *NSET section in .imp file) nboundary = 1; for (unsigned int inode = 0; inode < node_sets[nboundary].size(); ++inode) { if (node_sets[nboundary][inode].IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(node_sets[nboundary][inode].DynamicCastTo<ChNodeFEAxyzP>()); // downcast mnode->SetFixed(true); mnode->SetP(21); // field: potential [V] } } // This is necessary in order to precompute the // stiffness matrices for all inserted elements in mesh my_mesh->SetupInitial(); // Remember to add the mesh to the system! my_system.Add(my_mesh); // ==Asset== attach a visualization of the FEM mesh. // This will automatically update a triangle mesh (a ChTriangleMeshShape // asset that is internally managed) by setting proper // coordinates and vertex colours as in the FEM elements. // Such triangle mesh can be rendered by Irrlicht or POVray or whatever // postprocessor that can handle a coloured ChTriangleMeshShape). // Do not forget AddAsset() at the end! // This will paint the colored mesh with temperature scale (E_PLOT_NODE_P is the scalar field of the Poisson // problem) ChSharedPtr<ChVisualizationFEAmesh> mvisualizemesh(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemesh->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NODE_P); // plot V, potential field mvisualizemesh->SetColorscaleMinMax(-0.1, 24); my_mesh->AddAsset(mvisualizemesh); // This will paint the wireframe ChSharedPtr<ChVisualizationFEAmesh> mvisualizemeshB(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemeshB->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_SURFACE); mvisualizemeshB->SetColorscaleMinMax(-0.1, 24); mvisualizemeshB->SetWireframe(true); my_mesh->AddAsset(mvisualizemeshB); // This will paint the E vector field as line vectors ChSharedPtr<ChVisualizationFEAmesh> mvisualizemeshC(new ChVisualizationFEAmesh(*(my_mesh.get_ptr()))); mvisualizemeshC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE); mvisualizemeshC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_ELEM_VECT_DP); mvisualizemeshC->SetSymbolsScale(0.00002); mvisualizemeshC->SetDefaultSymbolsColor(ChColor(1.0f, 1.0f, 0.4f)); mvisualizemeshC->SetZbufferHide(false); my_mesh->AddAsset(mvisualizemeshC); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. // If you need a finer control on which item really needs a visualization proxy in // Irrlicht, just use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! application.AssetUpdateAll(); // // THE SOFT-REAL-TIME CYCLE // my_system.SetLcpSolverType( ChSystem::LCP_ITERATIVE_MINRES); // <- NEEDED because other solvers can't handle stiffness matrices my_system.SetIterLCPwarmStarting(false); // this helps a lot to speedup convergence in this class of problems my_system.SetIterLCPmaxItersSpeed(538); chrono::ChLcpIterativeMINRES* msolver = (chrono::ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed(); msolver->SetRelTolerance(1e-20); msolver->SetTolerance(1e-20); msolver->SetVerbose(true); msolver->SetDiagonalPreconditioning(true); my_system.SetTolForce(1e-20); my_system.SetParallelThreadNumber(1); // Note: if you are interested only in a single LINEAR STATIC solution // (not a transient thermal solution, but rather the steady-state solution), // at this point you can do: my_system.DoStaticLinear(); // Also, in the following while() loop, remove application.DoStep(); // so the loop is used just to keep the 3D view alive, to spin & look at the solution. application.SetTimestep(0.01); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.EndScene(); } // Print some node potentials V.. for (unsigned int inode = 0; inode < my_mesh->GetNnodes(); ++inode) { if (my_mesh->GetNode(inode).IsType<ChNodeFEAxyzP>()) { ChSharedPtr<ChNodeFEAxyzP> mnode(my_mesh->GetNode(inode).DynamicCastTo<ChNodeFEAxyzP>()); // downcast if (mnode->GetP() < 6.2) { // GetLog() << "Node at y=" << mnode->GetPos().y << " has V=" << mnode->GetP() << "\n"; } } } return 0; }
Fix comments.
Fix comments.
C++
bsd-3-clause
armanpazouki/chrono,Bryan-Peterson/chrono,andrewseidl/chrono,Bryan-Peterson/chrono,projectchrono/chrono,rserban/chrono,Milad-Rakhsha/chrono,andrewseidl/chrono,armanpazouki/chrono,projectchrono/chrono,rserban/chrono,amelmquist/chrono,jcmadsen/chrono,tjolsen/chrono,tjolsen/chrono,amelmquist/chrono,armanpazouki/chrono,rserban/chrono,andrewseidl/chrono,jcmadsen/chrono,Bryan-Peterson/chrono,dariomangoni/chrono,amelmquist/chrono,dariomangoni/chrono,jcmadsen/chrono,dariomangoni/chrono,tjolsen/chrono,tjolsen/chrono,projectchrono/chrono,tjolsen/chrono,Milad-Rakhsha/chrono,jcmadsen/chrono,dariomangoni/chrono,Bryan-Peterson/chrono,armanpazouki/chrono,projectchrono/chrono,rserban/chrono,dariomangoni/chrono,andrewseidl/chrono,jcmadsen/chrono,Milad-Rakhsha/chrono,Milad-Rakhsha/chrono,projectchrono/chrono,amelmquist/chrono,Bryan-Peterson/chrono,armanpazouki/chrono,projectchrono/chrono,andrewseidl/chrono,amelmquist/chrono,rserban/chrono,armanpazouki/chrono,Milad-Rakhsha/chrono,jcmadsen/chrono,Milad-Rakhsha/chrono,dariomangoni/chrono,amelmquist/chrono,jcmadsen/chrono,rserban/chrono,rserban/chrono
4727ac8b443aa0814ebf081233231e1701b4bd14
platform/shared/rubyext/System.cpp
platform/shared/rubyext/System.cpp
#include "common/RhoPort.h" #include "ruby/ext/rho/rhoruby.h" #include "sync/ClientRegister.h" #include "common/RhodesApp.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "RhoSystem" extern "C" { extern int rho_sysimpl_get_property(char* szPropName, VALUE* resValue); extern VALUE rho_sys_has_network(); extern VALUE rho_sys_get_locale(); extern int rho_sys_get_screen_width(); extern int rho_sys_get_screen_height(); VALUE rho_sys_get_property(char* szPropName) { if (!szPropName || !*szPropName) return rho_ruby_get_NIL(); VALUE res; if (rho_sysimpl_get_property(szPropName, &res)) return res; if (strcasecmp("platform",szPropName) == 0) return rho_ruby_create_string(rho_rhodesapp_getplatform()); if (strcasecmp("has_network",szPropName) == 0) return rho_sys_has_network(); if (strcasecmp("locale",szPropName) == 0) return rho_sys_get_locale(); if (strcasecmp("screen_width",szPropName) == 0) return rho_ruby_create_integer(rho_sys_get_screen_width()); if (strcasecmp("screen_height",szPropName) == 0) return rho_ruby_create_integer(rho_sys_get_screen_height()); if (strcasecmp("device_id",szPropName) == 0) { rho::String strDeviceID = ""; if ( rho::sync::CClientRegister::getInstance() ) strDeviceID = rho::sync::CClientRegister::getInstance()->getDevicePin(); return rho_ruby_create_string(strDeviceID.c_str()); } if (strcasecmp("full_browser",szPropName) == 0) return rho_ruby_create_boolean(1); if (strcasecmp("rhodes_port",szPropName) == 0) return rho_ruby_create_integer(atoi(RHODESAPP().getFreeListeningPort())); if (strcasecmp("is_emulator",szPropName) == 0) return rho_ruby_create_boolean(0); if (strcasecmp("has_touchscreen",szPropName) == 0) return rho_ruby_create_boolean(1); RAWLOG_ERROR1("Unknown Rho::System property : %s", szPropName); return rho_ruby_get_NIL(); } void rho_sys_set_push_notification(const char *url, const char* params) { RHODESAPP().setPushNotification(url, params); } void rho_sys_set_screen_rotation_notification(const char *url, const char* params) { RHODESAPP().setScreenRotationNotification(url, params); } void rho_sys_unzip_file(const char *url) { rho_unzip_file(url); } #if defined(OS_MACOSX) || defined(OS_ANDROID) // implemented in platform code #else int rho_sys_set_sleeping(int sleeping) { return 1; } #endif //defined(OS_MACOSX) || defined(OS_ANDROID) const char* rho_sys_get_start_params() { return rho::common::CRhodesApp::getStartParameters().c_str(); } } //extern "C"
#include "common/RhoPort.h" #include "ruby/ext/rho/rhoruby.h" #include "sync/ClientRegister.h" #include "common/RhodesApp.h" #include "logging/RhoLog.h" #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "RhoSystem" extern "C" { extern int rho_sysimpl_get_property(char* szPropName, VALUE* resValue); extern VALUE rho_sys_has_network(); extern VALUE rho_sys_get_locale(); extern int rho_sys_get_screen_width(); extern int rho_sys_get_screen_height(); VALUE rho_sys_get_property(char* szPropName) { if (!szPropName || !*szPropName) return rho_ruby_get_NIL(); VALUE res; if (rho_sysimpl_get_property(szPropName, &res)) return res; if (strcasecmp("platform",szPropName) == 0) return rho_ruby_create_string(rho_rhodesapp_getplatform()); if (strcasecmp("has_network",szPropName) == 0) return rho_sys_has_network(); if (strcasecmp("locale",szPropName) == 0) return rho_sys_get_locale(); if (strcasecmp("screen_width",szPropName) == 0) return rho_ruby_create_integer(rho_sys_get_screen_width()); if (strcasecmp("screen_height",szPropName) == 0) return rho_ruby_create_integer(rho_sys_get_screen_height()); if (strcasecmp("device_id",szPropName) == 0) { rho::String strDeviceID = ""; if ( rho::sync::CClientRegister::getInstance() ) strDeviceID = rho::sync::CClientRegister::getInstance()->getDevicePin(); return rho_ruby_create_string(strDeviceID.c_str()); } if (strcasecmp("full_browser",szPropName) == 0) return rho_ruby_create_boolean(1); if (strcasecmp("rhodes_port",szPropName) == 0) return rho_ruby_create_integer(atoi(RHODESAPP().getFreeListeningPort())); if (strcasecmp("is_emulator",szPropName) == 0) return rho_ruby_create_boolean(0); if (strcasecmp("has_touchscreen",szPropName) == 0) return rho_ruby_create_boolean(1); if (strcasecmp("has_sqlite",szPropName) == 0) return rho_ruby_create_boolean(1); RAWLOG_ERROR1("Unknown Rho::System property : %s", szPropName); return rho_ruby_get_NIL(); } void rho_sys_set_push_notification(const char *url, const char* params) { RHODESAPP().setPushNotification(url, params); } void rho_sys_set_screen_rotation_notification(const char *url, const char* params) { RHODESAPP().setScreenRotationNotification(url, params); } void rho_sys_unzip_file(const char *url) { rho_unzip_file(url); } #if defined(OS_MACOSX) || defined(OS_ANDROID) // implemented in platform code #else int rho_sys_set_sleeping(int sleeping) { return 1; } #endif //defined(OS_MACOSX) || defined(OS_ANDROID) const char* rho_sys_get_start_params() { return rho::common::CRhodesApp::getStartParameters().c_str(); } } //extern "C"
add has_sqlite property
add has_sqlite property
C++
mit
tauplatform/tau,rhomobile/rhodes,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,pslgoh/rhodes,pslgoh/rhodes,tauplatform/tau,pslgoh/rhodes,watusi/rhodes,pslgoh/rhodes,pslgoh/rhodes,watusi/rhodes,tauplatform/tau,watusi/rhodes,rhomobile/rhodes,watusi/rhodes,pslgoh/rhodes,tauplatform/tau,watusi/rhodes,rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,watusi/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,watusi/rhodes,pslgoh/rhodes,pslgoh/rhodes,tauplatform/tau,tauplatform/tau,pslgoh/rhodes,pslgoh/rhodes
a2f533454cbedb9b757b291394086e5478d10256
plugin-volume/pulseaudioengine.cpp
plugin-volume/pulseaudioengine.cpp
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudioengine.h" #include "pulseaudiodevice.h" #include <QtDebug> static void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int isLast, void *userdata) { PulseAudioEngine *pulseEngine = static_cast<PulseAudioEngine*>(userdata); QMap<pa_sink_state, QString> stateMap; stateMap[PA_SINK_INVALID_STATE] = "n/a"; stateMap[PA_SINK_RUNNING] = "RUNNING"; stateMap[PA_SINK_IDLE] = "IDLE"; stateMap[PA_SINK_SUSPENDED] = "SUSPENDED"; if (isLast < 0) { qWarning() << QString("Failed to get sink information: %s").arg(pa_strerror(pa_context_errno(context))); return; } if (isLast) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->addSink(info); } static void contextEventCallback(pa_context *context, const char *name, pa_proplist *p, void *userdata) { } static void contextStateCallbackInit(pa_context *context, void *userdata) { Q_UNUSED(context); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextStateCallback(pa_context *context, void *userdata) { Q_UNUSED(userdata); Q_UNUSED(context); } static void contextSuccessCallback(pa_context *context, int success, void *userdata) { Q_UNUSED(context); Q_UNUSED(success); Q_UNUSED(userdata); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSubscriptionCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); foreach (PulseAudioDevice *dev, pulseEngine->sinks()) { if (dev->index == idx) { pulseEngine->requestSinkInfoUpdate(dev); break; } } } PulseAudioEngine::PulseAudioEngine(QObject *parent) : QObject(parent) { bool keepGoing = true; bool ok = true; m_mainLoop = pa_threaded_mainloop_new(); if (m_mainLoop == 0) { qWarning("Unable to create pulseaudio mainloop"); return; } if (pa_threaded_mainloop_start(m_mainLoop) != 0) { qWarning("Unable to start pulseaudio mainloop"); pa_threaded_mainloop_free(m_mainLoop); return; } m_mainLoopApi = pa_threaded_mainloop_get_api(m_mainLoop); pa_threaded_mainloop_lock(m_mainLoop); m_context = pa_context_new(m_mainLoopApi, "razor-volume"); pa_context_set_state_callback(m_context, contextStateCallbackInit, this); pa_context_set_event_callback(m_context, contextEventCallback, this); if (!m_context) { qWarning("Unable to create new pulseaudio context"); pa_threaded_mainloop_free(m_mainLoop); return; } if (pa_context_connect(m_context, NULL, (pa_context_flags_t)0, NULL) < 0) { qWarning("Unable to create a connection to the pulseaudio context"); pa_context_unref(m_context); pa_threaded_mainloop_free(m_mainLoop); return; } pa_threaded_mainloop_wait(m_mainLoop); while (keepGoing) { switch (pa_context_get_state(m_context)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: qWarning("Connection established."); keepGoing = false; break; case PA_CONTEXT_TERMINATED: qCritical("Context terminated."); keepGoing = false; ok = false; break; case PA_CONTEXT_FAILED: default: qCritical() << QString("Connection failure: %1").arg(pa_strerror(pa_context_errno(m_context))); keepGoing = false; ok = false; } if (keepGoing) { pa_threaded_mainloop_wait(m_mainLoop); } } if (ok) { pa_context_set_state_callback(m_context, contextStateCallback, this); } else { if (m_context) { pa_context_unref(m_context); m_context = 0; } } pa_threaded_mainloop_unlock(m_mainLoop); if (ok) { retrieveSinks(); setupSubscription(); } } PulseAudioEngine::~PulseAudioEngine() { } void PulseAudioEngine::addSink(const pa_sink_info *info) { PulseAudioDevice *dev = 0; bool newSink = false; foreach (PulseAudioDevice *device, m_sinks) { if (info->name == device->name) { dev = device; break; } } if (!dev) { dev = new PulseAudioDevice(Sink, this, this); newSink = true; } dev->name = info->name; dev->index = info->index; dev->description = info->description; dev->cvolume = info->volume; dev->setMute(info->mute); pa_volume_t v = pa_cvolume_avg(&(info->volume)); double tmp = (double)v / PA_VOLUME_UI_MAX; qWarning("volume: %d %d %f", v, PA_VOLUME_UI_MAX, tmp); dev->setVolumeNoCommit(pa_sw_volume_to_linear(v)*100.0); if (newSink) { m_sinks.append(dev); emit sinkListChanged(); } } const QList<PulseAudioDevice *> &PulseAudioEngine::sinks() const { return m_sinks; } pa_threaded_mainloop *PulseAudioEngine::mainloop() const { return m_mainLoop; } void PulseAudioEngine::requestSinkInfoUpdate(PulseAudioDevice *device) { emit sinkInfoChanged(device); } void PulseAudioEngine::commitDeviceVolume(PulseAudioDevice *device) { if (!device) return; pa_volume_t v = pa_sw_volume_from_linear(device->volume()/100.0); pa_cvolume *volume = pa_cvolume_set(&(device->cvolume), device->cvolume.channels, v); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; if (device->type() == Sink) operation = pa_context_set_sink_volume_by_index(m_context, device->index, volume, contextSuccessCallback, this); else operation = pa_context_set_source_volume_by_index(m_context, device->index, volume, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinks() { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_list(m_context, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setupSubscription() { connect(this, SIGNAL(sinkInfoChanged(PulseAudioDevice*)), this, SLOT(retrieveSinkInfo(PulseAudioDevice*)), Qt::QueuedConnection); pa_context_set_subscribe_callback(m_context, contextSubscriptionCallback, this); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_subscribe(m_context, PA_SUBSCRIPTION_MASK_SINK, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinkInfo(PulseAudioDevice *device) { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_by_index(m_context, device->index, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::mute(PulseAudioDevice *device) { setMute(device, true); } void PulseAudioEngine::unmute(PulseAudioDevice *device) { setMute(device, false); } void PulseAudioEngine::setMute(PulseAudioDevice *device, bool state) { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_set_sink_mute_by_index(m_context, device->index, state, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); }
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudioengine.h" #include "pulseaudiodevice.h" #include <QtDebug> static void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int isLast, void *userdata) { PulseAudioEngine *pulseEngine = static_cast<PulseAudioEngine*>(userdata); QMap<pa_sink_state, QString> stateMap; stateMap[PA_SINK_INVALID_STATE] = "n/a"; stateMap[PA_SINK_RUNNING] = "RUNNING"; stateMap[PA_SINK_IDLE] = "IDLE"; stateMap[PA_SINK_SUSPENDED] = "SUSPENDED"; if (isLast < 0) { qWarning() << QString("Failed to get sink information: %s").arg(pa_strerror(pa_context_errno(context))); return; } if (isLast) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->addSink(info); } static void contextEventCallback(pa_context *context, const char *name, pa_proplist *p, void *userdata) { } static void contextStateCallbackInit(pa_context *context, void *userdata) { Q_UNUSED(context); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextStateCallback(pa_context *context, void *userdata) { Q_UNUSED(userdata); Q_UNUSED(context); } static void contextSuccessCallback(pa_context *context, int success, void *userdata) { Q_UNUSED(context); Q_UNUSED(success); Q_UNUSED(userdata); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSubscriptionCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); foreach (PulseAudioDevice *dev, pulseEngine->sinks()) { if (dev->index == idx) { pulseEngine->requestSinkInfoUpdate(dev); break; } } } PulseAudioEngine::PulseAudioEngine(QObject *parent) : QObject(parent) { bool keepGoing = true; bool ok = true; m_mainLoop = pa_threaded_mainloop_new(); if (m_mainLoop == 0) { qWarning("Unable to create pulseaudio mainloop"); return; } if (pa_threaded_mainloop_start(m_mainLoop) != 0) { qWarning("Unable to start pulseaudio mainloop"); pa_threaded_mainloop_free(m_mainLoop); return; } m_mainLoopApi = pa_threaded_mainloop_get_api(m_mainLoop); pa_threaded_mainloop_lock(m_mainLoop); m_context = pa_context_new(m_mainLoopApi, "razor-volume"); pa_context_set_state_callback(m_context, contextStateCallbackInit, this); pa_context_set_event_callback(m_context, contextEventCallback, this); if (!m_context) { qWarning("Unable to create new pulseaudio context"); pa_threaded_mainloop_free(m_mainLoop); return; } if (pa_context_connect(m_context, NULL, (pa_context_flags_t)0, NULL) < 0) { qWarning("Unable to create a connection to the pulseaudio context"); pa_context_unref(m_context); pa_threaded_mainloop_free(m_mainLoop); return; } pa_threaded_mainloop_wait(m_mainLoop); while (keepGoing) { switch (pa_context_get_state(m_context)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: qWarning("Connection established."); keepGoing = false; break; case PA_CONTEXT_TERMINATED: qCritical("Context terminated."); keepGoing = false; ok = false; break; case PA_CONTEXT_FAILED: default: qCritical() << QString("Connection failure: %1").arg(pa_strerror(pa_context_errno(m_context))); keepGoing = false; ok = false; } if (keepGoing) { pa_threaded_mainloop_wait(m_mainLoop); } } if (ok) { pa_context_set_state_callback(m_context, contextStateCallback, this); } else { if (m_context) { pa_context_unref(m_context); m_context = 0; } } pa_threaded_mainloop_unlock(m_mainLoop); if (ok) { retrieveSinks(); setupSubscription(); } } PulseAudioEngine::~PulseAudioEngine() { } void PulseAudioEngine::addSink(const pa_sink_info *info) { PulseAudioDevice *dev = 0; bool newSink = false; foreach (PulseAudioDevice *device, m_sinks) { if (info->name == device->name) { dev = device; break; } } if (!dev) { dev = new PulseAudioDevice(Sink, this, this); newSink = true; } dev->name = info->name; dev->index = info->index; dev->description = info->description; dev->cvolume = info->volume; dev->setMute(info->mute); pa_volume_t v = pa_cvolume_avg(&(info->volume)); dev->setVolumeNoCommit(((double)v*100.0) / PA_VOLUME_UI_MAX); if (newSink) { m_sinks.append(dev); emit sinkListChanged(); } } const QList<PulseAudioDevice *> &PulseAudioEngine::sinks() const { return m_sinks; } pa_threaded_mainloop *PulseAudioEngine::mainloop() const { return m_mainLoop; } void PulseAudioEngine::requestSinkInfoUpdate(PulseAudioDevice *device) { emit sinkInfoChanged(device); } void PulseAudioEngine::commitDeviceVolume(PulseAudioDevice *device) { if (!device) return; pa_volume_t v = (device->volume()/100.0) * PA_VOLUME_UI_MAX; pa_cvolume *volume = pa_cvolume_set(&(device->cvolume), device->cvolume.channels, v); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; if (device->type() == Sink) operation = pa_context_set_sink_volume_by_index(m_context, device->index, volume, contextSuccessCallback, this); else operation = pa_context_set_source_volume_by_index(m_context, device->index, volume, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinks() { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_list(m_context, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setupSubscription() { connect(this, SIGNAL(sinkInfoChanged(PulseAudioDevice*)), this, SLOT(retrieveSinkInfo(PulseAudioDevice*)), Qt::QueuedConnection); pa_context_set_subscribe_callback(m_context, contextSubscriptionCallback, this); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_subscribe(m_context, PA_SUBSCRIPTION_MASK_SINK, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinkInfo(PulseAudioDevice *device) { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_by_index(m_context, device->index, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::mute(PulseAudioDevice *device) { setMute(device, true); } void PulseAudioEngine::unmute(PulseAudioDevice *device) { setMute(device, false); } void PulseAudioEngine::setMute(PulseAudioDevice *device, bool state) { pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_set_sink_mute_by_index(m_context, device->index, state, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); }
use full volume range, even over 100%
panel-volume: use full volume range, even over 100%
C++
lgpl-2.1
npmiller/lxqt-panel,rysiowski/lxqt-panel,jeremywh7/lxqt-panel,lxde/lxqt-panel,rbazaud/lxqt-panel,DrTobe/lxqt-panel,Ilya87/lxqt-panel,hagabaka/lxqt-panel,stefonarch/lxqt-panel,ThomasVie/lxqt-panel-de,hagabaka/lxqt-panel,rbazaud/lxqt-panel,cferr/lxqt-panel,pmattern/lxqt-panel,jubalh/lxqt-panel,npmiller/lxqt-panel,cferr/lxqt-panel,Ilya87/lxqt-panel,rysiowski/lxqt-panel,zjes/lxqt-panel,zvacet/lxqt-panel,jubalh/lxqt-panel,jeremywh7/lxqt-panel,zvacet/lxqt-panel,musarder/lxqt-panel,lxde/lxqt-panel,stefonarch/lxqt-panel,pmattern/lxqt-panel,zjes/lxqt-panel,stefonarch/lxqt-panel,ThomasVie/lxqt-panel-de,DrTobe/lxqt-panel,musarder/lxqt-panel
bf3250b2a08d4fa27c408ca8e27fe7dd1a9726fe
source/reflectionzeug/include/reflectionzeug/VectorProperty.hpp
source/reflectionzeug/include/reflectionzeug/VectorProperty.hpp
#pragma once #include <sstream> #include <reflectionzeug/util.h> namespace reflectionzeug { template <typename Type> VectorProperty<Type>::VectorProperty(const std::string & name, const std::vector<Type> & value) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, value) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> VectorProperty<Type>::VectorProperty(const std::string & name, const std::function<std::vector<Type> ()> & getter, const std::function<void(const std::vector<Type> &)> & setter) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, getter, setter) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, const std::vector<Type> & (Object::*getter_pointer)() const, void (Object::*setter_pointer)(const std::vector<Type> &)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, std::vector<Type> (Object::*getter_pointer)() const, void (Object::*setter_pointer)(const std::vector<Type> &)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, std::vector<Type> (Object::*getter_pointer)() const, void (Object::*setter_pointer)(std::vector<Type>)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> std::vector<Type> VectorProperty<Type>::value() const { assert(this->m_value->get().size() == m_fixedSize); return ValueProperty<std::vector<Type>>::value(); } template <typename Type> void VectorProperty<Type>::setValue(const std::vector<Type> & value) { assert(value.size() == m_fixedSize); ValueProperty<std::vector<Type>>::setValue(value); } template <typename Type> unsigned int VectorProperty<Type>::fixedSize() const { return m_fixedSize; } template <typename Type> unsigned int VectorProperty<Type>::columns() const { return m_columns; } template <typename Type> unsigned int VectorProperty<Type>::rows() const { return m_rows; } template <typename Type> void VectorProperty<Type>::setDimensions(unsigned int columns, unsigned int rows) { assert(columns * rows == m_fixedSize); m_columns = columns; m_rows = rows; } template <typename Type> std::string VectorProperty<Type>::toString() const { std::vector<std::string> stringVector; for (const Type & element : this->value()) { stringVector.push_back(elementToString(element)); } return "(" + util::join(stringVector, ", ") + ")"; } template <typename Type> bool VectorProperty<Type>::fromString(const std::string & string) { if (!matchesVectorRegex(string)) return false; std::vector<std::string> values = util::extract(string, elementRegex()); std::vector<Type> vector; for (std::string & value : values) { vector.push_back(elementFromString(value)); } this->setValue(vector); return true; } template <typename Type> bool VectorProperty<Type>::matchesVectorRegex(const std::string & string) { std::stringstream vectorRegexStream; vectorRegexStream << "\\s*\\("; for (int i = 0; i < fixedSize() - 1; i++) { vectorRegexStream << "(" << elementRegex() << ")"; vectorRegexStream << "\\s*,\\s*"; } vectorRegexStream << elementRegex() << "\\)\\s*"; return util::matchesRegex(string, vectorRegexStream.str()); } } // namespace reflectionzeug
#pragma once #include <sstream> #include <reflectionzeug/util.h> namespace reflectionzeug { template <typename Type> VectorProperty<Type>::VectorProperty(const std::string & name, const std::vector<Type> & value) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, value) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> VectorProperty<Type>::VectorProperty(const std::string & name, const std::function<std::vector<Type> ()> & getter, const std::function<void(const std::vector<Type> &)> & setter) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, getter, setter) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, const std::vector<Type> & (Object::*getter_pointer)() const, void (Object::*setter_pointer)(const std::vector<Type> &)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, std::vector<Type> (Object::*getter_pointer)() const, void (Object::*setter_pointer)(const std::vector<Type> &)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> template <class Object> VectorProperty<Type>::VectorProperty(const std::string & name, Object & object, std::vector<Type> (Object::*getter_pointer)() const, void (Object::*setter_pointer)(std::vector<Type>)) : ValuePropertyInterface(name) , ValueProperty<std::vector<Type>>(name, object, getter_pointer, setter_pointer) , m_fixedSize((unsigned int)this->m_value->get().size()) , m_columns(m_fixedSize) , m_rows(1) { assert(m_fixedSize != 0); } template <typename Type> std::vector<Type> VectorProperty<Type>::value() const { assert(this->m_value->get().size() == m_fixedSize); return ValueProperty<std::vector<Type>>::value(); } template <typename Type> void VectorProperty<Type>::setValue(const std::vector<Type> & value) { assert(value.size() == m_fixedSize); ValueProperty<std::vector<Type>>::setValue(value); } template <typename Type> unsigned int VectorProperty<Type>::fixedSize() const { return m_fixedSize; } template <typename Type> unsigned int VectorProperty<Type>::columns() const { return m_columns; } template <typename Type> unsigned int VectorProperty<Type>::rows() const { return m_rows; } template <typename Type> void VectorProperty<Type>::setDimensions(unsigned int columns, unsigned int rows) { assert(columns * rows == m_fixedSize); m_columns = columns; m_rows = rows; } template <typename Type> std::string VectorProperty<Type>::toString() const { std::vector<std::string> stringVector; for (const Type & element : this->value()) { stringVector.push_back(elementToString(element)); } return "(" + util::join(stringVector, ", ") + ")"; } template <typename Type> bool VectorProperty<Type>::fromString(const std::string & string) { if (!matchesVectorRegex(string)) return false; std::vector<std::string> values = util::extract(string, elementRegex()); std::vector<Type> vector; for (std::string & value : values) { vector.push_back(elementFromString(value)); } this->setValue(vector); return true; } template <typename Type> bool VectorProperty<Type>::matchesVectorRegex(const std::string & string) { std::stringstream vectorRegexStream; vectorRegexStream << "\\s*\\("; for (unsigned int i = 0; i < fixedSize() - 1; i++) { vectorRegexStream << "(" << elementRegex() << ")"; vectorRegexStream << "\\s*,\\s*"; } vectorRegexStream << elementRegex() << "\\)\\s*"; return util::matchesRegex(string, vectorRegexStream.str()); } } // namespace reflectionzeug
fix windows warning unsigned / signed mismatch
fix windows warning unsigned / signed mismatch
C++
mit
j-o/libzeug,lanice/libzeug,p-otto/libzeug,j-o/libzeug,lanice/libzeug,kateyy/libzeug,kateyy/libzeug,lanice/libzeug,hpi-r2d2/libzeug,mjendruk/libzeug,lanice/libzeug,hpi-r2d2/libzeug,cginternals/libzeug,p-otto/libzeug,cginternals/libzeug,cginternals/libzeug,j-o/libzeug,simonkrogmann/libzeug,simonkrogmann/libzeug,cginternals/libzeug,mjendruk/libzeug,mjendruk/libzeug,j-o/libzeug,kateyy/libzeug,p-otto/libzeug
35bb15b009ea02d1c56443de15f240e13e1c7637
chrome/browser/sync/engine/process_updates_command.cc
chrome/browser/sync/engine/process_updates_command.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/engine/process_updates_command.h" #include <vector> #include "base/basictypes.h" #include "base/location.h" #include "chrome/browser/sync/engine/syncer.h" #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncer_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" using std::vector; namespace browser_sync { using sessions::SyncSession; using sessions::StatusController; using sessions::UpdateProgress; ProcessUpdatesCommand::ProcessUpdatesCommand() {} ProcessUpdatesCommand::~ProcessUpdatesCommand() {} bool ProcessUpdatesCommand::HasCustomGroupsToChange() const { // TODO(akalin): Set to true. return false; } std::set<ModelSafeGroup> ProcessUpdatesCommand::GetGroupsToChange( const sessions::SyncSession& session) const { return session.GetEnabledGroupsWithVerifiedUpdates(); } bool ProcessUpdatesCommand::ModelNeutralExecuteImpl(SyncSession* session) { const GetUpdatesResponse& updates = session->status_controller().updates_response().get_updates(); const int update_count = updates.entries_size(); // Don't bother processing updates if there were none. return update_count != 0; } void ProcessUpdatesCommand::ModelChangingExecuteImpl(SyncSession* session) { syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) { LOG(ERROR) << "Scoped dir lookup failed!"; return; } const sessions::UpdateProgress* progress = session->status_controller().update_progress(); if (!progress) return; // Nothing to do. syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir); vector<sessions::VerifiedUpdate>::const_iterator it; for (it = progress->VerifiedUpdatesBegin(); it != progress->VerifiedUpdatesEnd(); ++it) { const sync_pb::SyncEntity& update = it->second; if (it->first != VERIFY_SUCCESS && it->first != VERIFY_UNDELETE) continue; switch (ProcessUpdate(dir, update, &trans)) { case SUCCESS_PROCESSED: case SUCCESS_STORED: break; default: NOTREACHED(); break; } } StatusController* status = session->mutable_status_controller(); status->set_num_consecutive_errors(0); status->mutable_update_progress()->ClearVerifiedUpdates(); } namespace { // Returns true if the entry is still ok to process. bool ReverifyEntry(syncable::WriteTransaction* trans, const SyncEntity& entry, syncable::MutableEntry* same_id) { const bool deleted = entry.has_deleted() && entry.deleted(); const bool is_directory = entry.IsFolder(); const syncable::ModelType model_type = entry.GetModelType(); return VERIFY_SUCCESS == SyncerUtil::VerifyUpdateConsistency(trans, entry, same_id, deleted, is_directory, model_type); } } // namespace // Process a single update. Will avoid touching global state. ServerUpdateProcessingResult ProcessUpdatesCommand::ProcessUpdate( const syncable::ScopedDirLookup& dir, const sync_pb::SyncEntity& proto_update, syncable::WriteTransaction* const trans) { const SyncEntity& update = *static_cast<const SyncEntity*>(&proto_update); syncable::Id server_id = update.id(); const std::string name = SyncerProtoUtil::NameFromSyncEntity(update); // Look to see if there's a local item that should recieve this update, // maybe due to a duplicate client tag or a lost commit response. syncable::Id local_id = SyncerUtil::FindLocalIdToUpdate(trans, update); // FindLocalEntryToUpdate has veto power. if (local_id.IsNull()) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } SyncerUtil::CreateNewEntry(trans, local_id); // We take a two step approach. First we store the entries data in the // server fields of a local entry and then move the data to the local fields syncable::MutableEntry target_entry(trans, syncable::GET_BY_ID, local_id); // We need to run the Verify checks again; the world could have changed // since VerifyUpdatesCommand. if (!ReverifyEntry(trans, update, &target_entry)) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } // If we're repurposing an existing local entry with a new server ID, // change the ID now, after we're sure that the update can succeed. if (local_id != server_id) { DCHECK(!update.deleted()); SyncerUtil::ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id); // When IDs change, versions become irrelevant. Forcing BASE_VERSION // to zero would ensure that this update gets applied, but would indicate // creation or undeletion if it were committed that way. Instead, prefer // forcing BASE_VERSION to entry.version() while also forcing // IS_UNAPPLIED_UPDATE to true. If the item is UNSYNCED, it's committable // from the new state; it may commit before the conflict resolver gets // a crack at it. if (target_entry.Get(syncable::IS_UNSYNCED) || target_entry.Get(syncable::BASE_VERSION) > 0) { // If either of these conditions are met, then we can expect valid client // fields for this entry. When BASE_VERSION is positive, consistency is // enforced on the client fields at update-application time. Otherwise, // we leave the BASE_VERSION field alone; it'll get updated the first time // we successfully apply this update. target_entry.Put(syncable::BASE_VERSION, update.version()); } // Force application of this update, no matter what. target_entry.Put(syncable::IS_UNAPPLIED_UPDATE, true); } SyncerUtil::UpdateServerFieldsFromUpdate(&target_entry, update, name); return SUCCESS_PROCESSED; } } // namespace browser_sync
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/engine/process_updates_command.h" #include <vector> #include "base/basictypes.h" #include "base/location.h" #include "chrome/browser/sync/engine/syncer.h" #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncer_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" using std::vector; namespace browser_sync { using sessions::SyncSession; using sessions::StatusController; using sessions::UpdateProgress; ProcessUpdatesCommand::ProcessUpdatesCommand() {} ProcessUpdatesCommand::~ProcessUpdatesCommand() {} bool ProcessUpdatesCommand::HasCustomGroupsToChange() const { return true; } std::set<ModelSafeGroup> ProcessUpdatesCommand::GetGroupsToChange( const sessions::SyncSession& session) const { return session.GetEnabledGroupsWithVerifiedUpdates(); } bool ProcessUpdatesCommand::ModelNeutralExecuteImpl(SyncSession* session) { const GetUpdatesResponse& updates = session->status_controller().updates_response().get_updates(); const int update_count = updates.entries_size(); // Don't bother processing updates if there were none. return update_count != 0; } void ProcessUpdatesCommand::ModelChangingExecuteImpl(SyncSession* session) { syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) { LOG(ERROR) << "Scoped dir lookup failed!"; return; } const sessions::UpdateProgress* progress = session->status_controller().update_progress(); if (!progress) return; // Nothing to do. syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir); vector<sessions::VerifiedUpdate>::const_iterator it; for (it = progress->VerifiedUpdatesBegin(); it != progress->VerifiedUpdatesEnd(); ++it) { const sync_pb::SyncEntity& update = it->second; if (it->first != VERIFY_SUCCESS && it->first != VERIFY_UNDELETE) continue; switch (ProcessUpdate(dir, update, &trans)) { case SUCCESS_PROCESSED: case SUCCESS_STORED: break; default: NOTREACHED(); break; } } StatusController* status = session->mutable_status_controller(); status->set_num_consecutive_errors(0); status->mutable_update_progress()->ClearVerifiedUpdates(); } namespace { // Returns true if the entry is still ok to process. bool ReverifyEntry(syncable::WriteTransaction* trans, const SyncEntity& entry, syncable::MutableEntry* same_id) { const bool deleted = entry.has_deleted() && entry.deleted(); const bool is_directory = entry.IsFolder(); const syncable::ModelType model_type = entry.GetModelType(); return VERIFY_SUCCESS == SyncerUtil::VerifyUpdateConsistency(trans, entry, same_id, deleted, is_directory, model_type); } } // namespace // Process a single update. Will avoid touching global state. ServerUpdateProcessingResult ProcessUpdatesCommand::ProcessUpdate( const syncable::ScopedDirLookup& dir, const sync_pb::SyncEntity& proto_update, syncable::WriteTransaction* const trans) { const SyncEntity& update = *static_cast<const SyncEntity*>(&proto_update); syncable::Id server_id = update.id(); const std::string name = SyncerProtoUtil::NameFromSyncEntity(update); // Look to see if there's a local item that should recieve this update, // maybe due to a duplicate client tag or a lost commit response. syncable::Id local_id = SyncerUtil::FindLocalIdToUpdate(trans, update); // FindLocalEntryToUpdate has veto power. if (local_id.IsNull()) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } SyncerUtil::CreateNewEntry(trans, local_id); // We take a two step approach. First we store the entries data in the // server fields of a local entry and then move the data to the local fields syncable::MutableEntry target_entry(trans, syncable::GET_BY_ID, local_id); // We need to run the Verify checks again; the world could have changed // since VerifyUpdatesCommand. if (!ReverifyEntry(trans, update, &target_entry)) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } // If we're repurposing an existing local entry with a new server ID, // change the ID now, after we're sure that the update can succeed. if (local_id != server_id) { DCHECK(!update.deleted()); SyncerUtil::ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id); // When IDs change, versions become irrelevant. Forcing BASE_VERSION // to zero would ensure that this update gets applied, but would indicate // creation or undeletion if it were committed that way. Instead, prefer // forcing BASE_VERSION to entry.version() while also forcing // IS_UNAPPLIED_UPDATE to true. If the item is UNSYNCED, it's committable // from the new state; it may commit before the conflict resolver gets // a crack at it. if (target_entry.Get(syncable::IS_UNSYNCED) || target_entry.Get(syncable::BASE_VERSION) > 0) { // If either of these conditions are met, then we can expect valid client // fields for this entry. When BASE_VERSION is positive, consistency is // enforced on the client fields at update-application time. Otherwise, // we leave the BASE_VERSION field alone; it'll get updated the first time // we successfully apply this update. target_entry.Put(syncable::BASE_VERSION, update.version()); } // Force application of this update, no matter what. target_entry.Put(syncable::IS_UNAPPLIED_UPDATE, true); } SyncerUtil::UpdateServerFieldsFromUpdate(&target_entry, update, name); return SUCCESS_PROCESSED; } } // namespace browser_sync
Set HasCustomGroupsToChange() to true for ProcessUpdatesCommand
[Sync] Set HasCustomGroupsToChange() to true for ProcessUpdatesCommand Follow-up to 113090 to see which ModelChangingSyncerCommand triggers a perf regression. BUG=97832 TEST= Review URL: http://codereview.chromium.org/8822017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@114090 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium
2c529dad560649b1db62a406f1b876d425c78c19
app/gfx/gl/gl_implementation_mac.cc
app/gfx/gl/gl_implementation_mac.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gfx/gl/gl_bindings.h" #include "app/gfx/gl/gl_implementation.h" #include "base/base_paths.h" #include "base/file_path.h" #include "base/logging.h" #include "base/native_library.h" #include "base/path_service.h" namespace gfx { namespace { const char kOpenGLFrameworkPath[] = "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL"; } // namespace anonymous bool InitializeGLBindings(GLImplementation implementation) { // Prevent reinitialization with a different implementation. Once the gpu // unit tests have initialized with kGLImplementationMock, we don't want to // later switch to another GL implementation. if (GetGLImplementation() != kGLImplementationNone) return true; switch (implementation) { case kGLImplementationOSMesaGL: { FilePath module_path; if (!PathService::Get(base::DIR_MODULE, &module_path)) { LOG(ERROR) << "PathService::Get failed."; return false; } // When using OSMesa, just use OSMesaGetProcAddress to find entry points. base::NativeLibrary library = base::LoadNativeLibrary( module_path.Append("libosmesa.dylib")); if (!library) { DLOG(INFO) << "libosmesa.so not found"; return false; } GLGetProcAddressProc get_proc_address = reinterpret_cast<GLGetProcAddressProc>( base::GetFunctionPointerFromNativeLibrary( library, "OSMesaGetProcAddress")); if (!get_proc_address) { LOG(ERROR) << "OSMesaGetProcAddress not found."; base::UnloadNativeLibrary(library); return false; } SetGLGetProcAddressProc(get_proc_address); AddGLNativeLibrary(library); SetGLImplementation(kGLImplementationOSMesaGL); InitializeGLBindingsGL(); InitializeGLBindingsOSMESA(); break; } case kGLImplementationDesktopGL: { base::NativeLibrary library = base::LoadNativeLibrary( FilePath(kOpenGLFrameworkPath)); if (!library) { LOG(ERROR) << "OpenGL framework not found"; return false; } AddGLNativeLibrary(library); SetGLImplementation(kGLImplementationDesktopGL); InitializeGLBindingsGL(); break; } case kGLImplementationMockGL: { SetGLGetProcAddressProc(GetMockGLProcAddress); SetGLImplementation(kGLImplementationMockGL); InitializeGLBindingsGL(); break; } default: return false; } return true; } } // namespace gfx
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gfx/gl/gl_bindings.h" #include "app/gfx/gl/gl_implementation.h" #include "base/base_paths.h" #include "base/file_path.h" #include "base/logging.h" #include "base/native_library.h" #include "base/path_service.h" namespace gfx { namespace { const char kOpenGLFrameworkPath[] = "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL"; } // namespace anonymous bool InitializeGLBindings(GLImplementation implementation) { // Prevent reinitialization with a different implementation. Once the gpu // unit tests have initialized with kGLImplementationMock, we don't want to // later switch to another GL implementation. if (GetGLImplementation() != kGLImplementationNone) return true; switch (implementation) { case kGLImplementationOSMesaGL: { FilePath module_path; if (!PathService::Get(base::DIR_MODULE, &module_path)) { LOG(ERROR) << "PathService::Get failed."; return false; } // When using OSMesa, just use OSMesaGetProcAddress to find entry points. base::NativeLibrary library = base::LoadNativeLibrary( module_path.Append("osmesa.so")); if (!library) { DLOG(INFO) << "osmesa.so not found"; return false; } GLGetProcAddressProc get_proc_address = reinterpret_cast<GLGetProcAddressProc>( base::GetFunctionPointerFromNativeLibrary( library, "OSMesaGetProcAddress")); if (!get_proc_address) { LOG(ERROR) << "OSMesaGetProcAddress not found."; base::UnloadNativeLibrary(library); return false; } SetGLGetProcAddressProc(get_proc_address); AddGLNativeLibrary(library); SetGLImplementation(kGLImplementationOSMesaGL); InitializeGLBindingsGL(); InitializeGLBindingsOSMESA(); break; } case kGLImplementationDesktopGL: { base::NativeLibrary library = base::LoadNativeLibrary( FilePath(kOpenGLFrameworkPath)); if (!library) { LOG(ERROR) << "OpenGL framework not found"; return false; } AddGLNativeLibrary(library); SetGLImplementation(kGLImplementationDesktopGL); InitializeGLBindingsGL(); break; } case kGLImplementationMockGL: { SetGLGetProcAddressProc(GetMockGLProcAddress); SetGLImplementation(kGLImplementationMockGL); InitializeGLBindingsGL(); break; } default: return false; } return true; } } // namespace gfx
Fix the wrong mesa lib name.
Fix the wrong mesa lib name. Review URL: http://codereview.chromium.org/3596012 git-svn-id: http://src.chromium.org/svn/trunk/src@61902 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 37d52a4c17cad7d6d526933db70bfc661446fa44
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
0227203a229e85f98a491c6b9480c0bc210f1dbb
dispatch/glimports.hpp
dispatch/glimports.hpp
/************************************************************************** * * Copyright 2010 VMware, Inc. * All Rights Reserved. * * 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. * **************************************************************************/ /* * Central place for all GL includes, and respective OS dependent headers. */ #ifndef _GLIMPORTS_HPP_ #define _GLIMPORTS_HPP_ #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif # include <windows.h> #elif defined(__APPLE__) #elif defined(HAVE_X11) # include <X11/Xlib.h> #endif /* !_WIN32 */ #include <GL/gl.h> #include <GL/glext.h> // Windows 8 GL headers define GL_EXT_paletted_texture but not // GL_TEXTURE_INDEX_SIZE_EXT, and due to the way we include DirectX headers, it // ends up taking precedence over the ones we bundle... #if defined(GL_EXT_paletted_texture) && !defined(GL_TEXTURE_INDEX_SIZE_EXT) #define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED #endif // GL_NVX_gpu_memory_info #define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 #define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 #define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 #define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A #define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B #if defined(_WIN32) #include <GL/wglext.h> #ifndef PFD_SUPPORT_DIRECTDRAW #define PFD_SUPPORT_DIRECTDRAW 0x00002000 #endif #ifndef PFD_SUPPORT_COMPOSITION #define PFD_SUPPORT_COMPOSITION 0x00008000 #endif #ifndef WGL_SWAPMULTIPLE_MAX extern "C" typedef struct _WGLSWAP { HDC hdc; UINT uiFlags; } WGLSWAP, *PWGLSWAP, FAR *LPWGLSWAP; #define WGL_SWAPMULTIPLE_MAX 16 #endif /* !WGL_SWAPMULTIPLE_MAX */ #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IPHONE #elif TARGET_OS_MAC #include <AvailabilityMacros.h> /* Silence deprecated OpenGL warnings. */ #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 #include <OpenGL/OpenGLAvailability.h> #undef OPENGL_DEPRECATED #undef OPENGL_DEPRECATED_MSG #define OPENGL_DEPRECATED(from, to) #define OPENGL_DEPRECATED_MSG(from, to, msg) #endif #include <OpenGL/OpenGL.h> #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 #include <OpenGL/CGLIOSurface.h> #include <OpenGL/CGLDevice.h> #else #define kCGLPFAAcceleratedCompute 97 #define kCGLRPAcceleratedCompute 130 typedef void *CGLShareGroupObj; typedef struct __IOSurface *IOSurfaceRef; #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 #define kCGLPFATripleBuffer 3 #define kCGLPFABackingVolatile 77 #define kCGLPFAOpenGLProfile 99 #define kCGLRPVideoMemoryMegabytes 131 #define kCGLRPTextureMemoryMegabytes 132 #define kCGLCECrashOnRemovedFunctions 316 #define kCGLOGLPVersion_Legacy 0x1000 #define kCGLOGLPVersion_3_2_Core 0x3200 #define kCGLOGLPVersion_GL3_Core 0x3200 #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1080 #define kCGLPFASupportsAutomaticGraphicsSwitching 101 #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090 #define kCGLOGLPVersion_GL3_Core 0x3200 #define kCGLOGLPVersion_GL4_Core 0x4100 #define kCGLRPMajorGLVersion 133 #endif extern "C" { // From http://www.opensource.apple.com/source/gdb/gdb-954/libcheckpoint/cpcg.c typedef void * CGSConnectionID; typedef int CGSWindowID; typedef int CGSSurfaceID; CGLError CGLSetSurface(CGLContextObj ctx, CGSConnectionID cid, CGSWindowID wid, CGSSurfaceID sid); CGLError CGLGetSurface(CGLContextObj ctx, CGSConnectionID* cid, CGSWindowID* wid, CGSSurfaceID* sid); CGLError CGLUpdateContext(CGLContextObj ctx); } #endif #else #ifdef HAVE_X11 #include <GL/glx.h> #include <GL/glxext.h> #endif /* Prevent collision with trace::Bool */ #undef Bool #endif #include "eglimports.hpp" #endif /* _GLIMPORTS_HPP_ */
/************************************************************************** * * Copyright 2010 VMware, Inc. * All Rights Reserved. * * 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. * **************************************************************************/ /* * Central place for all GL includes, and respective OS dependent headers. */ #ifndef _GLIMPORTS_HPP_ #define _GLIMPORTS_HPP_ #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif # include <windows.h> #elif defined(__APPLE__) #elif defined(HAVE_X11) # include <X11/Xlib.h> #endif /* !_WIN32 */ #include <GL/gl.h> #include <GL/glext.h> // Windows 8 GL headers define GL_EXT_paletted_texture but not // GL_TEXTURE_INDEX_SIZE_EXT, and due to the way we include DirectX headers, it // ends up taking precedence over the ones we bundle... #if defined(GL_EXT_paletted_texture) && !defined(GL_TEXTURE_INDEX_SIZE_EXT) #define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED #endif // GL_NVX_gpu_memory_info #define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 #define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 #define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 #define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A #define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B #if defined(_WIN32) #include <GL/wglext.h> #ifndef PFD_SUPPORT_DIRECTDRAW #define PFD_SUPPORT_DIRECTDRAW 0x00002000 #endif #ifndef PFD_SUPPORT_COMPOSITION #define PFD_SUPPORT_COMPOSITION 0x00008000 #endif #ifndef WGL_SWAPMULTIPLE_MAX extern "C" typedef struct _WGLSWAP { HDC hdc; UINT uiFlags; } WGLSWAP, *PWGLSWAP, FAR *LPWGLSWAP; #define WGL_SWAPMULTIPLE_MAX 16 #endif /* !WGL_SWAPMULTIPLE_MAX */ #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IPHONE #elif TARGET_OS_MAC #include <AvailabilityMacros.h> /* Silence deprecated OpenGL warnings. */ #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 #include <OpenGL/OpenGLAvailability.h> #undef OPENGL_DEPRECATED #undef OPENGL_DEPRECATED_MSG #define OPENGL_DEPRECATED(from, to) #define OPENGL_DEPRECATED_MSG(from, to, msg) #endif #include <OpenGL/OpenGL.h> #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 #include <OpenGL/CGLIOSurface.h> #include <OpenGL/CGLDevice.h> #else #define kCGLPFAAcceleratedCompute 97 #define kCGLRPAcceleratedCompute 130 typedef void *CGLShareGroupObj; typedef struct __IOSurface *IOSurfaceRef; #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 #define kCGLPFATripleBuffer 3 #define kCGLPFAOpenGLProfile 99 #define kCGLRPVideoMemoryMegabytes 131 #define kCGLRPTextureMemoryMegabytes 132 #define kCGLCECrashOnRemovedFunctions 316 #define kCGLOGLPVersion_Legacy 0x1000 #define kCGLOGLPVersion_3_2_Core 0x3200 #define kCGLOGLPVersion_GL3_Core 0x3200 #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1080 #define kCGLPFABackingVolatile 77 #define kCGLPFASupportsAutomaticGraphicsSwitching 101 #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090 #define kCGLOGLPVersion_GL3_Core 0x3200 #define kCGLOGLPVersion_GL4_Core 0x4100 #define kCGLRPMajorGLVersion 133 #endif extern "C" { // From http://www.opensource.apple.com/source/gdb/gdb-954/libcheckpoint/cpcg.c typedef void * CGSConnectionID; typedef int CGSWindowID; typedef int CGSSurfaceID; CGLError CGLSetSurface(CGLContextObj ctx, CGSConnectionID cid, CGSWindowID wid, CGSSurfaceID sid); CGLError CGLGetSurface(CGLContextObj ctx, CGSConnectionID* cid, CGSWindowID* wid, CGSSurfaceID* sid); CGLError CGLUpdateContext(CGLContextObj ctx); } #endif #else #ifdef HAVE_X11 #include <GL/glx.h> #include <GL/glxext.h> #endif /* Prevent collision with trace::Bool */ #undef Bool #endif #include "eglimports.hpp" #endif /* _GLIMPORTS_HPP_ */
Move kCGLPFABackingVolatile to < 10.8
Move kCGLPFABackingVolatile to < 10.8 kCGLPFABackingVolatile was added in 10.8 not 10.7
C++
mit
surround-io/apitrace,swq0553/apitrace,apitrace/apitrace,schulmar/apitrace,joshua5201/apitrace,trtt/apitrace,tuanthng/apitrace,EoD/apitrace,tuanthng/apitrace,tuanthng/apitrace,surround-io/apitrace,joshua5201/apitrace,apitrace/apitrace,schulmar/apitrace,swq0553/apitrace,surround-io/apitrace,swq0553/apitrace,trtt/apitrace,EoD/apitrace,swq0553/apitrace,surround-io/apitrace,swq0553/apitrace,apitrace/apitrace,apitrace/apitrace,joshua5201/apitrace,schulmar/apitrace,tuanthng/apitrace,EoD/apitrace,tuanthng/apitrace,schulmar/apitrace,trtt/apitrace,trtt/apitrace,joshua5201/apitrace,joshua5201/apitrace,EoD/apitrace,EoD/apitrace,schulmar/apitrace,surround-io/apitrace,trtt/apitrace
6fcd2a15e62c7c3428363dd896b710d0bef4d14b
content/browser/debugger/devtools_manager_unittest.cc
content/browser/debugger/devtools_manager_unittest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/time.h" #include "content/browser/debugger/devtools_manager_impl.h" #include "content/browser/debugger/render_view_devtools_agent_host.h" #include "content/browser/mock_content_browser_client.h" #include "content/browser/renderer_host/test_render_view_host.h" #include "content/browser/tab_contents/test_tab_contents.h" #include "content/common/view_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/devtools_agent_host_registry.h" #include "content/public/browser/devtools_client_host.h" #include "content/public/browser/web_contents_delegate.h" #include "testing/gtest/include/gtest/gtest.h" using base::TimeDelta; using content::DevToolsAgentHost; using content::DevToolsAgentHostRegistry; using content::DevToolsClientHost; using content::DevToolsManager; using content::DevToolsManagerImpl; using content::WebContents; namespace { class TestDevToolsClientHost : public DevToolsClientHost { public: TestDevToolsClientHost() : last_sent_message(NULL), closed_(false) { } virtual ~TestDevToolsClientHost() { EXPECT_TRUE(closed_); } virtual void Close(DevToolsManager* manager) { EXPECT_FALSE(closed_); close_counter++; manager->ClientHostClosing(this); closed_ = true; } virtual void InspectedTabClosing() { FAIL(); } virtual void SetInspectedTabUrl(const std::string& url) { } virtual void DispatchOnInspectorFrontend(const std::string& message) { last_sent_message = &message; } virtual void TabReplaced(WebContents* new_tab) { } static void ResetCounters() { close_counter = 0; } static int close_counter; const std::string* last_sent_message; private: bool closed_; virtual void FrameNavigating(const std::string& url) {} DISALLOW_COPY_AND_ASSIGN(TestDevToolsClientHost); }; int TestDevToolsClientHost::close_counter = 0; class TestWebContentsDelegate : public content::WebContentsDelegate { public: TestWebContentsDelegate() : renderer_unresponsive_received_(false) {} // Notification that the tab is hung. virtual void RendererUnresponsive(WebContents* source) { renderer_unresponsive_received_ = true; } bool renderer_unresponsive_received() const { return renderer_unresponsive_received_; } private: bool renderer_unresponsive_received_; }; class DevToolsManagerTestBrowserClient : public content::MockContentBrowserClient { public: DevToolsManagerTestBrowserClient() { } virtual bool ShouldSwapProcessesForNavigation( const GURL& current_url, const GURL& new_url) OVERRIDE { return true; } private: DISALLOW_COPY_AND_ASSIGN(DevToolsManagerTestBrowserClient); }; } // namespace class DevToolsManagerTest : public RenderViewHostTestHarness { public: DevToolsManagerTest() : RenderViewHostTestHarness() { } protected: virtual void SetUp() OVERRIDE { original_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); RenderViewHostTestHarness::SetUp(); TestDevToolsClientHost::ResetCounters(); } virtual void TearDown() OVERRIDE { RenderViewHostTestHarness::TearDown(); content::GetContentClient()->set_browser(original_browser_client_); } private: content::ContentBrowserClient* original_browser_client_; DevToolsManagerTestBrowserClient browser_client_; }; TEST_F(DevToolsManagerTest, OpenAndManuallyCloseDevToolsClientHost) { DevToolsManagerImpl manager; DevToolsAgentHost* agent = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); DevToolsClientHost* host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(NULL == host); TestDevToolsClientHost client_host; manager.RegisterDevToolsClientHostFor(agent, &client_host); // Test that just registered devtools host is returned. host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(&client_host == host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); // Test that the same devtools host is returned. host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(&client_host == host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); client_host.Close(&manager); EXPECT_EQ(1, TestDevToolsClientHost::close_counter); host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(NULL == host); } TEST_F(DevToolsManagerTest, ForwardMessageToClient) { DevToolsManagerImpl manager; TestDevToolsClientHost client_host; DevToolsAgentHost* agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); manager.RegisterDevToolsClientHostFor(agent_host, &client_host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); std::string m = "test message"; agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); manager.DispatchOnInspectorFrontend(agent_host, m); EXPECT_TRUE(&m == client_host.last_sent_message); client_host.Close(&manager); EXPECT_EQ(1, TestDevToolsClientHost::close_counter); } TEST_F(DevToolsManagerTest, NoUnresponsiveDialogInInspectedTab) { TestRenderViewHost* inspected_rvh = rvh(); inspected_rvh->set_render_view_created(true); EXPECT_FALSE(contents()->GetDelegate()); TestWebContentsDelegate delegate; contents()->SetDelegate(&delegate); TestDevToolsClientHost client_host; DevToolsAgentHost* agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(inspected_rvh); DevToolsManager::GetInstance()-> RegisterDevToolsClientHostFor(agent_host, &client_host); // Start with a short timeout. inspected_rvh->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), 10); MessageLoop::current()->Run(); EXPECT_FALSE(delegate.renderer_unresponsive_received()); // Now close devtools and check that the notification is delivered. client_host.Close(DevToolsManager::GetInstance()); // Start with a short timeout. inspected_rvh->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), 10); MessageLoop::current()->Run(); EXPECT_TRUE(delegate.renderer_unresponsive_received()); contents()->SetDelegate(NULL); } TEST_F(DevToolsManagerTest, ReattachOnCancelPendingNavigation) { contents()->transition_cross_site = true; // Navigate to URL. First URL should use first RenderViewHost. const GURL url("http://www.google.com"); controller().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); contents()->TestDidNavigate(rvh(), 1, url, content::PAGE_TRANSITION_TYPED); EXPECT_FALSE(contents()->cross_navigation_pending()); TestDevToolsClientHost client_host; DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->RegisterDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()), &client_host); // Navigate to new site which should get a new RenderViewHost. const GURL url2("http://www.yahoo.com"); controller().LoadURL( url2, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); EXPECT_TRUE(contents()->cross_navigation_pending()); EXPECT_EQ(&client_host, devtools_manager->GetDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(pending_rvh()))); // Interrupt pending navigation and navigate back to the original site. controller().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); contents()->TestDidNavigate(rvh(), 1, url, content::PAGE_TRANSITION_TYPED); EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(&client_host, devtools_manager->GetDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()))); client_host.Close(DevToolsManager::GetInstance()); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/time.h" #include "content/browser/debugger/devtools_manager_impl.h" #include "content/browser/debugger/render_view_devtools_agent_host.h" #include "content/browser/mock_content_browser_client.h" #include "content/browser/renderer_host/test_render_view_host.h" #include "content/browser/tab_contents/test_tab_contents.h" #include "content/common/view_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/devtools_agent_host_registry.h" #include "content/public/browser/devtools_client_host.h" #include "content/public/browser/web_contents_delegate.h" #include "testing/gtest/include/gtest/gtest.h" using base::TimeDelta; using content::DevToolsAgentHost; using content::DevToolsAgentHostRegistry; using content::DevToolsClientHost; using content::DevToolsManager; using content::DevToolsManagerImpl; using content::WebContents; namespace { class TestDevToolsClientHost : public DevToolsClientHost { public: TestDevToolsClientHost() : last_sent_message(NULL), closed_(false) { } virtual ~TestDevToolsClientHost() { EXPECT_TRUE(closed_); } virtual void Close(DevToolsManager* manager) { EXPECT_FALSE(closed_); close_counter++; manager->ClientHostClosing(this); closed_ = true; } virtual void InspectedTabClosing() { FAIL(); } virtual void SetInspectedTabUrl(const std::string& url) { } virtual void DispatchOnInspectorFrontend(const std::string& message) { last_sent_message = &message; } virtual void TabReplaced(WebContents* new_tab) { } static void ResetCounters() { close_counter = 0; } static int close_counter; const std::string* last_sent_message; private: bool closed_; virtual void FrameNavigating(const std::string& url) {} DISALLOW_COPY_AND_ASSIGN(TestDevToolsClientHost); }; int TestDevToolsClientHost::close_counter = 0; class TestWebContentsDelegate : public content::WebContentsDelegate { public: TestWebContentsDelegate() : renderer_unresponsive_received_(false) {} // Notification that the tab is hung. virtual void RendererUnresponsive(WebContents* source) { renderer_unresponsive_received_ = true; } bool renderer_unresponsive_received() const { return renderer_unresponsive_received_; } private: bool renderer_unresponsive_received_; }; class DevToolsManagerTestBrowserClient : public content::MockContentBrowserClient { public: DevToolsManagerTestBrowserClient() { } virtual bool ShouldSwapProcessesForNavigation( const GURL& current_url, const GURL& new_url) OVERRIDE { return true; } private: DISALLOW_COPY_AND_ASSIGN(DevToolsManagerTestBrowserClient); }; } // namespace class DevToolsManagerTest : public RenderViewHostTestHarness { public: DevToolsManagerTest() : RenderViewHostTestHarness() { } protected: virtual void SetUp() OVERRIDE { original_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); RenderViewHostTestHarness::SetUp(); TestDevToolsClientHost::ResetCounters(); } virtual void TearDown() OVERRIDE { RenderViewHostTestHarness::TearDown(); content::GetContentClient()->set_browser(original_browser_client_); } private: content::ContentBrowserClient* original_browser_client_; DevToolsManagerTestBrowserClient browser_client_; }; TEST_F(DevToolsManagerTest, OpenAndManuallyCloseDevToolsClientHost) { DevToolsManagerImpl manager; DevToolsAgentHost* agent = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); DevToolsClientHost* host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(NULL == host); TestDevToolsClientHost client_host; manager.RegisterDevToolsClientHostFor(agent, &client_host); // Test that just registered devtools host is returned. host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(&client_host == host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); // Test that the same devtools host is returned. host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(&client_host == host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); client_host.Close(&manager); EXPECT_EQ(1, TestDevToolsClientHost::close_counter); host = manager.GetDevToolsClientHostFor(agent); EXPECT_TRUE(NULL == host); } TEST_F(DevToolsManagerTest, ForwardMessageToClient) { DevToolsManagerImpl manager; TestDevToolsClientHost client_host; DevToolsAgentHost* agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); manager.RegisterDevToolsClientHostFor(agent_host, &client_host); EXPECT_EQ(0, TestDevToolsClientHost::close_counter); std::string m = "test message"; agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()); manager.DispatchOnInspectorFrontend(agent_host, m); EXPECT_TRUE(&m == client_host.last_sent_message); client_host.Close(&manager); EXPECT_EQ(1, TestDevToolsClientHost::close_counter); } TEST_F(DevToolsManagerTest, NoUnresponsiveDialogInInspectedTab) { TestRenderViewHost* inspected_rvh = rvh(); inspected_rvh->set_render_view_created(true); EXPECT_FALSE(contents()->GetDelegate()); TestWebContentsDelegate delegate; contents()->SetDelegate(&delegate); TestDevToolsClientHost client_host; DevToolsAgentHost* agent_host = DevToolsAgentHostRegistry::GetDevToolsAgentHost(inspected_rvh); DevToolsManager::GetInstance()-> RegisterDevToolsClientHostFor(agent_host, &client_host); // Start with a short timeout. inspected_rvh->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_FALSE(delegate.renderer_unresponsive_received()); // Now close devtools and check that the notification is delivered. client_host.Close(DevToolsManager::GetInstance()); // Start with a short timeout. inspected_rvh->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_TRUE(delegate.renderer_unresponsive_received()); contents()->SetDelegate(NULL); } TEST_F(DevToolsManagerTest, ReattachOnCancelPendingNavigation) { contents()->transition_cross_site = true; // Navigate to URL. First URL should use first RenderViewHost. const GURL url("http://www.google.com"); controller().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); contents()->TestDidNavigate(rvh(), 1, url, content::PAGE_TRANSITION_TYPED); EXPECT_FALSE(contents()->cross_navigation_pending()); TestDevToolsClientHost client_host; DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->RegisterDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()), &client_host); // Navigate to new site which should get a new RenderViewHost. const GURL url2("http://www.yahoo.com"); controller().LoadURL( url2, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); EXPECT_TRUE(contents()->cross_navigation_pending()); EXPECT_EQ(&client_host, devtools_manager->GetDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(pending_rvh()))); // Interrupt pending navigation and navigate back to the original site. controller().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); contents()->TestDidNavigate(rvh(), 1, url, content::PAGE_TRANSITION_TYPED); EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(&client_host, devtools_manager->GetDevToolsClientHostFor( DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh()))); client_host.Close(DevToolsManager::GetInstance()); }
Convert uses of int ms to TimeDelta in content/browser/debugger.
Convert uses of int ms to TimeDelta in content/browser/debugger. [email protected] BUG=108171 Review URL: http://codereview.chromium.org/9572040 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@124948 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium
950f617328ba8cb9b0bb41a42af43ba72492dfdc
examples/react.cpp
examples/react.cpp
#include <reactive/bridge.hpp> #include <reactive/ptr_observable.hpp> #include <reactive/transform.hpp> #include <reactive/while.hpp> #include <reactive/finite_state_machine.hpp> #include <reactive/filter.hpp> #include <reactive/generate.hpp> #include <reactive/total_consumer.hpp> #include <reactive/cache.hpp> #include <SDL2/SDL.h> #include <boost/scope_exit.hpp> #include <boost/variant.hpp> namespace rx { template <class Element> struct visitor : observer<Element> { boost::optional<Element> result; virtual void got_element(Element value) SILICIUM_OVERRIDE { result = std::move(value); } virtual void ended() SILICIUM_OVERRIDE { } }; template <class Input> auto get(Input &from) { visitor<typename Input::element_type> v; from.async_get_one(v); return std::move(v.result); } template <class Input> auto deref_optional(Input &&input) { typedef boost::optional<typename Input::element_type> optional_type; return transform(while_(std::forward<Input>(input), [](optional_type const &element) { return element.is_initialized(); }), [](optional_type element) { return std::move(*element); }); } } namespace { void throw_error() { throw std::runtime_error(std::string("SDL error :") + SDL_GetError()); } void check_sdl(int rc) { if (rc < 0) { throw_error(); } } struct window_destructor { void operator()(SDL_Window *w) const { SDL_DestroyWindow(w); } }; struct renderer_destructor { void operator()(SDL_Renderer *r) const { SDL_DestroyRenderer(r); } }; void set_render_draw_color(SDL_Renderer &renderer, SDL_Color color) { SDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a); } SDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { SDL_Color result; result.r = red; result.g = green; result.b = blue; result.a = alpha; return result; } SDL_Rect make_rect(int x, int y, int w, int h) { SDL_Rect result; result.x = x; result.y = y; result.w = w; result.h = h; return result; } struct draw_filled_rect { SDL_Color color; SDL_Rect where; }; typedef boost::variant< draw_filled_rect > draw_operation; struct frame { std::vector<draw_operation> operations; }; struct draw_operation_renderer : boost::static_visitor<> { explicit draw_operation_renderer(SDL_Renderer &sdl) : sdl(&sdl) { } void operator()(draw_filled_rect const &operation) const { set_render_draw_color(*sdl, operation.color); SDL_RenderDrawRect(sdl, &operation.where); } private: SDL_Renderer *sdl; }; void render_frame(SDL_Renderer &sdl, frame const &frame_) { set_render_draw_color(sdl, make_color(0, 0, 0, 0xff)); SDL_RenderClear(&sdl); for (auto const &operation : frame_.operations) { boost::apply_visitor(draw_operation_renderer{sdl}, operation); } SDL_RenderPresent(&sdl); } struct game_state { int x = 100; int y = 100; int count = 1; }; int const max_rect_count = 5; frame draw_game_state(game_state const &state) { std::vector<draw_operation> operations; for (int i = 0; i < state.count; ++i) { int const max_width = 80; int const single_offset = (max_width / 2) / max_rect_count; int const total_offset = single_offset * i; int const width = max_width - total_offset * 2; operations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)}); } return frame { std::move(operations) }; } boost::optional<game_state> step_game_state(game_state previous, SDL_Event event_) { switch (event_.type) { case SDL_QUIT: return boost::none; case SDL_KEYUP: { switch (event_.key.keysym.sym) { case SDLK_LEFT: previous.x -= 10; break; case SDLK_RIGHT: previous.x += 10; break; case SDLK_UP: previous.y -= 10; break; case SDLK_DOWN: previous.y += 10; break; case SDLK_PLUS: previous.count = std::min(max_rect_count, previous.count + 1); break; case SDLK_MINUS: previous.count = std::max(1, previous.count - 1); break; case SDLK_ESCAPE: return boost::none; } break; } } return previous; } template <class Events> auto make_frames(Events &&input) { game_state initial_state; auto model = rx::make_finite_state_machine(std::forward<Events>(input), initial_state, step_game_state); return rx::transform(std::move(model), draw_game_state); } } int main() { check_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)); BOOST_SCOPE_EXIT(void) { SDL_Quit(); } BOOST_SCOPE_EXIT_END; std::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow("Silicium react.cpp", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0)); if (!window) { throw_error(); return 1; } std::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0)); rx::bridge<SDL_Event> frame_events; auto frames = rx::cache(make_frames(rx::ref(frame_events)), frame{{}}); for (;;) { SDL_Event event{}; while (frame_events.is_waiting() && SDL_PollEvent(&event)) { frame_events.got_element(event); } auto f = rx::get(frames); if (!f) { break; } render_frame(*renderer, *f); SDL_Delay(16); } }
#include <reactive/bridge.hpp> #include <reactive/ptr_observable.hpp> #include <reactive/transform.hpp> #include <reactive/while.hpp> #include <reactive/finite_state_machine.hpp> #include <reactive/filter.hpp> #include <reactive/generate.hpp> #include <reactive/total_consumer.hpp> #include <reactive/cache.hpp> #include <SDL2/SDL.h> #include <boost/scope_exit.hpp> #include <boost/variant.hpp> namespace rx { template <class Element> struct visitor : observer<Element> { boost::optional<Element> result; virtual void got_element(Element value) SILICIUM_OVERRIDE { result = std::move(value); } virtual void ended() SILICIUM_OVERRIDE { } }; template <class Input> auto get(Input &from) { visitor<typename Input::element_type> v; from.async_get_one(v); return std::move(v.result); } template <class Input> auto deref_optional(Input &&input) { typedef boost::optional<typename Input::element_type> optional_type; auto is_set = [](optional_type const &element) { return element.is_initialized(); }; auto deref = [](optional_type element) { return std::move(*element); }; return transform(while_(std::forward<Input>(input), is_set), deref); } } namespace { void throw_error() { throw std::runtime_error(std::string("SDL error :") + SDL_GetError()); } void check_sdl(int rc) { if (rc < 0) { throw_error(); } } struct window_destructor { void operator()(SDL_Window *w) const { SDL_DestroyWindow(w); } }; struct renderer_destructor { void operator()(SDL_Renderer *r) const { SDL_DestroyRenderer(r); } }; void set_render_draw_color(SDL_Renderer &renderer, SDL_Color color) { SDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a); } SDL_Color make_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { SDL_Color result; result.r = red; result.g = green; result.b = blue; result.a = alpha; return result; } SDL_Rect make_rect(int x, int y, int w, int h) { SDL_Rect result; result.x = x; result.y = y; result.w = w; result.h = h; return result; } struct draw_filled_rect { SDL_Color color; SDL_Rect where; }; typedef boost::variant< draw_filled_rect > draw_operation; struct frame { std::vector<draw_operation> operations; }; struct draw_operation_renderer : boost::static_visitor<> { explicit draw_operation_renderer(SDL_Renderer &sdl) : sdl(&sdl) { } void operator()(draw_filled_rect const &operation) const { set_render_draw_color(*sdl, operation.color); SDL_RenderDrawRect(sdl, &operation.where); } private: SDL_Renderer *sdl; }; void render_frame(SDL_Renderer &sdl, frame const &frame_) { set_render_draw_color(sdl, make_color(0, 0, 0, 0xff)); SDL_RenderClear(&sdl); for (auto const &operation : frame_.operations) { boost::apply_visitor(draw_operation_renderer{sdl}, operation); } SDL_RenderPresent(&sdl); } struct game_state { int x = 100; int y = 100; int count = 1; }; int const max_rect_count = 5; frame draw_game_state(game_state const &state) { std::vector<draw_operation> operations; for (int i = 0; i < state.count; ++i) { int const max_width = 80; int const single_offset = (max_width / 2) / max_rect_count; int const total_offset = single_offset * i; int const width = max_width - total_offset * 2; operations.emplace_back(draw_filled_rect{make_color(0xff, 0x00, 0x00, 0xff), make_rect(state.x + total_offset, state.y + total_offset, width, width)}); } return frame { std::move(operations) }; } boost::optional<game_state> step_game_state(game_state previous, SDL_Event event_) { switch (event_.type) { case SDL_QUIT: return boost::none; case SDL_KEYUP: { switch (event_.key.keysym.sym) { case SDLK_LEFT: previous.x -= 10; break; case SDLK_RIGHT: previous.x += 10; break; case SDLK_UP: previous.y -= 10; break; case SDLK_DOWN: previous.y += 10; break; case SDLK_PLUS: previous.count = std::min(max_rect_count, previous.count + 1); break; case SDLK_MINUS: previous.count = std::max(1, previous.count - 1); break; case SDLK_ESCAPE: return boost::none; } break; } } return previous; } template <class Events> auto make_frames(Events &&input) { game_state initial_state; auto model = rx::make_finite_state_machine(std::forward<Events>(input), initial_state, step_game_state); return rx::transform(std::move(model), draw_game_state); } } int main() { check_sdl(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)); BOOST_SCOPE_EXIT(void) { SDL_Quit(); } BOOST_SCOPE_EXIT_END; std::unique_ptr<SDL_Window, window_destructor> window(SDL_CreateWindow("Silicium react.cpp", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0)); if (!window) { throw_error(); return 1; } std::unique_ptr<SDL_Renderer, renderer_destructor> renderer(SDL_CreateRenderer(window.get(), -1, 0)); rx::bridge<SDL_Event> frame_events; auto frames = rx::cache(make_frames(rx::ref(frame_events)), frame{{}}); for (;;) { SDL_Event event{}; while (frame_events.is_waiting() && SDL_PollEvent(&event)) { frame_events.got_element(event); } auto f = rx::get(frames); if (!f) { break; } render_frame(*renderer, *f); SDL_Delay(16); } }
make deref_optional more readable
make deref_optional more readable
C++
mit
TyRoXx/silicium,TyRoXx/silicium
518bcd80c15dae523d44095df8030e848dd72a32
editor_src2/drag2d/src/drag2d/dataset/ImageLoader.cpp
editor_src2/drag2d/src/drag2d/dataset/ImageLoader.cpp
#include <string> #include "ImageLoader.h" #include <SOIL/SOIL.h> #include <libpng/png.h> #include <assert.h> #include <gl/glew.h> #include <fstream> #include "common/tools.h" #define USE_SOIL namespace d2d { uint8_t* ImageLoader::load(const std::string& filepath, int& width, int& height, unsigned int& texture, int& format) { int channels; uint8_t* pixel_data = loadData(filepath, width, height, channels, format); assert(pixel_data); loadTexture(texture, pixel_data, format, width, height, channels); return pixel_data; } void ImageLoader::fixPixelsData(uint8_t* pixels, int width, int height) { int ptr = 0; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { uint8_t r = pixels[ptr], g = pixels[ptr+1], b = pixels[ptr+2], a = pixels[ptr+3]; if (a == 0) r = g = b = 0; pixels[ptr++] = r; pixels[ptr++] = g; pixels[ptr++] = b; pixels[ptr++] = a; } } } uint8_t* ImageLoader::loadData(const std::string& filepath, int& width, int& height, int& channels, int& format) { uint8_t* data = NULL; std::string type = filepath.substr(filepath.find_last_of(".") + 1); StringTools::toLower(type); if (type == "png") { // todo: libpngٵʱеĻҵ #ifdef USE_SOIL data = loadPngBySOIL(filepath, width, height, channels); #else data = loadPngByLibpng(filepath, width, height, channels, format); #endif // USE_SOIL } else if (type == "ppm" || type == "pgm") { std::string filename = filepath.substr(0, filepath.find_last_of(".")); channels = 4; data = loadPPM(filename, width, height, format); } if (channels == 4) fixPixelsData(data, width, height); return data; } void ImageLoader::loadTexture(unsigned int& texture, uint8_t* pixel, int format, int width, int height, int channels) { //// todo: SOILʱʱǺڵ #ifdef USE_SOIL texture = SOIL_create_OGL_texture ( pixel, width, height, channels, texture, SOIL_FLAG_INVERT_Y ); #else glPixelStorei(GL_UNPACK_ALIGNMENT, 4); if (texture == 0) { glGenTextures(1,(GLuint*)&texture); //assert(texture); } glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, format, (GLsizei)width, (GLsizei)height, 0, format, GL_UNSIGNED_BYTE, pixel); #endif // USE_SOIL } int offset = 0; void callback_read(png_structp png, png_bytep data, png_size_t size) { char* raw = (char*) png_get_io_ptr(png); memcpy(data, raw + offset, size); offset += size; } uint8_t* ImageLoader::loadPngByLibpng(const std::string& filename, int& width, int& height, int& channels, int& format) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); // get length of file: fin.seekg (0, fin.end); int length = fin.tellg(); fin.seekg (0, fin.beg); char* data = new char[length]; fin.read (data,length); fin.close(); offset = 0; png_byte lHeader[8]; png_structp lPngPtr = NULL; png_infop lInfoPtr = NULL; png_byte* lImageBuffer = NULL; png_bytep* lRowPtrs = NULL; png_int_32 lRowSize; bool lTransparency; do { // if (m_resource.read(lHeader, sizeof(lHeader)) == 0) // break; memcpy(lHeader, (char*)data + offset, sizeof(lHeader)); offset += sizeof(lHeader); if (png_sig_cmp(lHeader, 0, 8) != 0) break; lPngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!lPngPtr) break; lInfoPtr = png_create_info_struct(lPngPtr); if (!lInfoPtr) break; png_set_read_fn(lPngPtr, data, callback_read); if (setjmp(png_jmpbuf(lPngPtr))) break; png_set_sig_bytes(lPngPtr, 8); png_read_info(lPngPtr, lInfoPtr); png_int_32 lDepth, lColorType; png_uint_32 lWidth, lHeight; png_get_IHDR(lPngPtr, lInfoPtr, &lWidth, &lHeight, &lDepth, &lColorType, NULL, NULL, NULL); width = lWidth; height = lHeight; // Creates a full alpha channel if transparency is encoded as // an array of palette entries or a single transparent color. lTransparency = false; if (png_get_valid(lPngPtr, lInfoPtr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(lPngPtr); lTransparency = true; // for read pngquant's 256 color image // break; } // Expands PNG with less than 8bits per channel to 8bits. if (lDepth < 8) { png_set_packing (lPngPtr); } // Shrinks PNG with 16bits per color channel down to 8bits. else if (lDepth == 16) { png_set_strip_16(lPngPtr); } // Indicates that image needs conversion to RGBA if needed. switch (lColorType) { case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(lPngPtr); format = lTransparency ? GL_RGBA : GL_RGB; channels = lTransparency ? 4 : 3; break; case PNG_COLOR_TYPE_RGB: format = lTransparency ? GL_RGBA : GL_RGB; channels = lTransparency ? 4 : 3; break; case PNG_COLOR_TYPE_RGBA: format = GL_RGBA; channels = 4; break; case PNG_COLOR_TYPE_GRAY: png_set_expand_gray_1_2_4_to_8(lPngPtr); format = lTransparency ? GL_LUMINANCE_ALPHA : GL_LUMINANCE; channels = 1; break; case PNG_COLOR_TYPE_GA: png_set_expand_gray_1_2_4_to_8(lPngPtr); format = GL_LUMINANCE_ALPHA; channels = 1; break; } png_read_update_info(lPngPtr, lInfoPtr); lRowSize = png_get_rowbytes(lPngPtr, lInfoPtr); if (lRowSize <= 0) break; lImageBuffer = new png_byte[lRowSize * lHeight]; if (!lImageBuffer) break; lRowPtrs = new png_bytep[lHeight]; if (!lRowPtrs) break; for (unsigned int i = 0; i < lHeight; ++i) { lRowPtrs[lHeight - (i + 1)] = lImageBuffer + i * lRowSize; } png_read_image(lPngPtr, lRowPtrs); png_destroy_read_struct(&lPngPtr, &lInfoPtr, NULL); delete[] lRowPtrs; delete[] data; return lImageBuffer; } while (0); // error //ERROR: // Log::error("Error while reading PNG file"); delete[] lRowPtrs; delete[] lImageBuffer; delete[] data; if (lPngPtr != NULL) { png_infop* lInfoPtrP = lInfoPtr != NULL ? &lInfoPtr : NULL; png_destroy_read_struct(&lPngPtr, lInfoPtrP, NULL); } return NULL; } uint8_t* ImageLoader::loadPngBySOIL(const std::string& filename, int& width, int& height, int& channels) { return SOIL_load_image(filename.c_str(), &width, &height, &channels, 0); } uint8_t* ImageLoader::loadPPM(const std::string& filename, int& width, int& height, int& format) { std::string filepath; int w0, h0, w1, h1; filepath = filename + ".ppm"; uint8_t* ppm = loadPPM(filepath, w0, h0); filepath = filename + ".pgm"; uint8_t* pgm = loadPGM(filepath, w1, h1); assert(w0 == w1 && h0 == h1); width = w0; height = h0; format = 0x1908; // GL_RGBA int size = width * height * 4; uint8_t* pixels = new uint8_t[size]; int ptr_ppm = 0, ptr_pgm = 0, ptr_dst = 0; while (ptr_dst != size) { pixels[ptr_dst] = std::min(255, (int)ppm[ptr_ppm]*16); pixels[ptr_dst+1] = std::min(255, (int)ppm[ptr_ppm+1]*16); pixels[ptr_dst+2] = std::min(255, (int)ppm[ptr_ppm+2]*16); // memcpy(&pixels[ptr_dst], &ppm[ptr_ppm], 3); ptr_dst += 3; ptr_ppm += 3; pixels[ptr_dst] = std::min(255, (int)pgm[ptr_pgm]*16); // memcpy(&pixels[ptr_dst], &pgm[ptr_pgm], 1); ptr_dst += 1; ptr_pgm += 1; } delete[] ppm; delete[] pgm; return pixels; } uint8_t* ImageLoader::loadPPM(const std::string& filename, int& width, int& height) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); uint8_t tag0, tag1; fin.read(reinterpret_cast<char*>(&tag0), sizeof(uint8_t)); fin.read(reinterpret_cast<char*>(&tag1), sizeof(uint8_t)); assert(tag0 == 80 && tag1 == 54); // P6 uint8_t skip; fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // width width = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); width = width * 10 + (n - 48); } fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // height height = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); height = height * 10 + (n - 48); } for (int i = 0; i < 4; ++i) fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); int size = width * height * 3; uint8_t* pixels = new uint8_t[size]; fin.read(reinterpret_cast<char*>(pixels), size); fin.close(); return pixels; } uint8_t* ImageLoader::loadPGM(const std::string& filename, int& width, int& height) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); uint8_t tag0, tag1; fin.read(reinterpret_cast<char*>(&tag0), sizeof(uint8_t)); fin.read(reinterpret_cast<char*>(&tag1), sizeof(uint8_t)); assert(tag0 == 80 && tag1 == 53); // P5 uint8_t skip; fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // width width = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); width = width * 10 + (n - 48); } fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // height height = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); height = height * 10 + (n - 48); } for (int i = 0; i < 4; ++i) fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); int size = width * height; uint8_t* pixels = new uint8_t[size]; fin.read(reinterpret_cast<char*>(pixels), size); fin.close(); return pixels; } }
#include <string> #include "ImageLoader.h" #include <SOIL/SOIL.h> #include <libpng/png.h> #include <assert.h> #include <gl/glew.h> #include <fstream> #include "common/tools.h" #define USE_SOIL namespace d2d { uint8_t* ImageLoader::load(const std::string& filepath, int& width, int& height, unsigned int& texture, int& format) { int channels; uint8_t* pixel_data = loadData(filepath, width, height, channels, format); assert(pixel_data); loadTexture(texture, pixel_data, format, width, height, channels); return pixel_data; } void ImageLoader::fixPixelsData(uint8_t* pixels, int width, int height) { int ptr = 0; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { uint8_t r = pixels[ptr], g = pixels[ptr+1], b = pixels[ptr+2], a = pixels[ptr+3]; if (a == 0) r = g = b = 0; pixels[ptr++] = r; pixels[ptr++] = g; pixels[ptr++] = b; pixels[ptr++] = a; } } } uint8_t* ImageLoader::loadData(const std::string& filepath, int& width, int& height, int& channels, int& format) { uint8_t* data = NULL; std::string type = filepath.substr(filepath.find_last_of(".") + 1); StringTools::toLower(type); if (type == "png") { // todo: libpngٵʱеĻҵ #ifdef USE_SOIL data = loadPngBySOIL(filepath, width, height, channels); #else data = loadPngByLibpng(filepath, width, height, channels, format); #endif // USE_SOIL } else if (type == "ppm" || type == "pgm") { std::string filename = filepath.substr(0, filepath.find_last_of(".")); channels = 4; data = loadPPM(filename, width, height, format); } if (channels == 4) fixPixelsData(data, width, height); return data; } void ImageLoader::loadTexture(unsigned int& texture, uint8_t* pixel, int format, int width, int height, int channels) { //// todo: SOILʱʱǺڵ #ifdef USE_SOIL texture = SOIL_create_OGL_texture ( pixel, width, height, channels, texture, SOIL_FLAG_INVERT_Y ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else glPixelStorei(GL_UNPACK_ALIGNMENT, 4); if (texture == 0) { glGenTextures(1,(GLuint*)&texture); //assert(texture); } glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, format, (GLsizei)width, (GLsizei)height, 0, format, GL_UNSIGNED_BYTE, pixel); #endif // USE_SOIL } int offset = 0; void callback_read(png_structp png, png_bytep data, png_size_t size) { char* raw = (char*) png_get_io_ptr(png); memcpy(data, raw + offset, size); offset += size; } uint8_t* ImageLoader::loadPngByLibpng(const std::string& filename, int& width, int& height, int& channels, int& format) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); // get length of file: fin.seekg (0, fin.end); int length = fin.tellg(); fin.seekg (0, fin.beg); char* data = new char[length]; fin.read (data,length); fin.close(); offset = 0; png_byte lHeader[8]; png_structp lPngPtr = NULL; png_infop lInfoPtr = NULL; png_byte* lImageBuffer = NULL; png_bytep* lRowPtrs = NULL; png_int_32 lRowSize; bool lTransparency; do { // if (m_resource.read(lHeader, sizeof(lHeader)) == 0) // break; memcpy(lHeader, (char*)data + offset, sizeof(lHeader)); offset += sizeof(lHeader); if (png_sig_cmp(lHeader, 0, 8) != 0) break; lPngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!lPngPtr) break; lInfoPtr = png_create_info_struct(lPngPtr); if (!lInfoPtr) break; png_set_read_fn(lPngPtr, data, callback_read); if (setjmp(png_jmpbuf(lPngPtr))) break; png_set_sig_bytes(lPngPtr, 8); png_read_info(lPngPtr, lInfoPtr); png_int_32 lDepth, lColorType; png_uint_32 lWidth, lHeight; png_get_IHDR(lPngPtr, lInfoPtr, &lWidth, &lHeight, &lDepth, &lColorType, NULL, NULL, NULL); width = lWidth; height = lHeight; // Creates a full alpha channel if transparency is encoded as // an array of palette entries or a single transparent color. lTransparency = false; if (png_get_valid(lPngPtr, lInfoPtr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(lPngPtr); lTransparency = true; // for read pngquant's 256 color image // break; } // Expands PNG with less than 8bits per channel to 8bits. if (lDepth < 8) { png_set_packing (lPngPtr); } // Shrinks PNG with 16bits per color channel down to 8bits. else if (lDepth == 16) { png_set_strip_16(lPngPtr); } // Indicates that image needs conversion to RGBA if needed. switch (lColorType) { case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(lPngPtr); format = lTransparency ? GL_RGBA : GL_RGB; channels = lTransparency ? 4 : 3; break; case PNG_COLOR_TYPE_RGB: format = lTransparency ? GL_RGBA : GL_RGB; channels = lTransparency ? 4 : 3; break; case PNG_COLOR_TYPE_RGBA: format = GL_RGBA; channels = 4; break; case PNG_COLOR_TYPE_GRAY: png_set_expand_gray_1_2_4_to_8(lPngPtr); format = lTransparency ? GL_LUMINANCE_ALPHA : GL_LUMINANCE; channels = 1; break; case PNG_COLOR_TYPE_GA: png_set_expand_gray_1_2_4_to_8(lPngPtr); format = GL_LUMINANCE_ALPHA; channels = 1; break; } png_read_update_info(lPngPtr, lInfoPtr); lRowSize = png_get_rowbytes(lPngPtr, lInfoPtr); if (lRowSize <= 0) break; lImageBuffer = new png_byte[lRowSize * lHeight]; if (!lImageBuffer) break; lRowPtrs = new png_bytep[lHeight]; if (!lRowPtrs) break; for (unsigned int i = 0; i < lHeight; ++i) { lRowPtrs[lHeight - (i + 1)] = lImageBuffer + i * lRowSize; } png_read_image(lPngPtr, lRowPtrs); png_destroy_read_struct(&lPngPtr, &lInfoPtr, NULL); delete[] lRowPtrs; delete[] data; return lImageBuffer; } while (0); // error //ERROR: // Log::error("Error while reading PNG file"); delete[] lRowPtrs; delete[] lImageBuffer; delete[] data; if (lPngPtr != NULL) { png_infop* lInfoPtrP = lInfoPtr != NULL ? &lInfoPtr : NULL; png_destroy_read_struct(&lPngPtr, lInfoPtrP, NULL); } return NULL; } uint8_t* ImageLoader::loadPngBySOIL(const std::string& filename, int& width, int& height, int& channels) { return SOIL_load_image(filename.c_str(), &width, &height, &channels, 0); } uint8_t* ImageLoader::loadPPM(const std::string& filename, int& width, int& height, int& format) { std::string filepath; int w0, h0, w1, h1; filepath = filename + ".ppm"; uint8_t* ppm = loadPPM(filepath, w0, h0); filepath = filename + ".pgm"; uint8_t* pgm = loadPGM(filepath, w1, h1); assert(w0 == w1 && h0 == h1); width = w0; height = h0; format = 0x1908; // GL_RGBA int size = width * height * 4; uint8_t* pixels = new uint8_t[size]; int ptr_ppm = 0, ptr_pgm = 0, ptr_dst = 0; while (ptr_dst != size) { pixels[ptr_dst] = std::min(255, (int)ppm[ptr_ppm]*16); pixels[ptr_dst+1] = std::min(255, (int)ppm[ptr_ppm+1]*16); pixels[ptr_dst+2] = std::min(255, (int)ppm[ptr_ppm+2]*16); // memcpy(&pixels[ptr_dst], &ppm[ptr_ppm], 3); ptr_dst += 3; ptr_ppm += 3; pixels[ptr_dst] = std::min(255, (int)pgm[ptr_pgm]*16); // memcpy(&pixels[ptr_dst], &pgm[ptr_pgm], 1); ptr_dst += 1; ptr_pgm += 1; } delete[] ppm; delete[] pgm; return pixels; } uint8_t* ImageLoader::loadPPM(const std::string& filename, int& width, int& height) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); uint8_t tag0, tag1; fin.read(reinterpret_cast<char*>(&tag0), sizeof(uint8_t)); fin.read(reinterpret_cast<char*>(&tag1), sizeof(uint8_t)); assert(tag0 == 80 && tag1 == 54); // P6 uint8_t skip; fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // width width = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); width = width * 10 + (n - 48); } fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // height height = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); height = height * 10 + (n - 48); } for (int i = 0; i < 4; ++i) fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); int size = width * height * 3; uint8_t* pixels = new uint8_t[size]; fin.read(reinterpret_cast<char*>(pixels), size); fin.close(); return pixels; } uint8_t* ImageLoader::loadPGM(const std::string& filename, int& width, int& height) { std::ifstream fin(filename.c_str(), std::ios::binary); assert(!fin.fail()); uint8_t tag0, tag1; fin.read(reinterpret_cast<char*>(&tag0), sizeof(uint8_t)); fin.read(reinterpret_cast<char*>(&tag1), sizeof(uint8_t)); assert(tag0 == 80 && tag1 == 53); // P5 uint8_t skip; fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // width width = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); width = width * 10 + (n - 48); } fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); // height height = 0; for (int i = 0; i < 4; ++i) { uint8_t n; fin.read(reinterpret_cast<char*>(&n), sizeof(uint8_t)); height = height * 10 + (n - 48); } for (int i = 0; i < 4; ++i) fin.read(reinterpret_cast<char*>(&skip), sizeof(uint8_t)); int size = width * height; uint8_t* pixels = new uint8_t[size]; fin.read(reinterpret_cast<char*>(pixels), size); fin.close(); return pixels; } }
修改图像边缘的采样,保证拉伸后正确
修改图像边缘的采样,保证拉伸后正确
C++
mit
xzrunner/easyeditor,xzrunner/easyeditor
186a7758b9d30675e0c8eda979a2fa5ca52683e7
engine/audio/plugins/sndfile/audiodecoder_sndfile.cpp
engine/audio/plugins/sndfile/audiodecoder_sndfile.cpp
/* Q Light Controller Plus audiodecoder_sndfile.cpp Copyright (c) Massimo Callegari 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.txt 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. */ /****************************************************** * Based on qmmp project * * * * Copyright (C) 2007-2009 by Ilya Kotov * * [email protected] * ******************************************************/ #include <QObject> #include <QFile> #include <QFileInfo> #include <QDebug> #include "audiodecoder_sndfile.h" AudioDecoderSndFile::~AudioDecoderSndFile() { m_totalTime = 0; m_bitrate = 0; m_freq = 0; if (m_path.isEmpty() == false && m_sndfile != NULL) sf_close(m_sndfile); m_sndfile = NULL; } AudioDecoder *AudioDecoderSndFile::createCopy() { AudioDecoderSndFile* copy = new AudioDecoderSndFile(); return qobject_cast<AudioDecoder *>(copy); } int AudioDecoderSndFile::priority() const { return 10; } bool AudioDecoderSndFile::initialize(const QString &path) { m_path = path; m_bitrate = 0; m_totalTime = 0; m_sndfile = NULL; m_freq = 0; SF_INFO snd_info; if (path.isEmpty()) return false; memset (&snd_info, 0, sizeof(snd_info)); snd_info.format = 0; m_sndfile = sf_open(m_path.toLocal8Bit(), SFM_READ, &snd_info); if (!m_sndfile) { qWarning("DecoderSndFile: failed to open: %s", qPrintable(m_path)); return false; } m_freq = snd_info.samplerate; int chan = snd_info.channels; m_totalTime = snd_info.frames * 1000 / m_freq; m_bitrate = QFileInfo(m_path).size () * 8.0 / m_totalTime + 0.5; if((snd_info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_FLOAT) { qDebug() << "DecoderSndFile: Float audio format"; sf_command (m_sndfile, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE); } AudioFormat pcmFormat = PCM_S16LE; switch(snd_info.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: pcmFormat = PCM_S8; break; case SF_FORMAT_PCM_16: pcmFormat = PCM_S16LE; break; case SF_FORMAT_PCM_24: pcmFormat = PCM_S24LE; break; case SF_FORMAT_PCM_32: pcmFormat = PCM_S32LE; break; default: pcmFormat = PCM_S16LE; break; } configure(m_freq, chan, pcmFormat); qDebug() << "DecoderSndFile: detected format: Sample Rate:" << m_freq << ",Channels: " << chan << ", PCM Format: " << pcmFormat /*snd_info.format*/; return true; } qint64 AudioDecoderSndFile::totalTime() { return m_totalTime; } int AudioDecoderSndFile::bitrate() { return m_bitrate; } qint64 AudioDecoderSndFile::read(char *audio, qint64 maxSize) { return sizeof(short)* sf_read_short (m_sndfile, (short *)audio, maxSize / sizeof(short)); } void AudioDecoderSndFile::seek(qint64 pos) { sf_seek(m_sndfile, m_freq * pos/1000, SEEK_SET); } QStringList AudioDecoderSndFile::supportedFormats() { QStringList caps; SF_FORMAT_INFO format_info; int k, count ; sf_command (0, SFC_GET_SIMPLE_FORMAT_COUNT, &count, sizeof (int)) ; for (k = 0 ; k < count ; k++) { format_info.format = k; sf_command (0, SFC_GET_SIMPLE_FORMAT, &format_info, sizeof (format_info)); qDebug("%08x %s %s", format_info.format, format_info.name, format_info.extension); QString ext = QString(format_info.extension); if (ext == "aiff" && !caps.contains("*.aiff")) caps << "*.aiff"; else if (ext == "aifc" && !caps.contains("*.aifc")) caps << "*.aifc"; else if (ext == "flac" && !caps.contains("*.flac")) caps << "*.flac"; else if (ext == "oga" && !caps.contains("*.oga")) caps << "*.oga" << "*.ogg"; else if (ext == "wav" && !caps.contains("*.wav")) caps << "*.wav"; } return caps; }
/* Q Light Controller Plus audiodecoder_sndfile.cpp Copyright (c) Massimo Callegari 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.txt 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. */ /****************************************************** * Based on qmmp project * * * * Copyright (C) 2007-2009 by Ilya Kotov * * [email protected] * ******************************************************/ #include <QObject> #include <QFile> #include <QFileInfo> #include <QDebug> #include "audiodecoder_sndfile.h" AudioDecoderSndFile::~AudioDecoderSndFile() { m_totalTime = 0; m_bitrate = 0; m_freq = 0; if (m_path.isEmpty() == false && m_sndfile != NULL) sf_close(m_sndfile); m_sndfile = NULL; } AudioDecoder *AudioDecoderSndFile::createCopy() { AudioDecoderSndFile* copy = new AudioDecoderSndFile(); return qobject_cast<AudioDecoder *>(copy); } int AudioDecoderSndFile::priority() const { return 10; } bool AudioDecoderSndFile::initialize(const QString &path) { m_path = path; m_bitrate = 0; m_totalTime = 0; m_sndfile = NULL; m_freq = 0; SF_INFO snd_info; if (path.isEmpty()) return false; memset (&snd_info, 0, sizeof(snd_info)); snd_info.format = 0; m_sndfile = sf_open(m_path.toLocal8Bit(), SFM_READ, &snd_info); if (!m_sndfile) { qWarning("DecoderSndFile: failed to open: %s", qPrintable(m_path)); return false; } m_freq = snd_info.samplerate; int chan = snd_info.channels; m_totalTime = snd_info.frames * 1000 / m_freq; m_bitrate = QFileInfo(m_path).size () * 8.0 / m_totalTime + 0.5; if((snd_info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_FLOAT) { qDebug() << "DecoderSndFile: Float audio format"; sf_command (m_sndfile, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE); } AudioFormat pcmFormat = PCM_S16LE; switch(snd_info.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: pcmFormat = PCM_S8; break; case SF_FORMAT_PCM_16: pcmFormat = PCM_S16LE; break; case SF_FORMAT_PCM_24: pcmFormat = PCM_S24LE; break; case SF_FORMAT_PCM_32: pcmFormat = PCM_S32LE; break; default: pcmFormat = PCM_S16LE; break; } configure(m_freq, chan, pcmFormat); qDebug() << "DecoderSndFile: detected format: Sample Rate:" << m_freq << ",Channels: " << chan << ", PCM Format: " << pcmFormat /*snd_info.format*/; return true; } qint64 AudioDecoderSndFile::totalTime() { return m_totalTime; } int AudioDecoderSndFile::bitrate() { return m_bitrate; } qint64 AudioDecoderSndFile::read(char *audio, qint64 maxSize) { return sizeof(short)* sf_read_short (m_sndfile, (short *)audio, maxSize / sizeof(short)); } void AudioDecoderSndFile::seek(qint64 pos) { sf_seek(m_sndfile, m_freq * pos/1000, SEEK_SET); } QStringList AudioDecoderSndFile::supportedFormats() { QStringList caps; SF_FORMAT_INFO format_info; int k, count ; sf_command (0, SFC_GET_SIMPLE_FORMAT_COUNT, &count, sizeof (int)) ; for (k = 0 ; k < count ; k++) { format_info.format = k; sf_command (0, SFC_GET_SIMPLE_FORMAT, &format_info, sizeof (format_info)); qDebug("%08x %s %s", format_info.format, format_info.name, format_info.extension); QString ext = QString(format_info.extension); if (ext == "aiff" && !caps.contains("*.aiff")) caps << "*.aiff"; else if (ext == "aifc" && !caps.contains("*.aifc")) caps << "*.aifc"; else if (ext == "flac" && !caps.contains("*.flac")) caps << "*.flac"; else if ((ext == "ogg" || ext == "oga") && !caps.contains("*.ogg")) caps << "*.oga" << "*.ogg"; else if (ext == "wav" && !caps.contains("*.wav")) caps << "*.wav"; } return caps; }
improve ogg format detection
audio: improve ogg format detection
C++
apache-2.0
mcallegari/qlcplus,plugz/qlcplus,plugz/qlcplus,sbenejam/qlcplus,kripton/qlcplus,kripton/qlcplus,plugz/qlcplus,mcallegari/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,plugz/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,kripton/qlcplus,kripton/qlcplus,mcallegari/qlcplus,sbenejam/qlcplus,kripton/qlcplus,sbenejam/qlcplus,mcallegari/qlcplus,plugz/qlcplus,mcallegari/qlcplus,plugz/qlcplus,kripton/qlcplus,plugz/qlcplus
9d2e043879b84f5781efa39ed66e2a45637bb0ca
framework/cybertron/tools/cyber_recorder/recorder.cpp
framework/cybertron/tools/cyber_recorder/recorder.cpp
/****************************************************************************** * Copyright 2018 The Apollo Authors. 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 "cybertron/tools/cyber_recorder/recorder.h" namespace apollo { namespace cybertron { namespace record { Recorder::Recorder(const std::string& output, bool all_channels, const std::vector<std::string>& channel_vec) : is_started_(false), is_stopping_(false), output_(output), all_channels_(all_channels), channel_vec_(channel_vec), writer_(nullptr), node_(nullptr) {} Recorder::~Recorder() { Stop(); } bool Recorder::Start() { writer_.reset(new RecordWriter()); if (!writer_->Open(output_)) { AERROR << "Datafile open file error."; return false; } std::string node_name = "cyber_recorder_record_" + std::to_string(getpid()); node_ = ::apollo::cybertron::CreateNode(node_name); if (node_ == nullptr) { AERROR << "create node failed, node: " << node_name; return false; } if (!InitReadersImpl()) { AERROR << " _init_readers error."; return false; } is_started_ = true; return true; } bool Recorder::Stop() { if (!is_started_ || is_stopping_) { return false; } is_stopping_ = true; if (!FreeReadersImpl()) { AERROR << " _free_readers error."; return false; } writer_->Close(); node_.reset(); return true; } void Recorder::TopologyCallback(const ChangeMsg& change_message) { ADEBUG << "ChangeMsg in Topology Callback:" << std::endl << change_message.ShortDebugString(); if (change_message.role_type() != apollo::cybertron::proto::ROLE_WRITER) { ADEBUG << "Change message role type is not ROLE_WRITER."; return; } FindNewChannel(change_message.role_attr()); } void Recorder::FindNewChannel(const RoleAttributes& role_attr) { if (!role_attr.has_channel_name() || role_attr.channel_name().empty()) { AWARN << "change message not has a channel name or has an empty one."; return; } if (!role_attr.has_message_type() || role_attr.message_type().empty()) { AWARN << "Change message not has a message type or has an empty one."; return; } if (!role_attr.has_proto_desc() || role_attr.proto_desc().empty()) { AWARN << "Change message not has a proto desc or has an empty one."; return; } if (!all_channels_ && std::find(channel_vec_.begin(), channel_vec_.end(), role_attr.channel_name()) == channel_vec_.end()) { ADEBUG << "New channel was found, but not in record list."; return; } if (channel_reader_map_.find(role_attr.channel_name()) == channel_reader_map_.end()) { if (!writer_->WriteChannel(role_attr.channel_name(), role_attr.message_type(), role_attr.proto_desc())) { AERROR << "write channel fail, channel:" << role_attr.channel_name(); } InitReaderImpl(role_attr.channel_name(), role_attr.message_type()); } } bool Recorder::InitReadersImpl() { std::shared_ptr<ChannelManager> channel_manager = TopologyManager::Instance()->channel_manager(); // get historical writers std::vector<proto::RoleAttributes> role_attr_vec; channel_manager->GetWriters(&role_attr_vec); for (auto role_attr : role_attr_vec) { FindNewChannel(role_attr); } // listen new writers in future change_conn_ = channel_manager->AddChangeListener( std::bind(&Recorder::TopologyCallback, this, std::placeholders::_1)); if (!change_conn_.IsConnected()) { AERROR << "change connection is not connected"; return false; } return true; } bool Recorder::FreeReadersImpl() { std::shared_ptr<ChannelManager> channel_manager = TopologyManager::Instance()->channel_manager(); channel_manager->RemoveChangeListener(change_conn_); return true; } bool Recorder::InitReaderImpl(const std::string& channel_name, const std::string& message_type) { try { std::weak_ptr<Recorder> weak_this = shared_from_this(); std::shared_ptr<ReaderBase> reader = nullptr; auto callback = [weak_this, channel_name]( const std::shared_ptr<RawMessage>& raw_message) { auto share_this = weak_this.lock(); if (!share_this) { return; } share_this->ReaderCallback(raw_message, channel_name); share_this->writer_->ShowProgress(); }; reader = node_->CreateReader<RawMessage>(channel_name, callback); if (reader == nullptr) { AERROR << "Create reader failed."; return false; } channel_reader_map_[channel_name] = reader; return true; } catch (const std::bad_weak_ptr& e) { AERROR << e.what(); return false; } } void Recorder::ReaderCallback(const std::shared_ptr<RawMessage>& message, const std::string& channel_name) { if (!is_started_ || is_stopping_) { AERROR << "record procedure is not started or stopping."; return; } if (message == nullptr) { AERROR << "message is nullptr, channel: " << channel_name; return; } if (!writer_->WriteMessage(channel_name, message, Time::Now().ToNanosecond())) { AERROR << "write data fail, channel: " << channel_name; return; } } } // namespace record } // namespace cybertron } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo Authors. 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 "cybertron/tools/cyber_recorder/recorder.h" namespace apollo { namespace cybertron { namespace record { Recorder::Recorder(const std::string& output, bool all_channels, const std::vector<std::string>& channel_vec) : is_started_(false), is_stopping_(false), output_(output), all_channels_(all_channels), channel_vec_(channel_vec), writer_(nullptr), node_(nullptr) {} Recorder::~Recorder() { Stop(); } bool Recorder::Start() { writer_.reset(new RecordWriter()); if (!writer_->Open(output_)) { AERROR << "Datafile open file error."; return false; } std::string node_name = "cyber_recorder_record_" + std::to_string(getpid()); node_ = ::apollo::cybertron::CreateNode(node_name); if (node_ == nullptr) { AERROR << "create node failed, node: " << node_name; return false; } if (!InitReadersImpl()) { AERROR << " _init_readers error."; return false; } is_started_ = true; return true; } bool Recorder::Stop() { if (!is_started_ || is_stopping_) { return false; } is_stopping_ = true; if (!FreeReadersImpl()) { AERROR << " _free_readers error."; return false; } writer_->Close(); node_.reset(); return true; } void Recorder::TopologyCallback(const ChangeMsg& change_message) { ADEBUG << "ChangeMsg in Topology Callback:" << std::endl << change_message.ShortDebugString(); if (change_message.role_type() != apollo::cybertron::proto::ROLE_WRITER) { ADEBUG << "Change message role type is not ROLE_WRITER."; return; } FindNewChannel(change_message.role_attr()); } void Recorder::FindNewChannel(const RoleAttributes& role_attr) { if (!role_attr.has_channel_name() || role_attr.channel_name().empty()) { AWARN << "change message not has a channel name or has an empty one."; return; } if (!role_attr.has_message_type() || role_attr.message_type().empty()) { AWARN << "Change message not has a message type or has an empty one."; return; } if (!role_attr.has_proto_desc() || role_attr.proto_desc().empty()) { AWARN << "Change message not has a proto desc or has an empty one."; return; } if (!all_channels_ && std::find(channel_vec_.begin(), channel_vec_.end(), role_attr.channel_name()) == channel_vec_.end()) { ADEBUG << "New channel was found, but not in record list."; return; } if (channel_reader_map_.find(role_attr.channel_name()) == channel_reader_map_.end()) { if (!writer_->WriteChannel(role_attr.channel_name(), role_attr.message_type(), role_attr.proto_desc())) { AERROR << "write channel fail, channel:" << role_attr.channel_name(); } InitReaderImpl(role_attr.channel_name(), role_attr.message_type()); } } bool Recorder::InitReadersImpl() { std::shared_ptr<ChannelManager> channel_manager = TopologyManager::Instance()->channel_manager(); // get historical writers std::vector<proto::RoleAttributes> role_attr_vec; channel_manager->GetWriters(&role_attr_vec); for (auto role_attr : role_attr_vec) { FindNewChannel(role_attr); } // listen new writers in future change_conn_ = channel_manager->AddChangeListener( std::bind(&Recorder::TopologyCallback, this, std::placeholders::_1)); if (!change_conn_.IsConnected()) { AERROR << "change connection is not connected"; return false; } return true; } bool Recorder::FreeReadersImpl() { std::shared_ptr<ChannelManager> channel_manager = TopologyManager::Instance()->channel_manager(); channel_manager->RemoveChangeListener(change_conn_); return true; } bool Recorder::InitReaderImpl(const std::string& channel_name, const std::string& message_type) { try { std::weak_ptr<Recorder> weak_this = shared_from_this(); std::shared_ptr<ReaderBase> reader = nullptr; auto callback = [weak_this, channel_name]( const std::shared_ptr<RawMessage>& raw_message) { auto share_this = weak_this.lock(); if (!share_this) { return; } share_this->ReaderCallback(raw_message, channel_name); share_this->writer_->ShowProgress(); }; ReaderConfig config; config.channel_name = channel_name; config.pending_queue_size = 20; reader = node_->CreateReader<RawMessage>(config, callback); if (reader == nullptr) { AERROR << "Create reader failed."; return false; } channel_reader_map_[channel_name] = reader; return true; } catch (const std::bad_weak_ptr& e) { AERROR << e.what(); return false; } } void Recorder::ReaderCallback(const std::shared_ptr<RawMessage>& message, const std::string& channel_name) { if (!is_started_ || is_stopping_) { AERROR << "record procedure is not started or stopping."; return; } if (message == nullptr) { AERROR << "message is nullptr, channel: " << channel_name; return; } if (!writer_->WriteMessage(channel_name, message, Time::Now().ToNanosecond())) { AERROR << "write data fail, channel: " << channel_name; return; } } } // namespace record } // namespace cybertron } // namespace apollo
enlarge pending queue size of recorder reader to avoid message drop
framework: enlarge pending queue size of recorder reader to avoid message drop
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
12d4124ad93263e5df4197f13b93c00dcbd57fee
src/sync_metadata.cpp
src/sync_metadata.cpp
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #include "sync_metadata.hpp" #include "object_schema.hpp" #include "object_store.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include <realm/descriptor.hpp> #include <realm/table.hpp> namespace realm { static const char * const c_sync_userMetadata = "UserMetadata"; static const char * const c_sync_marked_for_removal = "marked_for_removal"; static const char * const c_sync_identity = "identity"; static const char * const c_sync_auth_server_url = "auth_server_url"; static const char * const c_sync_user_token = "user_token"; SyncMetadataManager::SyncMetadataManager(std::string path) { std::lock_guard<std::mutex> lock(m_metadata_lock); auto nullable_string_property = [](std::string name)->Property { Property p = { name, PropertyType::String }; p.is_nullable = true; return p; }; Property primary_key = { c_sync_identity, PropertyType::String }; primary_key.is_indexed = true; primary_key.is_primary = true; Realm::Config config; config.path = path; Schema schema = { { c_sync_userMetadata, { primary_key, { c_sync_marked_for_removal, PropertyType::Bool }, nullable_string_property(c_sync_auth_server_url), nullable_string_property(c_sync_user_token), } } }; config.schema = std::move(schema); config.schema_mode = SchemaMode::Additive; // Open the Realm. SharedRealm realm = Realm::get_shared_realm(config); // Get data about the (hardcoded) schema. DescriptorRef descriptor = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata)->get_descriptor(); m_schema = { descriptor->get_column_index(c_sync_identity), descriptor->get_column_index(c_sync_marked_for_removal), descriptor->get_column_index(c_sync_user_token), descriptor->get_column_index(c_sync_auth_server_url) }; m_metadata_config = std::move(config); } Realm::Config SyncMetadataManager::get_configuration() const { std::lock_guard<std::mutex> lock(m_metadata_lock); return m_metadata_config; } SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const { return get_users(false); } SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const { return get_users(true); } SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const { // Open the Realm. SharedRealm realm = Realm::get_shared_realm(get_configuration()); TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); Query query = table->where().equal(m_schema.idx_marked_for_removal, marked); Results results(realm, std::move(query)); return SyncUserMetadataResults(std::move(results), std::move(realm), m_schema); } SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row) : m_realm(realm) , m_schema(schema) , m_row(Row(row)) , m_invalid(Row(row).get_bool(schema.idx_marked_for_removal)) { } SyncUserMetadata::SyncUserMetadata(SyncMetadataManager& manager, std::string identity, bool make_if_absent) : m_schema(manager.m_schema) { // Open the Realm. m_realm = Realm::get_shared_realm(manager.get_configuration()); // Retrieve or create the row for this object. TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); size_t row_idx = table->find_first_string(m_schema.idx_identity, identity); if (row_idx == not_found) { if (!make_if_absent) { m_invalid = true; m_realm = nullptr; return; } m_realm->begin_transaction(); row_idx = table->find_first_string(m_schema.idx_identity, identity); if (row_idx == not_found) { row_idx = table->add_empty_row(); table->set_string(m_schema.idx_identity, row_idx, identity); m_realm->commit_transaction(); } else { // Someone beat us to adding this user. m_realm->cancel_transaction(); } } m_row = table->get(row_idx); m_invalid = m_row.get_bool(m_schema.idx_marked_for_removal); } bool SyncUserMetadata::is_valid() const { return !m_invalid; } std::string SyncUserMetadata::identity() const { m_realm->verify_thread(); StringData result = m_row.get_string(m_schema.idx_identity); return result; } util::Optional<std::string> SyncUserMetadata::get_optional_string_field(size_t col_idx) const { REALM_ASSERT(!m_invalid); m_realm->verify_thread(); StringData result = m_row.get_string(col_idx); return result.is_null() ? util::none : util::make_optional(std::string(result)); } util::Optional<std::string> SyncUserMetadata::server_url() const { return get_optional_string_field(m_schema.idx_auth_server_url); } util::Optional<std::string> SyncUserMetadata::user_token() const { return get_optional_string_field(m_schema.idx_user_token); } void SyncUserMetadata::set_state(util::Optional<std::string> server_url, util::Optional<std::string> user_token) { if (m_invalid) { return; } m_realm->verify_thread(); m_realm->begin_transaction(); m_row.set_string(m_schema.idx_user_token, *user_token); m_row.set_string(m_schema.idx_auth_server_url, *server_url); m_realm->commit_transaction(); } void SyncUserMetadata::mark_for_removal() { if (m_invalid) { return; } m_realm->verify_thread(); m_realm->begin_transaction(); m_row.set_bool(m_schema.idx_marked_for_removal, true); m_realm->commit_transaction(); } void SyncUserMetadata::remove() { if (m_invalid) { return; } m_invalid = true; m_realm->begin_transaction(); TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); table->move_last_over(m_row.get_index()); m_realm->commit_transaction(); m_realm = nullptr; } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm 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. // //////////////////////////////////////////////////////////////////////////// #include "sync_metadata.hpp" #include "object_schema.hpp" #include "object_store.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include <realm/descriptor.hpp> #include <realm/table.hpp> namespace realm { static const char * const c_sync_userMetadata = "UserMetadata"; static const char * const c_sync_marked_for_removal = "marked_for_removal"; static const char * const c_sync_identity = "identity"; static const char * const c_sync_auth_server_url = "auth_server_url"; static const char * const c_sync_user_token = "user_token"; SyncMetadataManager::SyncMetadataManager(std::string path) { std::lock_guard<std::mutex> lock(m_metadata_lock); auto nullable_string_property = [](std::string name)->Property { Property p = { name, PropertyType::String }; p.is_nullable = true; return p; }; Property primary_key = { c_sync_identity, PropertyType::String }; primary_key.is_indexed = true; primary_key.is_primary = true; Realm::Config config; config.path = path; Schema schema = { { c_sync_userMetadata, { primary_key, { c_sync_marked_for_removal, PropertyType::Bool }, nullable_string_property(c_sync_auth_server_url), nullable_string_property(c_sync_user_token), } } }; config.schema = std::move(schema); config.schema_mode = SchemaMode::Additive; // Open the Realm. SharedRealm realm = Realm::get_shared_realm(config); // Get data about the (hardcoded) schema. DescriptorRef descriptor = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata)->get_descriptor(); m_schema = { descriptor->get_column_index(c_sync_identity), descriptor->get_column_index(c_sync_marked_for_removal), descriptor->get_column_index(c_sync_user_token), descriptor->get_column_index(c_sync_auth_server_url) }; m_metadata_config = std::move(config); } Realm::Config SyncMetadataManager::get_configuration() const { std::lock_guard<std::mutex> lock(m_metadata_lock); return m_metadata_config; } SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const { return get_users(false); } SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const { return get_users(true); } SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const { // Open the Realm. SharedRealm realm = Realm::get_shared_realm(get_configuration()); TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); Query query = table->where().equal(m_schema.idx_marked_for_removal, marked); Results results(realm, std::move(query)); return SyncUserMetadataResults(std::move(results), std::move(realm), m_schema); } SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row) : m_realm(realm) , m_schema(schema) , m_row(Row(row)) , m_invalid(Row(row).get_bool(schema.idx_marked_for_removal)) { } SyncUserMetadata::SyncUserMetadata(SyncMetadataManager& manager, std::string identity, bool make_if_absent) : m_schema(manager.m_schema) { // Open the Realm. m_realm = Realm::get_shared_realm(manager.get_configuration()); // Retrieve or create the row for this object. TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); size_t row_idx = table->find_first_string(m_schema.idx_identity, identity); if (row_idx == not_found) { if (!make_if_absent) { m_invalid = true; m_realm = nullptr; return; } m_realm->begin_transaction(); row_idx = table->find_first_string(m_schema.idx_identity, identity); if (row_idx == not_found) { row_idx = table->add_empty_row(); table->set_string(m_schema.idx_identity, row_idx, identity); m_realm->commit_transaction(); } else { // Someone beat us to adding this user. m_realm->cancel_transaction(); } } m_row = table->get(row_idx); m_invalid = m_row.get_bool(m_schema.idx_marked_for_removal); } bool SyncUserMetadata::is_valid() const { return !m_invalid; } std::string SyncUserMetadata::identity() const { m_realm->verify_thread(); StringData result = m_row.get_string(m_schema.idx_identity); return result; } util::Optional<std::string> SyncUserMetadata::get_optional_string_field(size_t col_idx) const { REALM_ASSERT(!m_invalid); m_realm->verify_thread(); StringData result = m_row.get_string(col_idx); return result.is_null() ? util::none : util::make_optional(std::string(result)); } util::Optional<std::string> SyncUserMetadata::server_url() const { return get_optional_string_field(m_schema.idx_auth_server_url); } util::Optional<std::string> SyncUserMetadata::user_token() const { return get_optional_string_field(m_schema.idx_user_token); } void SyncUserMetadata::set_state(util::Optional<std::string> server_url, util::Optional<std::string> user_token) { if (m_invalid) { return; } m_realm->verify_thread(); m_realm->begin_transaction(); m_row.set_string(m_schema.idx_user_token, *user_token); m_row.set_string(m_schema.idx_auth_server_url, *server_url); m_realm->commit_transaction(); } void SyncUserMetadata::mark_for_removal() { if (m_invalid) { return; } m_realm->verify_thread(); m_realm->begin_transaction(); m_row.set_bool(m_schema.idx_marked_for_removal, true); m_realm->commit_transaction(); } void SyncUserMetadata::remove() { m_invalid = true; m_realm->begin_transaction(); TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); table->move_last_over(m_row.get_index()); m_realm->commit_transaction(); m_realm = nullptr; } }
Remove an erroneous check
Remove an erroneous check
C++
apache-2.0
realm/realm-object-store,realm/realm-core,realm/realm-object-store,realm/realm-object-store,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core
db7223933628c475b5beb522cd8ec1e2e1a6f4b5
views/examples/native_theme_button_example.cc
views/examples/native_theme_button_example.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/examples/native_theme_button_example.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "ui/base/animation/throb_animation.h" #include "ui/base/models/combobox_model.h" #include "ui/gfx/canvas.h" #include "views/controls/label.h" #include "views/layout/grid_layout.h" #include "views/native_theme_painter.h" namespace { class ExampleComboboxModel : public ui::ComboboxModel { public: ExampleComboboxModel(const wchar_t** strings, int count) : strings_(strings), count_(count) { } ~ExampleComboboxModel() { } void set_data(const wchar_t** strings, int count) { strings_ = strings; count_ = count; } // Overridden from ui::ComboboxModel: virtual int GetItemCount() OVERRIDE { return count_; } virtual string16 GetItemAt(int index) OVERRIDE { return WideToUTF16Hack(strings_[index]); } private: const wchar_t** strings_; int count_; DISALLOW_COPY_AND_ASSIGN(ExampleComboboxModel); }; const wchar_t* kParts[] = { L"PushButton", L"RadioButton", L"Checkbox", }; const wchar_t* kStates[] = { L"Disabled", L"Normal", L"Hot", L"Pressed", L"<Dynamic>", }; } // anonymous namespace namespace examples { ExampleNativeThemeButton::ExampleNativeThemeButton( views::ButtonListener* listener, views::Combobox* cb_part, views::Combobox* cb_state) : CustomButton(listener), cb_part_(cb_part), cb_state_(cb_state), count_(0), is_checked_(false), is_indeterminate_(false) { cb_part_->set_listener(this); cb_state_->set_listener(this); painter_.reset(new views::NativeThemePainter(this)); set_background(views::Background::CreateBackgroundPainter( false, painter_.get())); } ExampleNativeThemeButton::~ExampleNativeThemeButton() { } std::string ExampleNativeThemeButton::MessWithState() { const char* message = NULL; switch(GetThemePart()) { case gfx::NativeTheme::kPushButton: message = "Pressed! count:%d"; break; case gfx::NativeTheme::kRadio: is_checked_ = !is_checked_; message = is_checked_ ? "Checked! count:%d" : "Unchecked! count:%d"; break; case gfx::NativeTheme::kCheckbox: if (is_indeterminate_) { is_checked_ = false; is_indeterminate_ = false; } else if (!is_checked_) { is_checked_ = true; } else { is_checked_ = false; is_indeterminate_ = true; } message = is_checked_ ? "Checked! count:%d" : is_indeterminate_ ? "Indeterminate! count:%d" : "Unchecked! count:%d"; break; default: DCHECK(false); } return base::StringPrintf(message, ++count_); } void ExampleNativeThemeButton::ItemChanged(views::Combobox* combo_box, int prev_index, int new_index) { SchedulePaint(); } gfx::NativeTheme::Part ExampleNativeThemeButton::GetThemePart() const { int selected = cb_part_->selected_item(); switch(selected) { case 0: return gfx::NativeTheme::kPushButton; case 1: return gfx::NativeTheme::kRadio; case 2: return gfx::NativeTheme::kCheckbox; default: DCHECK(false); } return gfx::NativeTheme::kPushButton; } gfx::Rect ExampleNativeThemeButton::GetThemePaintRect() const { gfx::NativeTheme::ExtraParams extra; gfx::NativeTheme::State state = GetThemeState(&extra); gfx::Size size(gfx::NativeTheme::instance()->GetPartSize(GetThemePart(), state, extra)); gfx::Rect rect(size); rect.set_x(GetMirroredXForRect(rect)); return rect; } gfx::NativeTheme::State ExampleNativeThemeButton::GetThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); int selected = cb_state_->selected_item(); if (selected > 3) { switch(state()) { case BS_DISABLED: return gfx::NativeTheme::kDisabled; case BS_NORMAL: return gfx::NativeTheme::kNormal; case BS_HOT: return gfx::NativeTheme::kHovered; case BS_PUSHED: return gfx::NativeTheme::kPressed; default: DCHECK(false); } } switch(selected) { case 0: return gfx::NativeTheme::kDisabled; case 1: return gfx::NativeTheme::kNormal; case 2: return gfx::NativeTheme::kHovered; case 3: return gfx::NativeTheme::kPressed; default: DCHECK(false); } return gfx::NativeTheme::kNormal; } void ExampleNativeThemeButton::GetExtraParams( gfx::NativeTheme::ExtraParams* params) const { params->button.checked = is_checked_; params->button.indeterminate = is_indeterminate_; params->button.is_default = false; params->button.has_border = false; params->button.classic_state = 0; params->button.background_color = SkColorSetARGB(0, 0, 0, 0); } const ui::Animation* ExampleNativeThemeButton::GetThemeAnimation() const { int selected = cb_state_->selected_item(); return selected <= 3 ? NULL : hover_animation_.get(); } gfx::NativeTheme::State ExampleNativeThemeButton::GetBackgroundThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return gfx::NativeTheme::kNormal; } gfx::NativeTheme::State ExampleNativeThemeButton::GetForegroundThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return gfx::NativeTheme::kHovered; } gfx::Size ExampleNativeThemeButton::GetPreferredSize() { return painter_.get() == NULL ? gfx::Size() : painter_->GetPreferredSize(); } void ExampleNativeThemeButton::OnPaintBackground(gfx::Canvas* canvas) { // Fill the background with a known colour so that we know where the bounds // of the View are. canvas->FillRectInt(SkColorSetRGB(255, 128, 128), 0, 0, width(), height()); CustomButton::OnPaintBackground(canvas); } //////////////////////////////////////////////////////////////////////////////// NativeThemeButtonExample::NativeThemeButtonExample(ExamplesMain* main) : ExampleBase(main) { } NativeThemeButtonExample::~NativeThemeButtonExample() { } std::wstring NativeThemeButtonExample::GetExampleTitle() { return L"Native Theme Button"; } void NativeThemeButtonExample::CreateExampleView(views::View* container) { views::GridLayout* layout = new views::GridLayout(container); container->SetLayoutManager(layout); layout->AddPaddingRow(0, 8); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddPaddingColumn(0, 8); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0.1f, views::GridLayout::USE_PREF, 0, 0); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0.9f, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 8); layout->StartRow(0, 0); layout->AddView(new views::Label(L"Part:")); views::Combobox* cb_part = new views::Combobox( new ExampleComboboxModel(kParts, arraysize(kParts))); cb_part->SetSelectedItem(0); layout->AddView(cb_part); layout->StartRow(0, 0); layout->AddView(new views::Label(L"State:")); views::Combobox* cb_state = new views::Combobox( new ExampleComboboxModel(kStates, arraysize(kStates))); cb_state->SetSelectedItem(0); layout->AddView(cb_state); layout->AddPaddingRow(0, 32); button_ = new ExampleNativeThemeButton(this, cb_part, cb_state); column_set = layout->AddColumnSet(1); column_set->AddPaddingColumn(0, 16); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 16); layout->StartRow(1, 1); layout->AddView(button_); layout->AddPaddingRow(0, 8); } void NativeThemeButtonExample::ButtonPressed(views::Button* sender, const views::Event& event) { PrintStatus(button_->MessWithState().c_str()); } } // namespace examples
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/examples/native_theme_button_example.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "ui/base/animation/throb_animation.h" #include "ui/base/models/combobox_model.h" #include "ui/gfx/canvas.h" #include "views/controls/label.h" #include "views/layout/grid_layout.h" #include "views/native_theme_painter.h" namespace { class ExampleComboboxModel : public ui::ComboboxModel { public: ExampleComboboxModel(const char** strings, int count) : strings_(strings), count_(count) { } virtual ~ExampleComboboxModel() {} // Overridden from ui::ComboboxModel: virtual int GetItemCount() OVERRIDE { return count_; } virtual string16 GetItemAt(int index) OVERRIDE { return ASCIIToUTF16(strings_[index]); } private: const char** strings_; int count_; DISALLOW_COPY_AND_ASSIGN(ExampleComboboxModel); }; const char* kParts[] = { "PushButton", "RadioButton", "Checkbox", }; const char* kStates[] = { "Disabled", "Normal", "Hot", "Pressed", "<Dynamic>", }; } // namespace namespace examples { ExampleNativeThemeButton::ExampleNativeThemeButton( views::ButtonListener* listener, views::Combobox* cb_part, views::Combobox* cb_state) : CustomButton(listener), cb_part_(cb_part), cb_state_(cb_state), count_(0), is_checked_(false), is_indeterminate_(false) { cb_part_->set_listener(this); cb_state_->set_listener(this); painter_.reset(new views::NativeThemePainter(this)); set_background(views::Background::CreateBackgroundPainter( false, painter_.get())); } ExampleNativeThemeButton::~ExampleNativeThemeButton() { } std::string ExampleNativeThemeButton::MessWithState() { const char* message = NULL; switch(GetThemePart()) { case gfx::NativeTheme::kPushButton: message = "Pressed! count:%d"; break; case gfx::NativeTheme::kRadio: is_checked_ = !is_checked_; message = is_checked_ ? "Checked! count:%d" : "Unchecked! count:%d"; break; case gfx::NativeTheme::kCheckbox: if (is_indeterminate_) { is_checked_ = false; is_indeterminate_ = false; } else if (!is_checked_) { is_checked_ = true; } else { is_checked_ = false; is_indeterminate_ = true; } message = is_checked_ ? "Checked! count:%d" : is_indeterminate_ ? "Indeterminate! count:%d" : "Unchecked! count:%d"; break; default: DCHECK(false); } return base::StringPrintf(message, ++count_); } void ExampleNativeThemeButton::ItemChanged(views::Combobox* combo_box, int prev_index, int new_index) { SchedulePaint(); } gfx::NativeTheme::Part ExampleNativeThemeButton::GetThemePart() const { int selected = cb_part_->selected_item(); switch(selected) { case 0: return gfx::NativeTheme::kPushButton; case 1: return gfx::NativeTheme::kRadio; case 2: return gfx::NativeTheme::kCheckbox; default: DCHECK(false); } return gfx::NativeTheme::kPushButton; } gfx::Rect ExampleNativeThemeButton::GetThemePaintRect() const { gfx::NativeTheme::ExtraParams extra; gfx::NativeTheme::State state = GetThemeState(&extra); gfx::Size size(gfx::NativeTheme::instance()->GetPartSize(GetThemePart(), state, extra)); gfx::Rect rect(size); rect.set_x(GetMirroredXForRect(rect)); return rect; } gfx::NativeTheme::State ExampleNativeThemeButton::GetThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); int selected = cb_state_->selected_item(); if (selected > 3) { switch(state()) { case BS_DISABLED: return gfx::NativeTheme::kDisabled; case BS_NORMAL: return gfx::NativeTheme::kNormal; case BS_HOT: return gfx::NativeTheme::kHovered; case BS_PUSHED: return gfx::NativeTheme::kPressed; default: DCHECK(false); } } switch(selected) { case 0: return gfx::NativeTheme::kDisabled; case 1: return gfx::NativeTheme::kNormal; case 2: return gfx::NativeTheme::kHovered; case 3: return gfx::NativeTheme::kPressed; default: DCHECK(false); } return gfx::NativeTheme::kNormal; } void ExampleNativeThemeButton::GetExtraParams( gfx::NativeTheme::ExtraParams* params) const { params->button.checked = is_checked_; params->button.indeterminate = is_indeterminate_; params->button.is_default = false; params->button.has_border = false; params->button.classic_state = 0; params->button.background_color = SkColorSetARGB(0, 0, 0, 0); } const ui::Animation* ExampleNativeThemeButton::GetThemeAnimation() const { int selected = cb_state_->selected_item(); return selected <= 3 ? NULL : hover_animation_.get(); } gfx::NativeTheme::State ExampleNativeThemeButton::GetBackgroundThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return gfx::NativeTheme::kNormal; } gfx::NativeTheme::State ExampleNativeThemeButton::GetForegroundThemeState( gfx::NativeTheme::ExtraParams* params) const { GetExtraParams(params); return gfx::NativeTheme::kHovered; } gfx::Size ExampleNativeThemeButton::GetPreferredSize() { return painter_.get() == NULL ? gfx::Size() : painter_->GetPreferredSize(); } void ExampleNativeThemeButton::OnPaintBackground(gfx::Canvas* canvas) { // Fill the background with a known colour so that we know where the bounds // of the View are. canvas->FillRectInt(SkColorSetRGB(255, 128, 128), 0, 0, width(), height()); CustomButton::OnPaintBackground(canvas); } //////////////////////////////////////////////////////////////////////////////// NativeThemeButtonExample::NativeThemeButtonExample(ExamplesMain* main) : ExampleBase(main) { } NativeThemeButtonExample::~NativeThemeButtonExample() { } std::wstring NativeThemeButtonExample::GetExampleTitle() { return L"Native Theme Button"; } void NativeThemeButtonExample::CreateExampleView(views::View* container) { views::GridLayout* layout = new views::GridLayout(container); container->SetLayoutManager(layout); layout->AddPaddingRow(0, 8); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddPaddingColumn(0, 8); column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 0.1f, views::GridLayout::USE_PREF, 0, 0); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0.9f, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 8); layout->StartRow(0, 0); layout->AddView(new views::Label(L"Part:")); views::Combobox* cb_part = new views::Combobox( new ExampleComboboxModel(kParts, arraysize(kParts))); cb_part->SetSelectedItem(0); layout->AddView(cb_part); layout->StartRow(0, 0); layout->AddView(new views::Label(L"State:")); views::Combobox* cb_state = new views::Combobox( new ExampleComboboxModel(kStates, arraysize(kStates))); cb_state->SetSelectedItem(0); layout->AddView(cb_state); layout->AddPaddingRow(0, 32); button_ = new ExampleNativeThemeButton(this, cb_part, cb_state); column_set = layout->AddColumnSet(1); column_set->AddPaddingColumn(0, 16); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 16); layout->StartRow(1, 1); layout->AddView(button_); layout->AddPaddingRow(0, 8); } void NativeThemeButtonExample::ButtonPressed(views::Button* sender, const views::Event& event) { PrintStatus(button_->MessWithState().c_str()); } } // namespace examples
Switch usages of wchar_t in ExampleComboboxModel to char type.
views/examples: Switch usages of wchar_t in ExampleComboboxModel to char type. [email protected] Review URL: http://codereview.chromium.org/7867035 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@100690 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,keishi/chromium,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,robclark/chromium,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,rogerwang/chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,littlstar/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,rogerwang/chromium,anirudhSK/chromium,Just-D/chromium-1,Just-D/chromium-1,rogerwang/chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,keishi/chromium,keishi/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,robclark/chromium,ChromiumWebApps/chromium,ltilve/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,robclark/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,robclark/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,rogerwang/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,Just-D/chromium-1,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,robclark/chromium,ltilve/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,keishi/chromium,dednal/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,Chilledheart/chromium,hujiajie/pa-chromium,Chilledheart/chromium,jaruba/chromium.src,keishi/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,dednal/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dednal/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,keishi/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,rogerwang/chromium,dednal/chromium.src,rogerwang/chromium,keishi/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,keishi/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,M4sse/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,robclark/chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,krieger-od/nwjs_chromium.src,rogerwang/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium
dbf7d2168631e6206d4a2ef9cd190e39675dfc22
Widgets/vtkAxesTransformRepresentation.cxx
Widgets/vtkAxesTransformRepresentation.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformRepresentation.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 "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkPolyDataMapper.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkVectorText.h" #include "vtkFollower.h" #include "vtkCamera.h" #include "vtkProperty.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkWindow.h" #include "vtkSmartPointer.h" #include "vtkBox.h" #include "vtkGlyph3D.h" #include "vtkCylinderSource.h" #include "vtkDoubleArray.h" #include "vtkPointData.h" #include "vtkTransformPolyDataFilter.h" #include "vtkTransform.h" #include "vtkSmartPointer.h" vtkStandardNewMacro(vtkAxesTransformRepresentation); //---------------------------------------------------------------------- vtkAxesTransformRepresentation::vtkAxesTransformRepresentation() { // By default, use one of these handles this->OriginRepresentation = vtkPointHandleRepresentation3D::New(); this->SelectionRepresentation = vtkPointHandleRepresentation3D::New(); // The line this->LinePoints = vtkPoints::New(); this->LinePoints->SetDataTypeToDouble(); this->LinePoints->SetNumberOfPoints(2); this->LinePolyData = vtkPolyData::New(); this->LinePolyData->SetPoints(this->LinePoints); vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New(); line->InsertNextCell(2); line->InsertCellPoint(0); line->InsertCellPoint(1); this->LinePolyData->SetLines(line); this->LineMapper = vtkPolyDataMapper::New(); this->LineMapper->SetInput(this->LinePolyData); this->LineActor = vtkActor::New(); this->LineActor->SetMapper(this->LineMapper); // The label this->LabelText = vtkVectorText::New(); this->LabelMapper = vtkPolyDataMapper::New(); this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort()); this->LabelActor = vtkFollower::New(); this->LabelActor->SetMapper(this->LabelMapper); // The tick marks this->GlyphPoints = vtkPoints::New(); this->GlyphPoints->SetDataTypeToDouble(); this->GlyphVectors = vtkDoubleArray::New(); this->GlyphVectors->SetNumberOfComponents(3); this->GlyphPolyData = vtkPolyData::New(); this->GlyphPolyData->SetPoints(this->GlyphPoints); this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors); this->GlyphCylinder = vtkCylinderSource::New(); this->GlyphCylinder->SetRadius(0.5); this->GlyphCylinder->SetHeight(0.1); this->GlyphCylinder->SetResolution(12); vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New(); this->GlyphXForm = vtkTransformPolyDataFilter::New(); this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort()); this->GlyphXForm->SetTransform(xform); xform->RotateZ(90); this->Glyph3D = vtkGlyph3D::New(); this->Glyph3D->SetInput(this->GlyphPolyData); this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort()); this->Glyph3D->SetScaleModeToDataScalingOff(); this->GlyphMapper = vtkPolyDataMapper::New(); this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort()); this->GlyphActor = vtkActor::New(); this->GlyphActor->SetMapper(this->GlyphMapper); // The bounding box this->BoundingBox = vtkBox::New(); this->LabelFormat = NULL; } //---------------------------------------------------------------------- vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation() { this->LinePoints->Delete(); this->LinePolyData->Delete(); this->LineMapper->Delete(); this->LineActor->Delete(); this->LabelText->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); if (this->LabelFormat) { delete [] this->LabelFormat; this->LabelFormat = NULL; } this->GlyphPoints->Delete(); this->GlyphVectors->Delete(); this->GlyphPolyData->Delete(); this->GlyphCylinder->Delete(); this->GlyphXForm->Delete(); this->Glyph3D->Delete(); this->GlyphMapper->Delete(); this->GlyphActor->Delete(); this->BoundingBox->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3]) { this->OriginRepresentation->GetWorldPosition(pos); } //---------------------------------------------------------------------- double* vtkAxesTransformRepresentation::GetOriginWorldPosition() { if (!this->OriginRepresentation) { static double temp[3]= {0, 0, 0}; return temp; } return this->OriginRepresentation->GetWorldPosition(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3]) { this->OriginRepresentation->SetDisplayPosition(x); double p[3]; this->OriginRepresentation->GetWorldPosition(p); this->OriginRepresentation->SetWorldPosition(p); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3]) { if (this->OriginRepresentation) { this->OriginRepresentation->SetWorldPosition(x); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3]) { this->OriginRepresentation->GetDisplayPosition(pos); pos[2] = 0.0; } //---------------------------------------------------------------------- double *vtkAxesTransformRepresentation::GetBounds() { this->BuildRepresentation(); this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->LineActor->GetBounds()); return this->BoundingBox->GetBounds(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2]) { // Store the start position this->StartEventPosition[0] = e[0]; this->StartEventPosition[1] = e[1]; this->StartEventPosition[2] = 0.0; // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; // Get the coordinates of the three handles // this->OriginRepresentation->GetWorldPosition(this->StartP1); // this->SelectionRepresentation->GetWorldPosition(this->StartP2); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::WidgetInteraction(double e[2]) { // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; } //---------------------------------------------------------------------------- int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // Check if we are on the origin. Use the handle to determine this. int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0); if ( p1State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkAxesTransformRepresentation::OnOrigin; // this->SetRepresentationState(vtkAxesTransformRepresentation::OnOrigin); } else { this->InteractionState = vtkAxesTransformRepresentation::Outside; } // Okay if we're near a handle return, otherwise test the line if ( this->InteractionState != vtkAxesTransformRepresentation::Outside ) { return this->InteractionState; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::BuildRepresentation() { if ( this->GetMTime() > this->BuildTime || this->OriginRepresentation->GetMTime() > this->BuildTime || this->SelectionRepresentation->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) ) { this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation:: ReleaseGraphicsResources(vtkWindow *w) { this->LineActor->ReleaseGraphicsResources(w); this->LabelActor->ReleaseGraphicsResources(w); this->GlyphActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderOpaqueGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderOpaqueGeometry(v); this->LabelActor->RenderOpaqueGeometry(v); this->GlyphActor->RenderOpaqueGeometry(v); return 3; } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderTranslucentPolygonalGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderTranslucentPolygonalGeometry(v); this->LabelActor->RenderTranslucentPolygonalGeometry(v); this->GlyphActor->RenderTranslucentPolygonalGeometry(v); return 3; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] ) { this->LabelActor->SetScale( scale ); } //---------------------------------------------------------------------- double * vtkAxesTransformRepresentation::GetLabelScale() { return this->LabelActor->GetScale(); } //---------------------------------------------------------------------------- vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty() { return this->LabelActor->GetProperty(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Label Format: "; if ( this->LabelFormat ) { os << this->LabelFormat << endl; } else { os << "(none)\n"; } os << indent << "Tolerance: " << this->Tolerance << endl; os << indent << "InteractionState: " << this->InteractionState << endl; os << indent << "Origin Representation: "; if ( this->OriginRepresentation ) { this->OriginRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Selection Representation: " << endl; if ( this->SelectionRepresentation ) { this->SelectionRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } this->Superclass::PrintSelf(os,indent); }
/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformRepresentation.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 "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkPolyDataMapper.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkVectorText.h" #include "vtkFollower.h" #include "vtkCamera.h" #include "vtkProperty.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkWindow.h" #include "vtkSmartPointer.h" #include "vtkBox.h" #include "vtkGlyph3D.h" #include "vtkCylinderSource.h" #include "vtkDoubleArray.h" #include "vtkPointData.h" #include "vtkTransformPolyDataFilter.h" #include "vtkTransform.h" #include "vtkSmartPointer.h" vtkStandardNewMacro(vtkAxesTransformRepresentation); //---------------------------------------------------------------------- vtkAxesTransformRepresentation::vtkAxesTransformRepresentation() { // By default, use one of these handles this->OriginRepresentation = vtkPointHandleRepresentation3D::New(); this->SelectionRepresentation = vtkPointHandleRepresentation3D::New(); // The line this->LinePoints = vtkPoints::New(); this->LinePoints->SetDataTypeToDouble(); this->LinePoints->SetNumberOfPoints(2); this->LinePolyData = vtkPolyData::New(); this->LinePolyData->SetPoints(this->LinePoints); vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New(); line->InsertNextCell(2); line->InsertCellPoint(0); line->InsertCellPoint(1); this->LinePolyData->SetLines(line); this->LineMapper = vtkPolyDataMapper::New(); this->LineMapper->SetInput(this->LinePolyData); this->LineActor = vtkActor::New(); this->LineActor->SetMapper(this->LineMapper); // The label this->LabelText = vtkVectorText::New(); this->LabelMapper = vtkPolyDataMapper::New(); this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort()); this->LabelActor = vtkFollower::New(); this->LabelActor->SetMapper(this->LabelMapper); // The tick marks this->GlyphPoints = vtkPoints::New(); this->GlyphPoints->SetDataTypeToDouble(); this->GlyphVectors = vtkDoubleArray::New(); this->GlyphVectors->SetNumberOfComponents(3); this->GlyphPolyData = vtkPolyData::New(); this->GlyphPolyData->SetPoints(this->GlyphPoints); this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors); this->GlyphCylinder = vtkCylinderSource::New(); this->GlyphCylinder->SetRadius(0.5); this->GlyphCylinder->SetHeight(0.1); this->GlyphCylinder->SetResolution(12); vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New(); this->GlyphXForm = vtkTransformPolyDataFilter::New(); this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort()); this->GlyphXForm->SetTransform(xform); xform->RotateZ(90); this->Glyph3D = vtkGlyph3D::New(); this->Glyph3D->SetInput(this->GlyphPolyData); this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort()); this->Glyph3D->SetScaleModeToDataScalingOff(); this->GlyphMapper = vtkPolyDataMapper::New(); this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort()); this->GlyphActor = vtkActor::New(); this->GlyphActor->SetMapper(this->GlyphMapper); // The bounding box this->BoundingBox = vtkBox::New(); this->LabelFormat = NULL; } //---------------------------------------------------------------------- vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation() { this->LinePoints->Delete(); this->LinePolyData->Delete(); this->LineMapper->Delete(); this->LineActor->Delete(); this->LabelText->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); if (this->LabelFormat) { delete [] this->LabelFormat; this->LabelFormat = NULL; } this->GlyphPoints->Delete(); this->GlyphVectors->Delete(); this->GlyphPolyData->Delete(); this->GlyphCylinder->Delete(); this->GlyphXForm->Delete(); this->Glyph3D->Delete(); this->GlyphMapper->Delete(); this->GlyphActor->Delete(); this->BoundingBox->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3]) { this->OriginRepresentation->GetWorldPosition(pos); } //---------------------------------------------------------------------- double* vtkAxesTransformRepresentation::GetOriginWorldPosition() { if (!this->OriginRepresentation) { static double temp[3]= {0, 0, 0}; return temp; } return this->OriginRepresentation->GetWorldPosition(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3]) { this->OriginRepresentation->SetDisplayPosition(x); double p[3]; this->OriginRepresentation->GetWorldPosition(p); this->OriginRepresentation->SetWorldPosition(p); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3]) { if (this->OriginRepresentation) { this->OriginRepresentation->SetWorldPosition(x); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3]) { this->OriginRepresentation->GetDisplayPosition(pos); pos[2] = 0.0; } //---------------------------------------------------------------------- double *vtkAxesTransformRepresentation::GetBounds() { this->BuildRepresentation(); this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->LineActor->GetBounds()); return this->BoundingBox->GetBounds(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2]) { // Store the start position this->StartEventPosition[0] = e[0]; this->StartEventPosition[1] = e[1]; this->StartEventPosition[2] = 0.0; // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; // Get the coordinates of the three handles // this->OriginRepresentation->GetWorldPosition(this->StartP1); // this->SelectionRepresentation->GetWorldPosition(this->StartP2); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::WidgetInteraction(double e[2]) { // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; } //---------------------------------------------------------------------------- int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // Check if we are on the origin. Use the handle to determine this. int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0); if ( p1State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkAxesTransformRepresentation::OnOrigin; } else { this->InteractionState = vtkAxesTransformRepresentation::Outside; } // Okay if we're near a handle return, otherwise test the line if ( this->InteractionState != vtkAxesTransformRepresentation::Outside ) { return this->InteractionState; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::BuildRepresentation() { if ( this->GetMTime() > this->BuildTime || this->OriginRepresentation->GetMTime() > this->BuildTime || this->SelectionRepresentation->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) ) { this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation:: ReleaseGraphicsResources(vtkWindow *w) { this->LineActor->ReleaseGraphicsResources(w); this->LabelActor->ReleaseGraphicsResources(w); this->GlyphActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderOpaqueGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderOpaqueGeometry(v); this->LabelActor->RenderOpaqueGeometry(v); this->GlyphActor->RenderOpaqueGeometry(v); return 3; } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderTranslucentPolygonalGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderTranslucentPolygonalGeometry(v); this->LabelActor->RenderTranslucentPolygonalGeometry(v); this->GlyphActor->RenderTranslucentPolygonalGeometry(v); return 3; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] ) { this->LabelActor->SetScale( scale ); } //---------------------------------------------------------------------- double * vtkAxesTransformRepresentation::GetLabelScale() { return this->LabelActor->GetScale(); } //---------------------------------------------------------------------------- vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty() { return this->LabelActor->GetProperty(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Label Format: "; if ( this->LabelFormat ) { os << this->LabelFormat << endl; } else { os << "(none)\n"; } os << indent << "Tolerance: " << this->Tolerance << endl; os << indent << "InteractionState: " << this->InteractionState << endl; os << indent << "Origin Representation: "; if ( this->OriginRepresentation ) { this->OriginRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Selection Representation: " << endl; if ( this->SelectionRepresentation ) { this->SelectionRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } this->Superclass::PrintSelf(os,indent); }
Remove commented out code.
Remove commented out code. Change-Id: I4a7dfdf2d0a51d1b0f1595b068b46cbc7057e75f
C++
bsd-3-clause
gram526/VTK,spthaolt/VTK,SimVascular/VTK,ashray/VTK-EVM,aashish24/VTK-old,aashish24/VTK-old,hendradarwin/VTK,aashish24/VTK-old,johnkit/vtk-dev,johnkit/vtk-dev,msmolens/VTK,gram526/VTK,SimVascular/VTK,candy7393/VTK,daviddoria/PointGraphsPhase1,sankhesh/VTK,demarle/VTK,biddisco/VTK,berendkleinhaneveld/VTK,mspark93/VTK,demarle/VTK,mspark93/VTK,daviddoria/PointGraphsPhase1,keithroe/vtkoptix,ashray/VTK-EVM,cjh1/VTK,sankhesh/VTK,biddisco/VTK,keithroe/vtkoptix,sankhesh/VTK,gram526/VTK,demarle/VTK,ashray/VTK-EVM,sankhesh/VTK,ashray/VTK-EVM,msmolens/VTK,johnkit/vtk-dev,keithroe/vtkoptix,gram526/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,candy7393/VTK,biddisco/VTK,demarle/VTK,johnkit/vtk-dev,SimVascular/VTK,sumedhasingla/VTK,candy7393/VTK,biddisco/VTK,candy7393/VTK,sankhesh/VTK,mspark93/VTK,mspark93/VTK,mspark93/VTK,spthaolt/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,collects/VTK,sankhesh/VTK,ashray/VTK-EVM,johnkit/vtk-dev,jmerkow/VTK,hendradarwin/VTK,keithroe/vtkoptix,keithroe/vtkoptix,berendkleinhaneveld/VTK,SimVascular/VTK,sankhesh/VTK,biddisco/VTK,spthaolt/VTK,berendkleinhaneveld/VTK,candy7393/VTK,spthaolt/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,gram526/VTK,collects/VTK,sumedhasingla/VTK,SimVascular/VTK,keithroe/vtkoptix,SimVascular/VTK,candy7393/VTK,jmerkow/VTK,msmolens/VTK,spthaolt/VTK,collects/VTK,cjh1/VTK,hendradarwin/VTK,candy7393/VTK,jmerkow/VTK,msmolens/VTK,collects/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,mspark93/VTK,keithroe/vtkoptix,cjh1/VTK,sankhesh/VTK,collects/VTK,ashray/VTK-EVM,aashish24/VTK-old,msmolens/VTK,aashish24/VTK-old,ashray/VTK-EVM,johnkit/vtk-dev,gram526/VTK,msmolens/VTK,sumedhasingla/VTK,cjh1/VTK,hendradarwin/VTK,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,aashish24/VTK-old,spthaolt/VTK,gram526/VTK,jmerkow/VTK,johnkit/vtk-dev,gram526/VTK,candy7393/VTK,mspark93/VTK,demarle/VTK,demarle/VTK,cjh1/VTK,demarle/VTK,cjh1/VTK,sumedhasingla/VTK,demarle/VTK,sumedhasingla/VTK,hendradarwin/VTK,collects/VTK,spthaolt/VTK,jmerkow/VTK,jmerkow/VTK,sumedhasingla/VTK,jmerkow/VTK,hendradarwin/VTK,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,ashray/VTK-EVM,msmolens/VTK,keithroe/vtkoptix,mspark93/VTK,berendkleinhaneveld/VTK,biddisco/VTK,biddisco/VTK,berendkleinhaneveld/VTK
5a5ca4812e574b84238e72566d5d358cc62a25f7
tests/examples.hh
tests/examples.hh
#ifndef EXAMPLES_HH #define EXAMPLES_HH #include <maya/MPxLocatorNode.h> #include <maya/MPxCommand.h> #include <maya/MSyntax.h> class Locator : public MPxLocatorNode { public: static MTypeId id; static void* creator() { return new Locator; } static MStatus initialize() { return MS::kSuccess; } }; class FullOpinionatedLocator : public MPxLocatorNode { public: static MTypeId id; static void* creator() { return new FullOpinionatedLocator; } static MStatus initialize() { return MS::kSuccess; } static MString nodeName; static MPxNode::Type nodeType; static MString classification; }; class PartialOpinionatedNode : public MPxNode { public: static MTypeId id; static void* creator() { return new PartialOpinionatedNode; } static MStatus initialize() { return MS::kSuccess; } static MString nodeName; }; class Command : public MPxCommand { public: static void* creator() { return new Locator; } static MSyntax syntaxCreator() { return MSyntax(); } static MString commandName; }; #endif // EXAMPLES_HH
#ifndef EXAMPLES_HH #define EXAMPLES_HH #include <maya/MPxLocatorNode.h> #include <maya/MPxCommand.h> #include <maya/MSyntax.h> class Locator : public MPxLocatorNode { public: static MTypeId id; static void* creator() { return new Locator; } static MStatus initialize() { return MS::kSuccess; } }; class FullOpinionatedLocator : public MPxLocatorNode { public: static MTypeId id; static void* creator() { return new FullOpinionatedLocator; } static MStatus initialize() { return MS::kSuccess; } static MString nodeName; static MPxNode::Type nodeType; static MString classification; }; class PartialOpinionatedNode : public MPxNode { public: static MTypeId id; static void* creator() { return new PartialOpinionatedNode; } static MStatus initialize() { return MS::kSuccess; } static MString nodeName; }; class Command : public MPxCommand { public: static void* creator() { return new Command; } static MSyntax syntaxCreator() { return MSyntax(); } static MString commandName; }; #endif // EXAMPLES_HH
Fix incorrect creator function
Fix incorrect creator function
C++
bsd-3-clause
michaeljones/maya-plugin-handler
3e3981fb3953fd3d97cfd3f27effc756540ae841
ferocious/main.cpp
ferocious/main.cpp
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setApplicationVersion(APP_VERSION); // activate anti-aliasing on all fonts: QFont font = QApplication::font(); font.setStyleStrategy(QFont::PreferAntialias); a.setFont(font); // retrieve and apply factory Stylesheet: QFile ss(":/ferocious.qss"); if(ss.open(QIODevice::ReadOnly | QIODevice::Text)){ a.setStyleSheet(ss.readAll()); ss.close(); }else{ qDebug() << "Couldn't open stylesheet resource"; } MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setApplicationVersion(APP_VERSION); // activate anti-aliasing on all fonts: QFont font = QApplication::font(); font.setStyleStrategy(QFont::PreferAntialias); a.setFont(font); // retrieve and apply factory Stylesheet: QFile ss(":/ferocious.qss"); if(ss.open(QIODevice::ReadOnly | QIODevice::Text)){ a.setStyleSheet(ss.readAll()); ss.close(); } else { qDebug() << "Couldn't open stylesheet resource"; } MainWindow w; w.show(); return a.exec(); }
clean whitespace
clean whitespace
C++
lgpl-2.1
jniemann66/ferocious
626331b7ecc9a3e4eac8d12d5b0c5a62c7916775
matrix/mem_worker_thread.cpp
matrix/mem_worker_thread.cpp
/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * 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 <unordered_map> #include "io_interface.h" #include "matrix_config.h" #include "mem_worker_thread.h" #include "EM_object.h" #include "local_mem_buffer.h" namespace fm { namespace detail { mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node) { tot_num_tasks = 0; threads.resize(num_nodes); for (int i = 0; i < num_nodes; i++) { threads[i].resize(nthreads_per_node); for (int j = 0; j < nthreads_per_node; j++) { std::string name = std::string("mem-worker-") + itoa(i) + "-" + itoa(j); threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); threads[i][j]->start(); } } ntasks_per_node.resize(num_nodes); } /* * This method dispatches tasks in a round-robin fashion. */ void mem_thread_pool::process_task(int node_id, thread_task *task) { if (node_id < 0) node_id = tot_num_tasks % get_num_nodes(); assert((size_t) node_id < threads.size()); size_t idx = ntasks_per_node[node_id] % threads[node_id].size(); threads[node_id][idx]->add_task(task); ntasks_per_node[node_id]++; tot_num_tasks++; } void mem_thread_pool::wait4complete() { for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) threads[i][j]->wait4complete(); } // After all workers complete, we should try to clear the memory buffers // in each worker thread to reduce memory consumption. detail::local_mem_buffer::clear_bufs(); } size_t mem_thread_pool::get_num_pending() const { size_t ret = 0; for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) ret += threads[i][j]->get_num_pending(); } return ret; } static mem_thread_pool::ptr global_threads; mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads() { if (global_threads == NULL) { int nthreads_per_node = matrix_conf.get_num_threads() / matrix_conf.get_num_nodes(); assert(nthreads_per_node > 0); global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(), nthreads_per_node); } return global_threads; } void mem_thread_pool::init_global_mem_threads(int num_nodes, int nthreads_per_node) { if (global_threads == NULL) global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node); } void io_worker_task::run() { std::vector<safs::io_interface::ptr> ios; pthread_spin_lock(&lock); for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) { std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios(); ios.insert(ios.end(), tmp.begin(), tmp.end()); } pthread_spin_unlock(&lock); // The task runs until there are no tasks left in the queue. while (dispatch->issue_task()) { for (size_t i = 0; i < ios.size(); i++) { ios[i]->wait4complete(0); while (ios[i]->num_pending_ios() > max_pending_ios) ios[i]->wait4complete(1); } } // Test if all I/O instances have processed all requests. size_t num_pending; do { for (size_t i = 0; i < ios.size(); i++) { ios[i]->wait4complete(0); // If there is still an I/O instance has pending requests, // we need to start over and test all I/O instances again. if (ios[i]->num_pending_ios() > 0) ios[i]->wait4complete(1); } // Test if all I/O instances have pending I/O requests left. // When a portion of a matrix is ready in memory and being processed, // it may result in writing data to another matrix. Therefore, we // need to process all completed I/O requests (portions with data // in memory) first and then count the number of new pending I/Os. num_pending = 0; for (size_t i = 0; i < ios.size(); i++) num_pending += ios[i]->num_pending_ios(); } while (num_pending > 0); pthread_spin_lock(&lock); EM_objs.clear(); pthread_spin_unlock(&lock); for (size_t i = 0; i < ios.size(); i++) { portion_callback &cb = static_cast<portion_callback &>( ios[i]->get_callback()); assert(!cb.has_callback()); } } } }
/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * 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 <unordered_map> #include "io_interface.h" #include "matrix_config.h" #include "mem_worker_thread.h" #include "EM_object.h" #include "local_mem_buffer.h" namespace fm { namespace detail { mem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node) { tot_num_tasks = 0; threads.resize(num_nodes); for (int i = 0; i < num_nodes; i++) { threads[i].resize(nthreads_per_node); for (int j = 0; j < nthreads_per_node; j++) { std::string name = std::string("mem-worker-") + itoa(i) + "-" + itoa(j); threads[i][j] = std::shared_ptr<pool_task_thread>( new pool_task_thread(i * nthreads_per_node + j, name, i)); threads[i][j]->start(); } } ntasks_per_node.resize(num_nodes); } /* * This method dispatches tasks in a round-robin fashion. */ void mem_thread_pool::process_task(int node_id, thread_task *task) { if (node_id < 0) node_id = tot_num_tasks % get_num_nodes(); assert((size_t) node_id < threads.size()); size_t idx = ntasks_per_node[node_id] % threads[node_id].size(); threads[node_id][idx]->add_task(task); ntasks_per_node[node_id]++; tot_num_tasks++; } void mem_thread_pool::wait4complete() { for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) threads[i][j]->wait4complete(); } // After all workers complete, we should try to clear the memory buffers // in each worker thread to reduce memory consumption. detail::local_mem_buffer::clear_bufs(); } size_t mem_thread_pool::get_num_pending() const { size_t ret = 0; for (size_t i = 0; i < threads.size(); i++) { size_t nthreads = threads[i].size(); for (size_t j = 0; j < nthreads; j++) ret += threads[i][j]->get_num_pending(); } return ret; } static mem_thread_pool::ptr global_threads; mem_thread_pool::ptr mem_thread_pool::get_global_mem_threads() { if (global_threads == NULL) { int nthreads_per_node = matrix_conf.get_num_threads() / matrix_conf.get_num_nodes(); assert(nthreads_per_node > 0); global_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(), nthreads_per_node); } return global_threads; } void mem_thread_pool::init_global_mem_threads(int num_nodes, int nthreads_per_node) { if (global_threads == NULL) global_threads = mem_thread_pool::create(num_nodes, nthreads_per_node); } static size_t wait4ios(const std::vector<safs::io_interface::ptr> &ios, size_t max_pending_ios) { size_t num_pending; do { num_pending = 0; for (size_t i = 0; i < ios.size(); i++) num_pending += ios[i]->num_pending_ios(); // Figure out how many I/O requests we have to wait for in // this iteration. int num_to_process; if (num_pending > max_pending_ios) num_to_process = num_pending - max_pending_ios; else num_to_process = 0; for (size_t i = 0; i < ios.size(); i++) { int ret = ios[i]->wait4complete(0); assert(ret >= 0); num_to_process -= ret; if (ios[i]->num_pending_ios() > 0 && num_to_process > 0) { ret = ios[i]->wait4complete(1); assert(ret >= 1); num_to_process -= ret; } } // Test if all I/O instances have pending I/O requests left. // When a portion of a matrix is ready in memory and being processed, // it may result in writing data to another matrix. Therefore, we // need to process all completed I/O requests (portions with data // in memory) first and then count the number of new pending I/Os. num_pending = 0; for (size_t i = 0; i < ios.size(); i++) num_pending += ios[i]->num_pending_ios(); } while (num_pending > max_pending_ios); return num_pending; } void io_worker_task::run() { std::vector<safs::io_interface::ptr> ios; pthread_spin_lock(&lock); for (auto it = EM_objs.begin(); it != EM_objs.end(); it++) { std::vector<safs::io_interface::ptr> tmp = (*it)->create_ios(); ios.insert(ios.end(), tmp.begin(), tmp.end()); } pthread_spin_unlock(&lock); // The task runs until there are no tasks left in the queue. while (dispatch->issue_task()) wait4ios(ios, max_pending_ios); // Test if all I/O instances have processed all requests. size_t num_pending = wait4ios(ios, 0); assert(num_pending == 0); pthread_spin_lock(&lock); EM_objs.clear(); pthread_spin_unlock(&lock); for (size_t i = 0; i < ios.size(); i++) { portion_callback &cb = static_cast<portion_callback &>( ios[i]->get_callback()); assert(!cb.has_callback()); } } } }
fix a bug in wait 4 IOs in io_worker_task.
[Matrix]: fix a bug in wait 4 IOs in io_worker_task.
C++
apache-2.0
zheng-da/FlashX,flashxio/FlashX,icoming/FlashX,icoming/FlashGraph,flashxio/FlashX,zheng-da/FlashX,icoming/FlashGraph,flashxio/FlashX,icoming/FlashX,flashxio/FlashX,zheng-da/FlashX,zheng-da/FlashX,icoming/FlashGraph,icoming/FlashX,flashxio/FlashX,icoming/FlashGraph,flashxio/FlashX,icoming/FlashGraph,zheng-da/FlashX,icoming/FlashX,icoming/FlashX
d6c1eaf01a94b36f6974624fbce8d321e35d991e
tests/test_10.cpp
tests/test_10.cpp
#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <tiramisu/debug.h> #include <tiramisu/core.h> #include <string.h> #include <Halide.h> #define AUTOMATIC_VECTORIATION 1 using namespace tiramisu; void generate_function_1(std::string name, int size, int val0) { tiramisu::global::set_default_tiramisu_options(); tiramisu::function function0(name); int Msize = 2*floor(size/2); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0); tiramisu::constant M("M", tiramisu::expr((int32_t) Msize), p_int32, true, NULL, 0, &function0); tiramisu::buffer buf0("buf0", 2, {size,size}, tiramisu::p_uint8, NULL, a_output, &function0); #if AUTOMATIC_VECTORIATION tiramisu::expr e1 = tiramisu::expr((uint8_t) val0); tiramisu::computation S0("[N,M]->{S0[i,j]: 0<=i<N and 0<=j<N}", e1, true, p_uint8, &function0); S0.set_access("[N,M]->{S0[i,j]->buf0[i,j]: 0<=i<N and 0<=j<N}"); S0.vectorize(1, 2, tiramisu::var(p_int32, "N")); #else function0.set_context_set("[N,M]->{:N>0 and M>0 and M%2=0 and M<=N}"); tiramisu::expr e1 = tiramisu::expr((uint8_t) val0); tiramisu::expr e2 = tiramisu::expr((uint8_t) val0); tiramisu::computation S0("[N,M]->{S0[i,j]: 0<=i<N and 0<=j<M}", e1, true, p_uint8, &function0); tiramisu::computation S0P("[N,M]->{S0P[i,j]: 0<=i<N and M<=j<N}", e2, true, p_uint8, &function0); S0.set_access("[N,M]->{S0[i,j]->buf0[i,j]: 0<=i<N and 0<=j<N}"); S0P.set_access("[N,M]->{S0P[i,j]->buf0[i,j]: 0<=i<N and 0<=j<N}"); S0.split(3,2); S0.tag_vector_dimension(2); S0P.set_schedule("[N,M]->{S0P[i,j]->S0P[1,i,0,j,0,0,0]: 0<=i<N and M<=j<N}"); #endif function0.set_arguments({&buf0}); function0.gen_time_processor_domain(); function0.gen_isl_ast(); function0.gen_halide_stmt(); function0.gen_halide_obj("build/generated_fct_test_10.o"); } int main(int argc, char **argv) { generate_function_1("assign_7_to_10x10_2D_array_with_vectorization", 32, 7); return 0; }
#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <tiramisu/debug.h> #include <tiramisu/core.h> #include <string.h> #include <Halide.h> using namespace tiramisu; void generate_function_1(std::string name, int size, int val0) { tiramisu::global::set_default_tiramisu_options(); tiramisu::function function0(name); int Msize = 2*floor(size/2); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0); tiramisu::constant M("M", tiramisu::expr((int32_t) Msize), p_int32, true, NULL, 0, &function0); tiramisu::buffer buf0("buf0", 2, {size,size}, tiramisu::p_uint8, NULL, a_output, &function0); tiramisu::expr e1 = tiramisu::expr((uint8_t) val0); tiramisu::computation S0("[N,M]->{S0[i,j]: 0<=i<N and 0<=j<N}", e1, true, p_uint8, &function0); S0.set_access("[N,M]->{S0[i,j]->buf0[i,j]: 0<=i<N and 0<=j<N}"); S0.vectorize(1, 2, tiramisu::var(p_int32, "N")); function0.set_arguments({&buf0}); function0.gen_time_processor_domain(); function0.gen_isl_ast(); function0.gen_halide_stmt(); function0.gen_halide_obj("build/generated_fct_test_10.o"); } int main(int argc, char **argv) { generate_function_1("assign_7_to_10x10_2D_array_with_vectorization", 32, 7); return 0; }
Remove deprecated code from test10
Remove deprecated code from test10
C++
mit
rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/COLi
382de274d5ab0df168dd1527ed20665ffc604a34
protocols/irc/ircservercontact.cpp
protocols/irc/ircservercontact.cpp
/* ircservercontact.cpp - IRC Server Contact Copyright (c) 2003 by Michel Hermier <[email protected]> Copyright (c) 2002 by Nick Betcher <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "ircusercontact.h" #include "ircservercontact.h" #include "ircaccount.h" #include "ircprotocol.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include <kaction.h> #include <kdebug.h> #include <klocale.h> #include <qtimer.h> IRCServerContact::IRCServerContact(IRCContactManager *contactManager, const QString &servername, Kopete::MetaContact *m) : IRCContact(contactManager, servername, m, "irc_server") { KIRC::Engine *engine = kircEngine(); QObject::connect(engine, SIGNAL(internalError(KIRC::Engine::Error, KIRC::Message &)), this, SLOT(engineInternalError(KIRC::Engine::Error, KIRC::Message &))); /* //FIXME: Have some kind of a debug option for raw input/ouput display?? QObject::connect(engine, SIGNAL(sentMessage(KIRC::Message &)), this, SLOT(engineSentMessage(KIRC::Message &))); QObject::connect(engine, SIGNAL(receivedMessage(KIRC::Message &)), this, SLOT(engineReceivedMessage(KIRC::Message &))); */ QObject::connect(engine, SIGNAL(incomingNotice(const QString &, const QString &)), this, SLOT(slotIncomingNotice(const QString &, const QString &))); QObject::connect(engine, SIGNAL(incomingCannotSendToChannel(const QString &, const QString &)), this, SLOT(slotCannotSendToChannel(const QString &, const QString &))); QObject::connect(engine, SIGNAL(incomingUnknown(const QString &)), this, SLOT(slotIncomingUnknown(const QString &))); QObject::connect(engine, SIGNAL(incomingConnectString(const QString &)), this, SLOT(slotIncomingConnect(const QString &))); QObject::connect(engine, SIGNAL(incomingMotd(const QString &)), this, SLOT(slotIncomingMotd(const QString &))); QObject::connect(Kopete::ChatSessionManager::self(), SIGNAL(viewCreated(KopeteView*)), this, SLOT(slotViewCreated(KopeteView*)) ); updateStatus(); } void IRCServerContact::updateStatus() { KIRC::Engine::Status status = kircEngine()->status(); switch( status ) { case KIRC::Engine::Idle: case KIRC::Engine::Connecting: if( m_chatSession ) m_chatSession->setDisplayName( caption() ); setOnlineStatus( m_protocol->m_ServerStatusOffline ); break; case KIRC::Engine::Authentifying: case KIRC::Engine::Connected: case KIRC::Engine::Closing: // should make some extra check here setOnlineStatus( m_protocol->m_ServerStatusOnline ); break; default: setOnlineStatus( m_protocol->m_StatusUnknown ); } } const QString IRCServerContact::caption() const { return i18n("%1 @ %2").arg(ircAccount()->mySelf()->nickName() ).arg( kircEngine()->currentHost().isEmpty() ? ircAccount()->networkName() : kircEngine()->currentHost() ); } void IRCServerContact::engineInternalError(KIRC::Engine::Error engineError, KIRC::Message &ircmsg) { QString error; switch (engineError) { case KIRC::Engine::ParsingFailed: error = i18n("KIRC Error - Parse error: "); break; case KIRC::Engine::UnknownCommand: error = i18n("KIRC Error - Unknown command: "); break; case KIRC::Engine::UnknownNumericReply: error = i18n("KIRC Error - Unknown numeric reply: "); break; case KIRC::Engine::InvalidNumberOfArguments: error = i18n("KIRC Error - Invalid number of arguments: "); break; case KIRC::Engine::MethodFailed: error = i18n("KIRC Error - Method failed: "); break; default: error = i18n("KIRC Error - Unknown error: "); } ircAccount()->appendMessage(error + QString(ircmsg.raw()), IRCAccount::ErrorReply); } void IRCServerContact::slotSendMsg(Kopete::Message &, Kopete::ChatSession *manager) { manager->messageSucceeded(); Kopete::Message msg( manager->myself(), manager->members(), i18n("You can not talk to the server, you can only issue commands here. Type /help for supported commands."), Kopete::Message::Internal, Kopete::Message::PlainText, CHAT_VIEW); manager->appendMessage(msg); } void IRCServerContact::appendMessage( const QString &message ) { Kopete::ContactPtrList members; members.append( this ); Kopete::Message msg( this, members, message, Kopete::Message::Internal, Kopete::Message::RichText, CHAT_VIEW ); appendMessage(msg); } void IRCServerContact::slotIncomingNotice( const QString &orig, const QString &notice ) { QString originator = orig.contains('!') ? orig.section('!',0,1) : orig; ircAccount()->appendMessage( i18n("NOTICE from %1: %2").arg( originator == ircAccount()->mySelf()->nickName() ? kircEngine()->currentHost() : originator, notice ), IRCAccount::NoticeReply ); } void IRCServerContact::slotIncomingUnknown(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::UnknownReply); } void IRCServerContact::slotIncomingConnect(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::ConnectReply); } void IRCServerContact::slotIncomingMotd(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::InfoReply); } void IRCServerContact::slotCannotSendToChannel(const QString &channel, const QString &message) { ircAccount()->appendMessage(QString::fromLatin1("%1: %2").arg(channel).arg(message), IRCAccount::ErrorReply); } void IRCServerContact::appendMessage(Kopete::Message &msg) { msg.setImportance( Kopete::Message::Low ); //to don't distrub the user if (m_chatSession && m_chatSession->view(false)) m_chatSession->appendMessage(msg); else mMsgBuffer.append( msg ); } void IRCServerContact::slotDumpMessages() { if (!mMsgBuffer.isEmpty()) { manager()->appendMessage( mMsgBuffer.front() ); mMsgBuffer.pop_front(); QTimer::singleShot( 0, this, SLOT( slotDumpMessages() ) ); } } void IRCServerContact::slotViewCreated( KopeteView *v ) { kdDebug(14121) << k_funcinfo << "Created: " << v << ", mgr: " << v->msgManager() << ", Mine: " << m_chatSession << endl; if (m_chatSession && v->msgManager() == m_chatSession) QTimer::singleShot(500, this, SLOT(slotDumpMessages())); } #include "ircservercontact.moc"
/* ircservercontact.cpp - IRC Server Contact Copyright (c) 2003 by Michel Hermier <[email protected]> Copyright (c) 2002 by Nick Betcher <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "ircusercontact.h" #include "ircservercontact.h" #include "ircaccount.h" #include "ircprotocol.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include <kaction.h> #include <kdebug.h> #include <klocale.h> #include <qtimer.h> IRCServerContact::IRCServerContact(IRCContactManager *contactManager, const QString &servername, Kopete::MetaContact *m) : IRCContact(contactManager, servername, m, "irc_server") { KIRC::Engine *engine = kircEngine(); QObject::connect(engine, SIGNAL(internalError(KIRC::Engine::Error, KIRC::Message &)), this, SLOT(engineInternalError(KIRC::Engine::Error, KIRC::Message &))); /* //FIXME: Have some kind of a debug option for raw input/ouput display?? QObject::connect(engine, SIGNAL(sentMessage(KIRC::Message &)), this, SLOT(engineSentMessage(KIRC::Message &))); QObject::connect(engine, SIGNAL(receivedMessage(KIRC::Message &)), this, SLOT(engineReceivedMessage(KIRC::Message &))); */ QObject::connect(engine, SIGNAL(incomingNotice(const QString &, const QString &)), this, SLOT(slotIncomingNotice(const QString &, const QString &))); QObject::connect(engine, SIGNAL(incomingCannotSendToChannel(const QString &, const QString &)), this, SLOT(slotCannotSendToChannel(const QString &, const QString &))); QObject::connect(engine, SIGNAL(incomingUnknown(const QString &)), this, SLOT(slotIncomingUnknown(const QString &))); QObject::connect(engine, SIGNAL(incomingConnectString(const QString &)), this, SLOT(slotIncomingConnect(const QString &))); QObject::connect(engine, SIGNAL(incomingMotd(const QString &)), this, SLOT(slotIncomingMotd(const QString &))); QObject::connect(Kopete::ChatSessionManager::self(), SIGNAL(viewCreated(KopeteView*)), this, SLOT(slotViewCreated(KopeteView*)) ); updateStatus(); } void IRCServerContact::updateStatus() { KIRC::Engine::Status status = kircEngine()->status(); switch( status ) { case KIRC::Engine::Idle: case KIRC::Engine::Connecting: if( m_chatSession ) m_chatSession->setDisplayName( caption() ); setOnlineStatus( m_protocol->m_ServerStatusOffline ); break; case KIRC::Engine::Authentifying: case KIRC::Engine::Connected: case KIRC::Engine::Closing: // should make some extra check here setOnlineStatus( m_protocol->m_ServerStatusOnline ); break; default: setOnlineStatus( m_protocol->m_StatusUnknown ); } } const QString IRCServerContact::caption() const { return i18n("%1 @ %2").arg(ircAccount()->mySelf()->nickName() ).arg( kircEngine()->currentHost().isEmpty() ? ircAccount()->networkName() : kircEngine()->currentHost() ); } void IRCServerContact::engineInternalError(KIRC::Engine::Error engineError, KIRC::Message &ircmsg) { QString error; switch (engineError) { case KIRC::Engine::ParsingFailed: error = i18n("KIRC Error - Parse error: "); break; case KIRC::Engine::UnknownCommand: error = i18n("KIRC Error - Unknown command: "); break; case KIRC::Engine::UnknownNumericReply: error = i18n("KIRC Error - Unknown numeric reply: "); break; case KIRC::Engine::InvalidNumberOfArguments: error = i18n("KIRC Error - Invalid number of arguments: "); break; case KIRC::Engine::MethodFailed: error = i18n("KIRC Error - Method failed: "); break; default: error = i18n("KIRC Error - Unknown error: "); } ircAccount()->appendMessage(error + QString(ircmsg.raw()), IRCAccount::ErrorReply); } void IRCServerContact::slotSendMsg(Kopete::Message &, Kopete::ChatSession *manager) { manager->messageSucceeded(); Kopete::Message msg( manager->myself(), manager->members(), i18n("You can not talk to the server, you can only issue commands here. Type /help for supported commands."), Kopete::Message::Internal, Kopete::Message::PlainText, CHAT_VIEW); manager->appendMessage(msg); } void IRCServerContact::appendMessage( const QString &message ) { Kopete::ContactPtrList members; members.append( this ); Kopete::Message msg( this, members, message, Kopete::Message::Internal, Kopete::Message::RichText, CHAT_VIEW ); appendMessage(msg); } void IRCServerContact::slotIncomingNotice( const QString &orig, const QString &notice ) { QString originator = orig.contains('!') ? orig.section('!',0,1) : orig; ircAccount()->appendMessage( i18n("NOTICE from %1: %2").arg( originator == ircAccount()->mySelf()->nickName() ? kircEngine()->currentHost() : originator, notice ), IRCAccount::NoticeReply ); } void IRCServerContact::slotIncomingUnknown(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::UnknownReply); } void IRCServerContact::slotIncomingConnect(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::ConnectReply); } void IRCServerContact::slotIncomingMotd(const QString &message) { ircAccount()->appendMessage(message, IRCAccount::InfoReply); } void IRCServerContact::slotCannotSendToChannel(const QString &channel, const QString &message) { ircAccount()->appendMessage(QString::fromLatin1("%1: %2").arg(channel).arg(message), IRCAccount::ErrorReply); } void IRCServerContact::appendMessage(Kopete::Message &msg) { msg.setImportance( Kopete::Message::Low ); //to don't distrub the user if (m_chatSession && m_chatSession->view(false)) m_chatSession->appendMessage(msg); /* // disable the buffering for now: cause a memleak since we don't made it a *fixed size fifo* else mMsgBuffer.append( msg ); */ } void IRCServerContact::slotDumpMessages() { if (!mMsgBuffer.isEmpty()) { manager()->appendMessage( mMsgBuffer.front() ); mMsgBuffer.pop_front(); QTimer::singleShot( 0, this, SLOT( slotDumpMessages() ) ); } } void IRCServerContact::slotViewCreated( KopeteView *v ) { kdDebug(14121) << k_funcinfo << "Created: " << v << ", mgr: " << v->msgManager() << ", Mine: " << m_chatSession << endl; if (m_chatSession && v->msgManager() == m_chatSession) QTimer::singleShot(500, this, SLOT(slotDumpMessages())); } #include "ircservercontact.moc"
Remove the buffering of message in the server for now. It's a source of memory leak.
Remove the buffering of message in the server for now. It's a source of memory leak. svn path=/trunk/KDE/kdenetwork/kopete/; revision=437402
C++
lgpl-2.1
Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete
0119eb5aa10a65139659376f65b6f8268749157f
src/modules/SimplePropagation/SimplePropagationModule.cpp
src/modules/SimplePropagation/SimplePropagationModule.cpp
/** * @author Paul Schuetze <[email protected]> * @author Koen Wolters <[email protected]> */ #include "SimplePropagationModule.hpp" #include <cmath> #include <limits> #include <map> #include <memory> #include <random> #include <string> #include <utility> #include <Eigen/Core> #include <Math/Point3D.h> #include <Math/Vector3D.h> #include "core/config/Configuration.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" #include "core/utils/unit.h" #include "tools/runge_kutta.h" #include "objects/PropagatedCharge.hpp" using namespace allpix; using namespace ROOT::Math; SimplePropagationModule::SimplePropagationModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), random_generator_(), config_(std::move(config)), messenger_(messenger), detector_(std::move(detector)), model_(), deposits_message_(nullptr) { // get detector model model_ = detector_->getModel(); // fetch deposits for single detector messenger_->bindSingle(this, &SimplePropagationModule::deposits_message_); // seed the random generator // FIXME: modules should share random device? random_generator_.seed(std::random_device()()); // set defaults for config variables config_.setDefault<double>("spatial_precision", Units::get(0.1, "nm")); config_.setDefault<double>("timestep_start", Units::get(0.01, "ns")); config_.setDefault<double>("timestep_min", Units::get(0.0005, "ns")); config_.setDefault<double>("timestep_max", Units::get(0.1, "ns")); config_.setDefault<unsigned int>("charge_per_step", 10); } SimplePropagationModule::~SimplePropagationModule() = default; // run the propagation void SimplePropagationModule::run() { // skip if this detector did not get any deposits if(deposits_message_ == nullptr) { return; } // create vector of propagated charges std::vector<PropagatedCharge> propagated_charges; // propagate all deposits LOG(INFO) << "Propagating charges in sensor"; for(auto& deposit : deposits_message_->getData()) { // loop over all charges unsigned int electrons_remaining = deposit.getCharge(); LOG(DEBUG) << "set of charges on " << deposit.getPosition(); auto charge_per_step = config_.get<unsigned int>("charge_per_step"); while(electrons_remaining > 0) { // define number of charges to be propagated and remove electrons of this step from the total if(charge_per_step > electrons_remaining) { charge_per_step = electrons_remaining; } electrons_remaining -= charge_per_step; // get position and propagate through sensor auto position = deposit.getPosition(); // NOTE: this is already a local position // propagate a single charge deposit auto prop_pair = propagate(position); position = prop_pair.first; LOG(DEBUG) << " propagated " << charge_per_step << " to " << position << "um in " << prop_pair.second << "ns"; // create a new propagated charge and add it to the list PropagatedCharge propagated_charge(position, charge_per_step); propagated_charges.push_back(propagated_charge); } } // create a new message with propagated charges PropagatedChargeMessage propagated_charge_message(std::move(propagated_charges), detector_); // dispatch the message messenger_->dispatchMessage(propagated_charge_message, "implant"); } std::pair<XYZPoint, double> SimplePropagationModule::propagate(const XYZPoint& root_pos) { // create a runge kutta solver using the electric field as step function Eigen::Vector3d position(root_pos.x(), root_pos.y(), root_pos.z()); // define a function to compute the electron mobility auto electron_mobility = [&](double efield_mag) { /* Reference: https://doi.org/10.1016/0038-1101(77)90054-5 (section 5.2) */ // variables for charge mobility auto temperature = config_.get<double>("temperature"); double electron_Vm = Units::get(1.53e9 * std::pow(temperature, -0.87), "cm/s"); double electron_Ec = Units::get(1.01 * std::pow(temperature, 1.55), "V/cm"); double electron_Beta = 2.57e-2 * std::pow(temperature, 0.66); // compute electron mobility double numerator = electron_Vm / electron_Ec; double denominator = std::pow(1. + std::pow(efield_mag / electron_Ec, electron_Beta), 1.0 / electron_Beta); return numerator / denominator; }; // define a function to compute the diffusion auto boltzmann_kT = Units::get(8.6173e-5, "eV/K") * config_.get<double>("temperature"); auto timestep = config_.get<double>("timestep_start"); auto electron_diffusion = [&](double efield_mag) -> Eigen::Vector3d { double diffusion_constant = boltzmann_kT * electron_mobility(efield_mag); double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep); std::normal_distribution<double> gauss_distribution(0, diffusion_std_dev); Eigen::Vector3d diffusion; for(int i = 0; i < 3; ++i) { diffusion[i] = gauss_distribution(random_generator_); } return diffusion; }; // define a function to compute the electron velocity auto voltage_scaling = config_.get<double>("voltage") / Units::get(1.0, "V"); // NOTE: not a real voltage auto electron_velocity = [&](double, Eigen::Vector3d pos) -> Eigen::Vector3d { // get the electric field double* raw_field = detector_->getElectricFieldRaw(pos); if(raw_field == nullptr) { // return a zero electric field outside of the sensor return Eigen::Vector3d(0, 0, 0); } // compute the drift velocity auto efield = static_cast<Eigen::Map<Eigen::Vector3d>>(raw_field); return voltage_scaling * (electron_mobility(efield.norm()) * (efield)); }; // build the runge kutta solver with an RKF5 tableau auto runge_kutta = make_runge_kutta(tableau::RK5, electron_velocity, timestep, position); // continue until outside the sensor (no electric field) // FIXME: we need to determine what would be a good time to stop while(true) { // do a runge kutta step auto step = runge_kutta.step(); // get the current result and timestep timestep = runge_kutta.getTimeStep(); position = runge_kutta.getValue(); // get electric field at current position and stop if field does not exist (outside sensor) double* raw_field = detector_->getElectricFieldRaw(position); if(raw_field == nullptr) { break; } // apply diffusion step auto efield = static_cast<Eigen::Map<Eigen::Vector3d>>(raw_field); auto diffusion = electron_diffusion(efield.norm()); runge_kutta.setValue(position + diffusion); // adapt step size to precision double uncertainty = step.error.norm(); double target_spatial_precision = config_.get<double>("spatial_precision"); if(model_->getSensorSizeZ() - position.z() < step.value.z() * 1.2) { timestep *= 0.7; } else { if(uncertainty > target_spatial_precision) { timestep *= 0.7; } else if(uncertainty < 0.5 * target_spatial_precision) { timestep *= 2; } } if(timestep > config_.get<double>("timestep_max")) { timestep = config_.get<double>("timestep_max"); } else if(timestep < config_.get<double>("timestep_min")) { timestep = config_.get<double>("timestep_min"); } runge_kutta.setTimeStep(timestep); } position = runge_kutta.getValue(); return std::make_pair(static_cast<XYZPoint>(position), runge_kutta.getTime()); }
/** * @author Paul Schuetze <[email protected]> * @author Koen Wolters <[email protected]> */ #include "SimplePropagationModule.hpp" #include <cmath> #include <limits> #include <map> #include <memory> #include <random> #include <string> #include <utility> #include <Eigen/Core> #include <Math/Point3D.h> #include <Math/Vector3D.h> #include "core/config/Configuration.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" #include "core/utils/unit.h" #include "tools/runge_kutta.h" #include "objects/PropagatedCharge.hpp" using namespace allpix; using namespace ROOT::Math; SimplePropagationModule::SimplePropagationModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), random_generator_(), config_(std::move(config)), messenger_(messenger), detector_(std::move(detector)), model_(), deposits_message_(nullptr) { // get detector model model_ = detector_->getModel(); // fetch deposits for single detector messenger_->bindSingle(this, &SimplePropagationModule::deposits_message_); // seed the random generator // FIXME: modules should share random device? random_generator_.seed(std::random_device()()); // set defaults for config variables config_.setDefault<double>("spatial_precision", Units::get(0.1, "nm")); config_.setDefault<double>("timestep_start", Units::get(0.01, "ns")); config_.setDefault<double>("timestep_min", Units::get(0.0005, "ns")); config_.setDefault<double>("timestep_max", Units::get(0.1, "ns")); config_.setDefault<unsigned int>("charge_per_step", 10); } SimplePropagationModule::~SimplePropagationModule() = default; // run the propagation void SimplePropagationModule::run() { // skip if this detector did not get any deposits if(deposits_message_ == nullptr) { return; } // create vector of propagated charges std::vector<PropagatedCharge> propagated_charges; // propagate all deposits LOG(INFO) << "Propagating charges in sensor"; for(auto& deposit : deposits_message_->getData()) { // loop over all charges unsigned int electrons_remaining = deposit.getCharge(); LOG(DEBUG) << "set of charges on " << deposit.getPosition(); auto charge_per_step = config_.get<unsigned int>("charge_per_step"); while(electrons_remaining > 0) { // define number of charges to be propagated and remove electrons of this step from the total if(charge_per_step > electrons_remaining) { charge_per_step = electrons_remaining; } electrons_remaining -= charge_per_step; // get position and propagate through sensor auto position = deposit.getPosition(); // NOTE: this is already a local position // propagate a single charge deposit auto prop_pair = propagate(position); position = prop_pair.first; LOG(DEBUG) << " propagated " << charge_per_step << " to " << position << " in " << prop_pair.second << " time"; // create a new propagated charge and add it to the list PropagatedCharge propagated_charge(position, charge_per_step); propagated_charges.push_back(propagated_charge); } } // create a new message with propagated charges PropagatedChargeMessage propagated_charge_message(std::move(propagated_charges), detector_); // dispatch the message messenger_->dispatchMessage(propagated_charge_message, "implant"); } std::pair<XYZPoint, double> SimplePropagationModule::propagate(const XYZPoint& root_pos) { // create a runge kutta solver using the electric field as step function Eigen::Vector3d position(root_pos.x(), root_pos.y(), root_pos.z()); // define a function to compute the electron mobility auto electron_mobility = [&](double efield_mag) { /* Reference: https://doi.org/10.1016/0038-1101(77)90054-5 (section 5.2) */ // variables for charge mobility auto temperature = config_.get<double>("temperature"); double electron_Vm = Units::get(1.53e9 * std::pow(temperature, -0.87), "cm/s"); double electron_Ec = Units::get(1.01 * std::pow(temperature, 1.55), "V/cm"); double electron_Beta = 2.57e-2 * std::pow(temperature, 0.66); // compute electron mobility double numerator = electron_Vm / electron_Ec; double denominator = std::pow(1. + std::pow(efield_mag / electron_Ec, electron_Beta), 1.0 / electron_Beta); return numerator / denominator; }; // define a function to compute the diffusion auto boltzmann_kT = Units::get(8.6173e-5, "eV/K") * config_.get<double>("temperature"); auto timestep = config_.get<double>("timestep_start"); auto electron_diffusion = [&](double efield_mag) -> Eigen::Vector3d { double diffusion_constant = boltzmann_kT * electron_mobility(efield_mag); double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep); std::normal_distribution<double> gauss_distribution(0, diffusion_std_dev); Eigen::Vector3d diffusion; for(int i = 0; i < 3; ++i) { diffusion[i] = gauss_distribution(random_generator_); } return diffusion; }; // define a function to compute the electron velocity auto electron_velocity = [&](double, Eigen::Vector3d pos) -> Eigen::Vector3d { // get the electric field double* raw_field = detector_->getElectricFieldRaw(pos); if(raw_field == nullptr) { // return a zero electric field outside of the sensor return Eigen::Vector3d(0, 0, 0); } // compute the drift velocity auto efield = static_cast<Eigen::Map<Eigen::Vector3d>>(raw_field); return electron_mobility(efield.norm()) * (efield); }; // build the runge kutta solver with an RKF5 tableau auto runge_kutta = make_runge_kutta(tableau::RK5, electron_velocity, timestep, position); // continue until outside the sensor (no electric field) // FIXME: we need to determine what would be a good time to stop while(true) { // do a runge kutta step auto step = runge_kutta.step(); // get the current result and timestep timestep = runge_kutta.getTimeStep(); position = runge_kutta.getValue(); // get electric field at current position and stop if field does not exist (outside sensor) double* raw_field = detector_->getElectricFieldRaw(position); if(raw_field == nullptr) { break; } // apply diffusion step auto efield = static_cast<Eigen::Map<Eigen::Vector3d>>(raw_field); auto diffusion = electron_diffusion(efield.norm()); runge_kutta.setValue(position + diffusion); // adapt step size to precision double uncertainty = step.error.norm(); double target_spatial_precision = config_.get<double>("spatial_precision"); if(model_->getSensorSizeZ() - position.z() < step.value.z() * 1.2) { timestep *= 0.7; } else { if(uncertainty > target_spatial_precision) { timestep *= 0.7; } else if(uncertainty < 0.5 * target_spatial_precision) { timestep *= 2; } } if(timestep > config_.get<double>("timestep_max")) { timestep = config_.get<double>("timestep_max"); } else if(timestep < config_.get<double>("timestep_min")) { timestep = config_.get<double>("timestep_min"); } runge_kutta.setTimeStep(timestep); } position = runge_kutta.getValue(); return std::make_pair(static_cast<XYZPoint>(position), runge_kutta.getTime()); }
remove voltage as long it is not consistent with electric field
remove voltage as long it is not consistent with electric field
C++
mit
Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared
7ac046c58f0815223712f77288722a7b06755ec3
src/operator/tensor/elemwise_binary_scalar_op_extended.cc
src/operator/tensor/elemwise_binary_scalar_op_extended.cc
/*! * Copyright (c) 2016 by Contributors * \file elemwise_binary_scalar_op.cc * \brief CPU Implementation of unary function. */ #include "./elemwise_unary_op.h" #include "./elemwise_binary_op.h" #include "./elemwise_binary_scalar_op.h" namespace mxnet { namespace op { MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_maximum_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::maximum>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_maximum_scalar"}) .add_alias("_MaximumScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_maximum_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::ge>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_minimum_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::minimum>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_minimum_scalar"}) .add_alias("_MinimumScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_minimum_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::le>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_power_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::power>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_power_scalar"}) .add_alias("_PowerScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_power_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::power_grad>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_rpower_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::rpower>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseOut{"_backward_rpower_scalar"}) .add_alias("_RPowerScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_rpower_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::rpower_grad>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_hypot_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::hypot>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_hypot_scalar" }) .add_alias("_HypotScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_hypot_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); }) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::hypot_grad_left>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(smooth_l1) .describe(R"code(Calculate Smooth L1 Loss(lhs, scalar) by summing .. math:: f(x) = \begin{cases} (\sigma x)^2/2,& \text{if }x < 1/\sigma^2\\ |x|-0.5/\sigma^2,& \text{otherwise} \end{cases} where :math:`x` is an element of the tensor *lhs* and :math:`\sigma` is the scalar. Example:: a = mx.nd.array([1, 2, 3, 4]), :math:`\sigma=1`, smooth_l1(a, :math:`\sigma`) = [0.5, 1.5, 2.5, 3.5] )code" ADD_FILELINE) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::smooth_l1_loss>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_smooth_l1" }); MXNET_OPERATOR_REGISTER_BINARY(_backward_smooth_l1) .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); }) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::smooth_l1_gradient>); } // namespace op } // namespace mxnet
/*! * Copyright (c) 2016 by Contributors * \file elemwise_binary_scalar_op.cc * \brief CPU Implementation of unary function. */ #include "./elemwise_unary_op.h" #include "./elemwise_binary_op.h" #include "./elemwise_binary_scalar_op.h" namespace mxnet { namespace op { MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_maximum_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::maximum>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_maximum_scalar"}) .add_alias("_MaximumScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_maximum_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::ge>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_minimum_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::minimum>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_minimum_scalar"}) .add_alias("_MinimumScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_minimum_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::le>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_power_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::power>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_power_scalar"}) .add_alias("_PowerScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_power_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::power_grad>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_rpower_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::rpower>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseOut{"_backward_rpower_scalar"}) .add_alias("_RPowerScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_rpower_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]);}) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::rpower_grad>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(_hypot_scalar) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::hypot>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_hypot_scalar" }) .add_alias("_HypotScalar"); MXNET_OPERATOR_REGISTER_BINARY(_backward_hypot_scalar) .add_argument("scalar", "float", "scalar value") .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); }) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::hypot_grad_left>); MXNET_OPERATOR_REGISTER_BINARY_SCALAR(smooth_l1) .describe(R"code(Calculate Smooth L1 Loss(lhs, scalar) by summing .. math:: f(x) = \begin{cases} (\sigma x)^2/2,& \text{if }x < 1/\sigma^2\\ |x|-0.5/\sigma^2,& \text{otherwise} \end{cases} where :math:`x` is an element of the tensor *lhs* and :math:`\sigma` is the scalar. Example:: smooth_l1([1, 2, 3, 4], sigma=1) = [0.5, 1.5, 2.5, 3.5] )code" ADD_FILELINE) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarCompute<cpu, mshadow_op::smooth_l1_loss>) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_smooth_l1" }); MXNET_OPERATOR_REGISTER_BINARY(_backward_smooth_l1) .set_attr_parser([](NodeAttrs* attrs) {attrs->parsed = std::stod(attrs->dict["scalar"]); }) .set_attr<FCompute>("FCompute<cpu>", BinaryScalarBackward<cpu, mshadow_op::smooth_l1_gradient>); } // namespace op } // namespace mxnet
Fix smooth_l1 example display (#6377)
[DOC] Fix smooth_l1 example display (#6377) * Fix doc format * Fix
C++
apache-2.0
kevinthesun/mxnet,tornadomeet/mxnet,madjam/mxnet,sergeykolychev/mxnet,wangyum/mxnet,vikingMei/mxnet,mbaijal/incubator-mxnet,fullfanta/mxnet,jamesliu/mxnet,leezu/mxnet,rahul003/mxnet,jennyzhang0215/incubator-mxnet,kevinthesun/mxnet,EvanzzzZ/mxnet,apaleyes/mxnet,ZihengJiang/mxnet,TuSimple/mxnet,DR08/mxnet,DR08/mxnet,reminisce/mxnet,jennyzhang0215/incubator-mxnet,stefanhenneking/mxnet,sergeykolychev/mxnet,fullfanta/mxnet,luoyetx/mxnet,apaleyes/mxnet,TuSimple/mxnet,apaleyes/mxnet,eric-haibin-lin/mxnet,nicklhy/mxnet,nicklhy/mxnet,antoan2/incubator-mxnet,thirdwing/mxnet,smolix/incubator-mxnet,xcgoner/dist-mxnet,coder-james/mxnet,formath/mxnet,coder-james/mxnet,apache/incubator-mxnet,madjam/mxnet,hotpxl/mxnet,navrasio/mxnet,solin319/incubator-mxnet,yuruofeifei/mxnet,mbaijal/incubator-mxnet,dmlc/mxnet,danithaca/mxnet,EvanzzzZ/mxnet,zhreshold/mxnet,Mega-DatA-Lab/mxnet,formath/mxnet,jiajiechen/mxnet,TuSimple/mxnet,ptrendx/mxnet,vikingMei/mxnet,zhreshold/mxnet,gautamkmr/incubator-mxnet,jamesliu/mxnet,ykim362/mxnet,lxn2/mxnet,DR08/mxnet,wangyum/mxnet,sxjscience/mxnet,sxjscience/mxnet,ForkedReposBak/mxnet,apaleyes/mxnet,tornadomeet/mxnet,mbaijal/incubator-mxnet,ykim362/mxnet,stefanhenneking/mxnet,yajiedesign/mxnet,fullfanta/mxnet,apaleyes/mxnet,Northrend/mxnet,danithaca/mxnet,arank/mxnet,EvanzzzZ/mxnet,tlby/mxnet,DR08/mxnet,tornadomeet/mxnet,tornadomeet/mxnet,precedenceguo/mxnet,larroy/mxnet,Ldpe2G/mxnet,weleen/mxnet,precedenceguo/mxnet,weleen/mxnet,szha/mxnet,smolix/incubator-mxnet,smolix/incubator-mxnet,thirdwing/mxnet,arank/mxnet,ykim362/mxnet,stefanhenneking/mxnet,ykim362/mxnet,CodingCat/mxnet,ShownX/incubator-mxnet,piiswrong/mxnet,zhreshold/mxnet,antoan2/incubator-mxnet,madjam/mxnet,gautamkmr/incubator-mxnet,smolix/incubator-mxnet,precedenceguo/mxnet,jamesliu/mxnet,navrasio/mxnet,ykim362/mxnet,crazy-cat/incubator-mxnet,zhreshold/mxnet,arikpoz/mxnet,mbaijal/incubator-mxnet,gautamkmr/incubator-mxnet,antoan2/incubator-mxnet,ForkedReposBak/mxnet,larroy/mxnet,szha/mxnet,zhreshold/mxnet,apaleyes/mxnet,piiswrong/mxnet,sergeykolychev/mxnet,vikingMei/mxnet,nicklhy/mxnet,kkk669/mxnet,stefanhenneking/mxnet,arank/mxnet,thirdwing/mxnet,EvanzzzZ/mxnet,antoan2/incubator-mxnet,piiswrong/mxnet,ptrendx/mxnet,dmlc/mxnet,CodingCat/mxnet,luoyetx/mxnet,saurabh3949/mxnet,pluskid/mxnet,jennyzhang0215/incubator-mxnet,Ldpe2G/mxnet,CodingCat/mxnet,jermainewang/mxnet,indhub/mxnet,stefanhenneking/mxnet,saurabh3949/mxnet,weleen/mxnet,Mega-DatA-Lab/mxnet,yajiedesign/mxnet,formath/mxnet,kevinthesun/mxnet,hotpxl/mxnet,danithaca/mxnet,Prasad9/incubator-mxnet,eric-haibin-lin/mxnet,ForkedReposBak/mxnet,coder-james/mxnet,hpi-xnor/BMXNet,tornadomeet/mxnet,vikingMei/mxnet,eric-haibin-lin/mxnet,reminisce/mxnet,wangyum/mxnet,crazy-cat/incubator-mxnet,szha/mxnet,tlby/mxnet,tlby/mxnet,weleen/mxnet,arikpoz/mxnet,fullfanta/mxnet,EvanzzzZ/mxnet,hesseltuinhof/mxnet,antoan2/incubator-mxnet,lxn2/mxnet,danithaca/mxnet,tlby/mxnet,crazy-cat/incubator-mxnet,madjam/mxnet,DR08/mxnet,tornadomeet/mxnet,leezu/mxnet,hesseltuinhof/mxnet,indhub/mxnet,yajiedesign/mxnet,hesseltuinhof/mxnet,coder-james/mxnet,yajiedesign/mxnet,arank/mxnet,weleen/mxnet,danithaca/mxnet,Mega-DatA-Lab/mxnet,mbaijal/incubator-mxnet,wangyum/mxnet,lxn2/mxnet,navrasio/mxnet,indhub/mxnet,ForkedReposBak/mxnet,pluskid/mxnet,jermainewang/mxnet,indhub/mxnet,formath/mxnet,saurabh3949/mxnet,rahul003/mxnet,fullfanta/mxnet,leezu/mxnet,xcgoner/dist-mxnet,thirdwing/mxnet,kkk669/mxnet,jennyzhang0215/incubator-mxnet,tlby/mxnet,Prasad9/incubator-mxnet,kkk669/mxnet,lxn2/mxnet,yajiedesign/mxnet,solin319/incubator-mxnet,indhub/mxnet,ZihengJiang/mxnet,pluskid/mxnet,yajiedesign/mxnet,stefanhenneking/mxnet,jiajiechen/mxnet,arank/mxnet,wangyum/mxnet,DR08/mxnet,piiswrong/mxnet,navrasio/mxnet,tlby/mxnet,formath/mxnet,DickJC123/mxnet,thirdwing/mxnet,ptrendx/mxnet,arank/mxnet,indhub/mxnet,Prasad9/incubator-mxnet,weleen/mxnet,apache/incubator-mxnet,arikpoz/mxnet,pluskid/mxnet,larroy/mxnet,sxjscience/mxnet,ptrendx/mxnet,hotpxl/mxnet,weleen/mxnet,tornadomeet/mxnet,crazy-cat/incubator-mxnet,navrasio/mxnet,DickJC123/mxnet,CodingCat/mxnet,Ldpe2G/mxnet,arikpoz/mxnet,nicklhy/mxnet,solin319/incubator-mxnet,tlby/mxnet,ptrendx/mxnet,dmlc/mxnet,hotpxl/mxnet,Mega-DatA-Lab/mxnet,Mega-DatA-Lab/mxnet,szha/mxnet,solin319/incubator-mxnet,jennyzhang0215/incubator-mxnet,eric-haibin-lin/mxnet,mbaijal/incubator-mxnet,indhub/mxnet,ZihengJiang/mxnet,leezu/mxnet,DickJC123/mxnet,hesseltuinhof/mxnet,antoan2/incubator-mxnet,arikpoz/mxnet,TuSimple/mxnet,hpi-xnor/BMXNet,ptrendx/mxnet,kevinthesun/mxnet,sxjscience/mxnet,madjam/mxnet,rahul003/mxnet,hotpxl/mxnet,jiajiechen/mxnet,luoyetx/mxnet,luoyetx/mxnet,larroy/mxnet,precedenceguo/mxnet,weleen/mxnet,leezu/mxnet,wangyum/mxnet,stefanhenneking/mxnet,vikingMei/mxnet,larroy/mxnet,larroy/mxnet,EvanzzzZ/mxnet,vikingMei/mxnet,formath/mxnet,thirdwing/mxnet,xcgoner/dist-mxnet,luoyetx/mxnet,wangyum/mxnet,Northrend/mxnet,yuruofeifei/mxnet,formath/mxnet,sxjscience/mxnet,saurabh3949/mxnet,nicklhy/mxnet,sergeykolychev/mxnet,yuruofeifei/mxnet,kkk669/mxnet,jiajiechen/mxnet,eric-haibin-lin/mxnet,hotpxl/mxnet,hesseltuinhof/mxnet,ForkedReposBak/mxnet,indhub/mxnet,TuSimple/mxnet,sergeykolychev/mxnet,szha/mxnet,thirdwing/mxnet,CodingCat/mxnet,precedenceguo/mxnet,Ldpe2G/mxnet,gautamkmr/incubator-mxnet,lxn2/mxnet,apaleyes/mxnet,LinkHS/incubator-mxnet,luoyetx/mxnet,zhreshold/mxnet,zhreshold/mxnet,reminisce/mxnet,ykim362/mxnet,eric-haibin-lin/mxnet,jennyzhang0215/incubator-mxnet,yuruofeifei/mxnet,sxjscience/mxnet,hpi-xnor/BMXNet,larroy/mxnet,ForkedReposBak/mxnet,ptrendx/mxnet,LinkHS/incubator-mxnet,jermainewang/mxnet,reminisce/mxnet,ShownX/incubator-mxnet,precedenceguo/mxnet,ZihengJiang/mxnet,piiswrong/mxnet,LinkHS/incubator-mxnet,Northrend/mxnet,TuSimple/mxnet,lxn2/mxnet,LinkHS/incubator-mxnet,hpi-xnor/BMXNet,Prasad9/incubator-mxnet,tlby/mxnet,LinkHS/incubator-mxnet,Ldpe2G/mxnet,kkk669/mxnet,sergeykolychev/mxnet,arank/mxnet,rahul003/mxnet,solin319/incubator-mxnet,gautamkmr/incubator-mxnet,solin319/incubator-mxnet,mbaijal/incubator-mxnet,Northrend/mxnet,precedenceguo/mxnet,smolix/incubator-mxnet,vikingMei/mxnet,gautamkmr/incubator-mxnet,ForkedReposBak/mxnet,danithaca/mxnet,rahul003/mxnet,jiajiechen/mxnet,jennyzhang0215/incubator-mxnet,ForkedReposBak/mxnet,rahul003/mxnet,hpi-xnor/BMXNet,lxn2/mxnet,nicklhy/mxnet,ShownX/incubator-mxnet,eric-haibin-lin/mxnet,kevinthesun/mxnet,crazy-cat/incubator-mxnet,apache/incubator-mxnet,pluskid/mxnet,leezu/mxnet,saurabh3949/mxnet,madjam/mxnet,jamesliu/mxnet,DickJC123/mxnet,szha/mxnet,dmlc/mxnet,dmlc/mxnet,leezu/mxnet,piiswrong/mxnet,crazy-cat/incubator-mxnet,yuruofeifei/mxnet,apache/incubator-mxnet,antoan2/incubator-mxnet,sxjscience/mxnet,saurabh3949/mxnet,apaleyes/mxnet,szha/mxnet,coder-james/mxnet,jermainewang/mxnet,gautamkmr/incubator-mxnet,hpi-xnor/BMXNet,vikingMei/mxnet,rahul003/mxnet,eric-haibin-lin/mxnet,danithaca/mxnet,Ldpe2G/mxnet,nicklhy/mxnet,DR08/mxnet,precedenceguo/mxnet,piiswrong/mxnet,antoan2/incubator-mxnet,yuruofeifei/mxnet,jennyzhang0215/incubator-mxnet,rahul003/mxnet,luoyetx/mxnet,smolix/incubator-mxnet,solin319/incubator-mxnet,yajiedesign/mxnet,jiajiechen/mxnet,jermainewang/mxnet,sergeykolychev/mxnet,ykim362/mxnet,jermainewang/mxnet,eric-haibin-lin/mxnet,dmlc/mxnet,mbaijal/incubator-mxnet,TuSimple/mxnet,ShownX/incubator-mxnet,dmlc/mxnet,solin319/incubator-mxnet,pluskid/mxnet,fullfanta/mxnet,saurabh3949/mxnet,Ldpe2G/mxnet,tlby/mxnet,LinkHS/incubator-mxnet,kevinthesun/mxnet,yuruofeifei/mxnet,fullfanta/mxnet,DR08/mxnet,yajiedesign/mxnet,piiswrong/mxnet,fullfanta/mxnet,yuruofeifei/mxnet,saurabh3949/mxnet,hesseltuinhof/mxnet,fullfanta/mxnet,tlby/mxnet,arikpoz/mxnet,hpi-xnor/BMXNet,ShownX/incubator-mxnet,ptrendx/mxnet,jermainewang/mxnet,jermainewang/mxnet,xcgoner/dist-mxnet,hotpxl/mxnet,luoyetx/mxnet,weleen/mxnet,saurabh3949/mxnet,hpi-xnor/BMXNet,ZihengJiang/mxnet,LinkHS/incubator-mxnet,kkk669/mxnet,EvanzzzZ/mxnet,sergeykolychev/mxnet,CodingCat/mxnet,coder-james/mxnet,yuruofeifei/mxnet,madjam/mxnet,hotpxl/mxnet,xcgoner/dist-mxnet,nicklhy/mxnet,sergeykolychev/mxnet,szha/mxnet,reminisce/mxnet,navrasio/mxnet,kevinthesun/mxnet,CodingCat/mxnet,reminisce/mxnet,hesseltuinhof/mxnet,navrasio/mxnet,Northrend/mxnet,madjam/mxnet,TuSimple/mxnet,hesseltuinhof/mxnet,ptrendx/mxnet,navrasio/mxnet,pluskid/mxnet,luoyetx/mxnet,mbaijal/incubator-mxnet,Northrend/mxnet,Prasad9/incubator-mxnet,EvanzzzZ/mxnet,tornadomeet/mxnet,danithaca/mxnet,TuSimple/mxnet,ZihengJiang/mxnet,leezu/mxnet,crazy-cat/incubator-mxnet,ptrendx/mxnet,reminisce/mxnet,dmlc/mxnet,EvanzzzZ/mxnet,Northrend/mxnet,coder-james/mxnet,lxn2/mxnet,ZihengJiang/mxnet,Mega-DatA-Lab/mxnet,rahul003/mxnet,ForkedReposBak/mxnet,madjam/mxnet,coder-james/mxnet,arikpoz/mxnet,tornadomeet/mxnet,danithaca/mxnet,stefanhenneking/mxnet,formath/mxnet,leezu/mxnet,ZihengJiang/mxnet,smolix/incubator-mxnet,dmlc/mxnet,coder-james/mxnet,lxn2/mxnet,ShownX/incubator-mxnet,szha/mxnet,kkk669/mxnet,Northrend/mxnet,solin319/incubator-mxnet,jiajiechen/mxnet,ZihengJiang/mxnet,jamesliu/mxnet,jamesliu/mxnet,reminisce/mxnet,kkk669/mxnet,arikpoz/mxnet,Prasad9/incubator-mxnet,gautamkmr/incubator-mxnet,kkk669/mxnet,hesseltuinhof/mxnet,nicklhy/mxnet,apaleyes/mxnet,gautamkmr/incubator-mxnet,crazy-cat/incubator-mxnet,Prasad9/incubator-mxnet,reminisce/mxnet,xcgoner/dist-mxnet,Prasad9/incubator-mxnet,hotpxl/mxnet,Mega-DatA-Lab/mxnet,piiswrong/mxnet,ShownX/incubator-mxnet,smolix/incubator-mxnet,Northrend/mxnet,ShownX/incubator-mxnet,arank/mxnet,ShownX/incubator-mxnet,kevinthesun/mxnet,stefanhenneking/mxnet,Mega-DatA-Lab/mxnet,Mega-DatA-Lab/mxnet,LinkHS/incubator-mxnet,jiajiechen/mxnet,ykim362/mxnet,jamesliu/mxnet,arank/mxnet,wangyum/mxnet,crazy-cat/incubator-mxnet,larroy/mxnet,hpi-xnor/BMXNet,jamesliu/mxnet,xcgoner/dist-mxnet,jermainewang/mxnet,arikpoz/mxnet,Ldpe2G/mxnet,jamesliu/mxnet,xcgoner/dist-mxnet,Ldpe2G/mxnet,vikingMei/mxnet,pluskid/mxnet,TuSimple/mxnet,pluskid/mxnet,yajiedesign/mxnet,zhreshold/mxnet,ykim362/mxnet,CodingCat/mxnet,jennyzhang0215/incubator-mxnet,indhub/mxnet,sxjscience/mxnet,antoan2/incubator-mxnet,larroy/mxnet,navrasio/mxnet,wangyum/mxnet,jiajiechen/mxnet,Prasad9/incubator-mxnet,thirdwing/mxnet,formath/mxnet,kevinthesun/mxnet,CodingCat/mxnet,precedenceguo/mxnet,sxjscience/mxnet,xcgoner/dist-mxnet,DR08/mxnet,zhreshold/mxnet,LinkHS/incubator-mxnet,smolix/incubator-mxnet,reminisce/mxnet,thirdwing/mxnet
1d8dcc464df4d4f57af94f3e5efba7fa4b995cf0
include/eixx/connect/transport_otp_connection_tcp.hpp
include/eixx/connect/transport_otp_connection_tcp.hpp
//---------------------------------------------------------------------------- /// \file transport_otp_connection_tcp.hpp //---------------------------------------------------------------------------- /// \brief Interface of TCP connectivity transport with an Erlang node. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-09-11 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Serge Aleynikov <saleyn at gmail dot com> 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. ***** END LICENSE BLOCK ***** */ #ifndef _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_ #define _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_ #include <eixx/connect/transport_otp_connection.hpp> #include <ei.h> #include <erl_interface.h> #include <eixx/config.h> #ifdef HAVE_EI_EPMD extern "C" { #include <epmd/ei_epmd.h> // see erl_interface/src #include <misc/eiext.h> // ERL_VERSION_MAGIC #include <connect/ei_connect_int.h> // see erl_interface/src } #endif namespace eixx { namespace connect { #ifndef HAVE_EI_EPMD // These constants are not exposed by EI headers: static const char ERL_VERSION_MAGIC = 131; static const short EPMD_PORT = 4369; static const int EPMDBUF = 512; static const char EI_EPMD_PORT2_REQ = 122; static const char EI_EPMD_PORT2_RESP = 119; static const char EI_DIST_HIGH = 5; static const int DFLAG_PUBLISHED = 1; static const int DFLAG_ATOM_CACHE = 2; static const int DFLAG_EXTENDED_REFERENCES = 4; static const int DFLAG_DIST_MONITOR = 8; static const int DFLAG_FUN_TAGS = 16; static const int DFLAG_NEW_FUN_TAGS = 0x80; static const int DFLAG_EXTENDED_PIDS_PORTS = 0x100; static const int DFLAG_NEW_FLOATS = 0x800; #endif //---------------------------------------------------------------------------- /// TCP connection channel //---------------------------------------------------------------------------- template <typename Handler, typename Alloc> class tcp_connection : public connection<Handler, Alloc> { public: typedef connection<Handler, Alloc> base_t; tcp_connection(boost::asio::io_service& a_svc, Handler* a_h, const Alloc& a_alloc) : connection<Handler, Alloc>(TCP, a_svc, a_h, a_alloc) , m_socket(a_svc) , m_resolver(a_svc) , m_state(CS_INIT) {} /// Get the socket associated with the connection. boost::asio::ip::tcp::socket& socket() { return m_socket; } void stop(const boost::system::error_code& e) { if (this->handler()->verbose() >= VERBOSE_TRACE) std::cout << "Calling connection_tcp::stop(" << e.message() << ')' << std::endl; boost::system::error_code ec; m_socket.close(ec); m_state = CS_INIT; base_t::stop(e); } std::string peer_address() const { std::stringstream s; s << m_peer_endpoint.address() << ':' << m_peer_endpoint.port(); return s.str(); } int native_socket() { return m_socket.native(); } private: /// Authentication state enum connect_state { CS_INIT , CS_WAIT_RESOLVE , CS_WAIT_EPMD_CONNECT , CS_WAIT_EPMD_WRITE_DONE , CS_WAIT_EPMD_REPLY , CS_WAIT_CONNECT , CS_WAIT_WRITE_CHALLENGE_DONE , CS_WAIT_STATUS , CS_WAIT_CHALLENGE , CS_WAIT_WRITE_CHALLENGE_REPLY_DONE , CS_WAIT_CHALLENGE_ACK , CS_CONNECTED }; /// Socket for the connection. boost::asio::ip::tcp::socket m_socket; boost::asio::ip::tcp::resolver m_resolver; boost::asio::ip::tcp::endpoint m_peer_endpoint; connect_state m_state; // Async connection state size_t m_expect_size; char m_buf_epmd[EPMDBUF]; char* m_epmd_wr; char m_buf_node[256]; const char* m_node_rd; char* m_node_wr; uint16_t m_dist_version; uint32_t m_remote_challenge; uint32_t m_our_challenge; void connect(atom a_this_node, atom a_remote_nodename, atom a_cookie) throw(std::runtime_error); boost::shared_ptr<tcp_connection<Handler, Alloc> > shared_from_this() { boost::shared_ptr<connection<Handler, Alloc> > p = base_t::shared_from_this(); return *reinterpret_cast<boost::shared_ptr<tcp_connection<Handler, Alloc> >*>(&p); } /// Set the socket to non-blocking mode and issue on_connect() callback. /// /// When implementing a server this method is to be called after /// accepting a new connection. When implementing a client, call /// connect() method instead, which invokes start() automatically. void start(); std::string remote_alivename() const { auto s = this->remote_nodename().to_string(); #ifndef NDEBUG auto n = s.find('@'); #endif BOOST_ASSERT(n != std::string::npos); return s.substr(0, s.find('@')); } std::string remote_hostname() const { auto s = this->remote_nodename().to_string(); #ifndef NDEBUG auto n = s.find('@'); #endif BOOST_ASSERT(n != std::string::npos); return s.substr(s.find('@')+1); } void handle_resolve( const boost::system::error_code& err, boost::asio::ip::tcp::resolver::iterator ep_iterator); void handle_epmd_connect( const boost::system::error_code& err, boost::asio::ip::tcp::resolver::iterator ep_iterator); void handle_epmd_write(const boost::system::error_code& err); void handle_epmd_read_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_epmd_read_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_connect(const boost::system::error_code& err); void handle_write_name(const boost::system::error_code& err); void handle_read_status_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_status_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_write_challenge_reply(const boost::system::error_code& err); void handle_read_challenge_ack_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_ack_body( const boost::system::error_code& err, size_t bytes_transferred); uint32_t gen_challenge(void); void gen_digest(unsigned challenge, const char cookie[], uint8_t digest[16]); uint32_t md_32(char* string, int length); }; } // namespace connect } // namespace eixx //------------------------------------------------------------------------------ // connection_tcp implementation //------------------------------------------------------------------------------ #include <eixx/connect/transport_otp_connection_tcp.hxx> #endif // _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_
//---------------------------------------------------------------------------- /// \file transport_otp_connection_tcp.hpp //---------------------------------------------------------------------------- /// \brief Interface of TCP connectivity transport with an Erlang node. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <[email protected]> // Created: 2010-09-11 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Serge Aleynikov <saleyn at gmail dot com> 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. ***** END LICENSE BLOCK ***** */ #ifndef _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_ #define _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_ #include <eixx/connect/transport_otp_connection.hpp> #include <ei.h> #include <erl_interface.h> #include <eixx/config.h> #ifdef HAVE_EI_EPMD extern "C" { #include <epmd/ei_epmd.h> // see erl_interface/src #include <misc/eiext.h> // ERL_VERSION_MAGIC #include <connect/ei_connect_int.h> // see erl_interface/src } #endif namespace eixx { namespace connect { #ifndef HAVE_EI_EPMD // These constants are not exposed by EI headers: static const int ERL_VERSION_MAGIC = 131; static const short EPMD_PORT = 4369; static const int EPMDBUF = 512; static const char EI_EPMD_PORT2_REQ = 122; static const char EI_EPMD_PORT2_RESP = 119; static const char EI_DIST_HIGH = 5; static const int DFLAG_PUBLISHED = 1; static const int DFLAG_ATOM_CACHE = 2; static const int DFLAG_EXTENDED_REFERENCES = 4; static const int DFLAG_DIST_MONITOR = 8; static const int DFLAG_FUN_TAGS = 16; static const int DFLAG_NEW_FUN_TAGS = 0x80; static const int DFLAG_EXTENDED_PIDS_PORTS = 0x100; static const int DFLAG_NEW_FLOATS = 0x800; #endif //---------------------------------------------------------------------------- /// TCP connection channel //---------------------------------------------------------------------------- template <typename Handler, typename Alloc> class tcp_connection : public connection<Handler, Alloc> { public: typedef connection<Handler, Alloc> base_t; tcp_connection(boost::asio::io_service& a_svc, Handler* a_h, const Alloc& a_alloc) : connection<Handler, Alloc>(TCP, a_svc, a_h, a_alloc) , m_socket(a_svc) , m_resolver(a_svc) , m_state(CS_INIT) {} /// Get the socket associated with the connection. boost::asio::ip::tcp::socket& socket() { return m_socket; } void stop(const boost::system::error_code& e) { if (this->handler()->verbose() >= VERBOSE_TRACE) std::cout << "Calling connection_tcp::stop(" << e.message() << ')' << std::endl; boost::system::error_code ec; m_socket.close(ec); m_state = CS_INIT; base_t::stop(e); } std::string peer_address() const { std::stringstream s; s << m_peer_endpoint.address() << ':' << m_peer_endpoint.port(); return s.str(); } int native_socket() { return m_socket.native(); } private: /// Authentication state enum connect_state { CS_INIT , CS_WAIT_RESOLVE , CS_WAIT_EPMD_CONNECT , CS_WAIT_EPMD_WRITE_DONE , CS_WAIT_EPMD_REPLY , CS_WAIT_CONNECT , CS_WAIT_WRITE_CHALLENGE_DONE , CS_WAIT_STATUS , CS_WAIT_CHALLENGE , CS_WAIT_WRITE_CHALLENGE_REPLY_DONE , CS_WAIT_CHALLENGE_ACK , CS_CONNECTED }; /// Socket for the connection. boost::asio::ip::tcp::socket m_socket; boost::asio::ip::tcp::resolver m_resolver; boost::asio::ip::tcp::endpoint m_peer_endpoint; connect_state m_state; // Async connection state size_t m_expect_size; char m_buf_epmd[EPMDBUF]; char* m_epmd_wr; char m_buf_node[256]; const char* m_node_rd; char* m_node_wr; uint16_t m_dist_version; uint32_t m_remote_challenge; uint32_t m_our_challenge; void connect(atom a_this_node, atom a_remote_nodename, atom a_cookie) throw(std::runtime_error); boost::shared_ptr<tcp_connection<Handler, Alloc> > shared_from_this() { boost::shared_ptr<connection<Handler, Alloc> > p = base_t::shared_from_this(); return *reinterpret_cast<boost::shared_ptr<tcp_connection<Handler, Alloc> >*>(&p); } /// Set the socket to non-blocking mode and issue on_connect() callback. /// /// When implementing a server this method is to be called after /// accepting a new connection. When implementing a client, call /// connect() method instead, which invokes start() automatically. void start(); std::string remote_alivename() const { auto s = this->remote_nodename().to_string(); #ifndef NDEBUG auto n = s.find('@'); #endif BOOST_ASSERT(n != std::string::npos); return s.substr(0, s.find('@')); } std::string remote_hostname() const { auto s = this->remote_nodename().to_string(); #ifndef NDEBUG auto n = s.find('@'); #endif BOOST_ASSERT(n != std::string::npos); return s.substr(s.find('@')+1); } void handle_resolve( const boost::system::error_code& err, boost::asio::ip::tcp::resolver::iterator ep_iterator); void handle_epmd_connect( const boost::system::error_code& err, boost::asio::ip::tcp::resolver::iterator ep_iterator); void handle_epmd_write(const boost::system::error_code& err); void handle_epmd_read_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_epmd_read_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_connect(const boost::system::error_code& err); void handle_write_name(const boost::system::error_code& err); void handle_read_status_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_status_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_body( const boost::system::error_code& err, size_t bytes_transferred); void handle_write_challenge_reply(const boost::system::error_code& err); void handle_read_challenge_ack_header( const boost::system::error_code& err, size_t bytes_transferred); void handle_read_challenge_ack_body( const boost::system::error_code& err, size_t bytes_transferred); uint32_t gen_challenge(void); void gen_digest(unsigned challenge, const char cookie[], uint8_t digest[16]); uint32_t md_32(char* string, int length); }; } // namespace connect } // namespace eixx //------------------------------------------------------------------------------ // connection_tcp implementation //------------------------------------------------------------------------------ #include <eixx/connect/transport_otp_connection_tcp.hxx> #endif // _EIXX_TRANSPORT_OTP_CONNECTION_TCP_HPP_
use int for ERL_VERSION_MAGIC
use int for ERL_VERSION_MAGIC When comparing int to char, char was interpreted as signed. This caused "Invalid control message magic number"
C++
apache-2.0
saleyn/eixx
00c1cb1cffb20d58a513321a140934f971939deb
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs01.C /// @brief Run and manage the DDR4 MRS01 loading /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs01_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs01_data::mrs01_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_dll_enable(fapi2::ENUM_ATTR_EFF_DRAM_DLL_ENABLE_YES), iv_odic(0), iv_additive_latency(0), iv_wl_enable(0), iv_tdqs(0), iv_qoff(0) { FAPI_TRY( mss::eff_dram_dll_enable(i_target, iv_dll_enable) ); FAPI_TRY( mss::eff_dram_ron(i_target, iv_odic) ); FAPI_TRY( mss::eff_dram_al(i_target, iv_additive_latency) ); FAPI_TRY( mss::eff_dram_wr_lvl_enable(i_target, iv_wl_enable) ); FAPI_TRY( mss::vpd_mt_dram_rtt_nom(i_target, &(iv_rtt_nom[0])) ); FAPI_TRY( mss::eff_dram_tdqs(i_target, iv_tdqs) ); FAPI_TRY( mss::eff_dram_output_buffer(i_target, iv_qoff) ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("unable to get attributes for mrs0"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs01_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "Unable to construct MRS01 data from attributes"); FAPI_TRY( mrs01(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs01_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Little table to map Output Driver Imepdance Control. 34Ohm is index 0, // 48Ohm is index 1 // Left bit is A2, right bit is A1 constexpr uint8_t odic_map[2] = { 0b00, 0b01 }; // Indexed by denominator. So, if RQZ is 240, and you have OHM240, then you're looking // for index 1. So this doesn't correspond directly with the table in the JEDEC spec, // as that's not in "denominator order." // 0 RQZ/1 RQZ/2 RQZ/3 RQZ/4 RQZ/5 RQZ/6 RQZ/7 constexpr uint8_t rtt_nom_map[8] = { 0, 0b100, 0b010, 0b110, 0b001, 0b101, 0b011, 0b111 }; size_t l_rtt_nom_index = 0; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_odic_buffer; fapi2::buffer<uint8_t> l_rtt_nom_buffer; FAPI_ASSERT( ((i_data.iv_odic == fapi2::ENUM_ATTR_EFF_DRAM_RON_OHM34) || (i_data.iv_odic == fapi2::ENUM_ATTR_EFF_DRAM_RON_OHM48)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(1) .set_PARAMETER(OUTPUT_IMPEDANCE) .set_PARAMETER_VALUE(i_data.iv_odic) .set_DIMM_IN_ERROR(i_target), "Bad value for output driver impedance: %d (%s)", i_data.iv_odic, mss::c_str(i_target)); // Map from impedance to bits in MRS1 l_odic_buffer = (i_data.iv_odic == fapi2::ENUM_ATTR_EFF_DRAM_RON_OHM34) ? odic_map[0] : odic_map[1]; // We have to be careful about 0 l_rtt_nom_index = (i_data.iv_rtt_nom[mss::index(i_rank)] == 0) ? 0 : fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_RTT_NOM_OHM240 / i_data.iv_rtt_nom[mss::index(i_rank)]; // Map from RTT_NOM array to the value in the map l_rtt_nom_buffer = rtt_nom_map[l_rtt_nom_index]; // Print this here as opposed to the MRS01 ctor as we want to see the specific rtt now information FAPI_INF("MR1 rank %d attributes: DLL_ENABLE: 0x%x, ODIC: 0x%x(0x%x), AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x(0x%x), TDQS: 0x%x, QOFF: 0x%x", i_rank, i_data.iv_dll_enable, i_data.iv_odic, uint8_t(l_odic_buffer), uint8_t(l_additive_latency), i_data.iv_wl_enable, i_data.iv_rtt_nom[mss::index(i_rank)], uint8_t(l_rtt_nom_buffer), i_data.iv_tdqs, i_data.iv_qoff); io_inst.arr0.writeBit<A0>(i_data.iv_dll_enable); mss::swizzle<A1, 2, 7>(l_odic_buffer, io_inst.arr0); mss::swizzle<A3, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_additive_latency), io_inst.arr0); io_inst.arr0.writeBit<A7>(i_data.iv_wl_enable); mss::swizzle<A8, 3, 7>(l_rtt_nom_buffer, io_inst.arr0); io_inst.arr0.writeBit<A11>(i_data.iv_tdqs); io_inst.arr0.writeBit<A12>(i_data.iv_qoff); FAPI_INF("MR1: 0x%016llx", uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS1, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { fapi2::buffer<uint8_t> l_odic; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_rtt_nom; uint8_t l_dll_enable = i_inst.arr0.getBit<A0>(); uint8_t l_wrl_enable = i_inst.arr0.getBit<A7>(); uint8_t l_tdqs = i_inst.arr0.getBit<A11>(); uint8_t l_qoff = i_inst.arr0.getBit<A12>(); mss::swizzle<6, 2, A2>(i_inst.arr0, l_odic); mss::swizzle<6, 2, A4>(i_inst.arr0, l_additive_latency); mss::swizzle<5, 3, A10>(i_inst.arr0, l_rtt_nom); FAPI_INF("MR1 rank %d decode: DLL_ENABLE: 0x%x, ODIC: 0x%x, AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x, TDQS: 0x%x, QOFF: 0x%x", i_rank, l_dll_enable, uint8_t(l_odic), uint8_t(l_additive_latency), l_wrl_enable, uint8_t(l_rtt_nom), l_tdqs, l_qoff); return FAPI2_RC_SUCCESS; } fapi2::ReturnCode (*mrs01_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) = &mrs01; fapi2::ReturnCode (*mrs01_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) = &mrs01_decode; } // ns ddr4 } // ns mss
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs01.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs01.C /// @brief Run and manage the DDR4 MRS01 loading /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs01_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs01_data::mrs01_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_dll_enable(fapi2::ENUM_ATTR_EFF_DRAM_DLL_ENABLE_YES), iv_additive_latency(0), iv_wl_enable(0), iv_tdqs(0), iv_qoff(0) { FAPI_TRY( mss::eff_dram_dll_enable(i_target, iv_dll_enable) ); FAPI_TRY( mss::vpd_mt_dram_drv_imp_dq_dqs(i_target, &(iv_odic[0])) ); FAPI_TRY( mss::eff_dram_al(i_target, iv_additive_latency) ); FAPI_TRY( mss::eff_dram_wr_lvl_enable(i_target, iv_wl_enable) ); FAPI_TRY( mss::vpd_mt_dram_rtt_nom(i_target, &(iv_rtt_nom[0])) ); FAPI_TRY( mss::eff_dram_tdqs(i_target, iv_tdqs) ); FAPI_TRY( mss::eff_dram_output_buffer(i_target, iv_qoff) ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("unable to get attributes for mrs0"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs01_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "Unable to construct MRS01 data from attributes"); FAPI_TRY( mrs01(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs01, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs01_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs01(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Little table to map Output Driver Imepdance Control. 34Ohm is index 0, // 48Ohm is index 1 // Left bit is A2, right bit is A1 constexpr uint8_t odic_map[2] = { 0b00, 0b01 }; // Indexed by denominator. So, if RQZ is 240, and you have OHM240, then you're looking // for index 1. So this doesn't correspond directly with the table in the JEDEC spec, // as that's not in "denominator order." // 0 RQZ/1 RQZ/2 RQZ/3 RQZ/4 RQZ/5 RQZ/6 RQZ/7 constexpr uint8_t rtt_nom_map[8] = { 0, 0b100, 0b010, 0b110, 0b001, 0b101, 0b011, 0b111 }; size_t l_rtt_nom_index = 0; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_odic_buffer; fapi2::buffer<uint8_t> l_rtt_nom_buffer; FAPI_ASSERT( ((i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) || (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM48)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(1) .set_PARAMETER(OUTPUT_IMPEDANCE) .set_PARAMETER_VALUE(i_data.iv_odic[mss::index(i_rank)]) .set_DIMM_IN_ERROR(i_target), "Bad value for output driver impedance: %d (%s)", i_data.iv_odic[mss::index(i_rank)], mss::c_str(i_target)); // Map from impedance to bits in MRS1 l_odic_buffer = (i_data.iv_odic[mss::index(i_rank)] == fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS_OHM34) ? odic_map[0] : odic_map[1]; // We have to be careful about 0 l_rtt_nom_index = (i_data.iv_rtt_nom[mss::index(i_rank)] == 0) ? 0 : fapi2::ENUM_ATTR_MSS_VPD_MT_DRAM_RTT_NOM_OHM240 / i_data.iv_rtt_nom[mss::index(i_rank)]; // Map from RTT_NOM array to the value in the map l_rtt_nom_buffer = rtt_nom_map[l_rtt_nom_index]; // Print this here as opposed to the MRS01 ctor as we want to see the specific rtt now information FAPI_INF("MR1 rank %d attributes: DLL_ENABLE: 0x%x, ODIC: 0x%x(0x%x), AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x(0x%x), TDQS: 0x%x, QOFF: 0x%x", i_rank, i_data.iv_dll_enable, i_data.iv_odic[mss::index(i_rank)], uint8_t(l_odic_buffer), uint8_t(l_additive_latency), i_data.iv_wl_enable, i_data.iv_rtt_nom[mss::index(i_rank)], uint8_t(l_rtt_nom_buffer), i_data.iv_tdqs, i_data.iv_qoff); io_inst.arr0.writeBit<A0>(i_data.iv_dll_enable); mss::swizzle<A1, 2, 7>(l_odic_buffer, io_inst.arr0); mss::swizzle<A3, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_additive_latency), io_inst.arr0); io_inst.arr0.writeBit<A7>(i_data.iv_wl_enable); mss::swizzle<A8, 3, 7>(l_rtt_nom_buffer, io_inst.arr0); io_inst.arr0.writeBit<A11>(i_data.iv_tdqs); io_inst.arr0.writeBit<A12>(i_data.iv_qoff); FAPI_INF("MR1: 0x%016llx", uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS1, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode mrs01_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { fapi2::buffer<uint8_t> l_odic; fapi2::buffer<uint8_t> l_additive_latency; fapi2::buffer<uint8_t> l_rtt_nom; uint8_t l_dll_enable = i_inst.arr0.getBit<A0>(); uint8_t l_wrl_enable = i_inst.arr0.getBit<A7>(); uint8_t l_tdqs = i_inst.arr0.getBit<A11>(); uint8_t l_qoff = i_inst.arr0.getBit<A12>(); mss::swizzle<6, 2, A2>(i_inst.arr0, l_odic); mss::swizzle<6, 2, A4>(i_inst.arr0, l_additive_latency); mss::swizzle<5, 3, A10>(i_inst.arr0, l_rtt_nom); FAPI_INF("MR1 rank %d decode: DLL_ENABLE: 0x%x, ODIC: 0x%x, AL: 0x%x, WLE: 0x%x, " "RTT_NOM: 0x%x, TDQS: 0x%x, QOFF: 0x%x", i_rank, l_dll_enable, uint8_t(l_odic), uint8_t(l_additive_latency), l_wrl_enable, uint8_t(l_rtt_nom), l_tdqs, l_qoff); return FAPI2_RC_SUCCESS; } fapi2::ReturnCode (*mrs01_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs01_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) = &mrs01; fapi2::ReturnCode (*mrs01_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) = &mrs01_decode; } // ns ddr4 } // ns mss
Change DRAM output impedance value to be from MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS
Change DRAM output impedance value to be from MSS_VPD_MT_DRAM_DRV_IMP_DQ_DQS Change-Id: I934ef11c93dec80795df6f173bbd996ffee5af31 Original-Change-Id: I146ff2adbaa96d7b0ae34c4fdde6b6fde3c34f5e Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/28147 Tested-by: Jenkins Server <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: JACOB L. HARVEY <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: Brian R. Silver <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
b61423cb531c71a1c6faf254b522258bfa02d656
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs06.C
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs06.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs06.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs06.C /// @brief Run and manage the DDR4 MRS06 loading /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs06_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs06_data::mrs06_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_tccd_l(0) { FAPI_TRY( mss::eff_vref_dq_train_value(i_target, &(iv_vrefdq_train_value[0])) ); FAPI_TRY( mss::eff_vref_dq_train_range(i_target, &(iv_vrefdq_train_range[0])) ); FAPI_TRY( mss::eff_vref_dq_train_enable(i_target, &(iv_vrefdq_train_enable[0])) ); FAPI_TRY( mss::eff_dram_tccd_l(i_target, iv_tccd_l) ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("unable to get attributes for mrs0"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs06 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs06(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs06_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "Unable to construct MRS06 data from attributes"); FAPI_TRY( mrs06(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs06, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs06_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs06(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs06_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { constexpr uint64_t LOWEST_TCCD = 4; constexpr uint64_t TCCD_COUNT = 5; // 4 5 6 7 8 constexpr uint8_t tccd_l_map[TCCD_COUNT] = { 0b000, 0b001, 0b010, 0b011, 0b100 }; fapi2::buffer<uint8_t> l_tccd_l_buffer; fapi2::buffer<uint8_t> l_vrefdq_train_value_buffer; FAPI_ASSERT((i_data.iv_tccd_l >= LOWEST_TCCD) && (i_data.iv_tccd_l < (LOWEST_TCCD + TCCD_COUNT)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(6) .set_PARAMETER(TCCD) .set_PARAMETER_VALUE(i_data.iv_tccd_l) .set_DIMM_IN_ERROR(i_target), "Bad value for TCCD: %d (%s)", i_data.iv_tccd_l, mss::c_str(i_target)); l_tccd_l_buffer = tccd_l_map[i_data.iv_tccd_l - LOWEST_TCCD]; l_vrefdq_train_value_buffer = i_data.iv_vrefdq_train_value[mss::index(i_rank)]; FAPI_INF("MR6 rank %d attributes: TRAIN_V: 0x%x(0x%x), TRAIN_R: 0x%x, TRAIN_E: 0x%x, TCCD_L: 0x%x(0x%x)", i_rank, i_data.iv_vrefdq_train_value[mss::index(i_rank)], uint8_t(l_vrefdq_train_value_buffer), i_data.iv_vrefdq_train_range[mss::index(i_rank)], i_data.iv_vrefdq_train_enable[mss::index(i_rank)], i_data.iv_tccd_l, uint8_t(l_tccd_l_buffer)); mss::swizzle<A0, 6, 7>(l_vrefdq_train_value_buffer, io_inst.arr0); io_inst.arr0.writeBit<A6>(i_data.iv_vrefdq_train_range[mss::index(i_rank)]); io_inst.arr0.writeBit<A7>(i_data.iv_vrefdq_train_enable[mss::index(i_rank)]); mss::swizzle<A10, 3, 7>(l_tccd_l_buffer, io_inst.arr0); FAPI_INF("MR6: 0x%016llx", uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS6, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return void /// fapi2::ReturnCode mrs06_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { fapi2::buffer<uint8_t> l_tccd_l_buffer; fapi2::buffer<uint8_t> l_vrefdq_train_value_buffer; mss::swizzle<2, 6, A5>(i_inst.arr0, l_vrefdq_train_value_buffer); uint8_t l_vrefdq_train_range = i_inst.arr0.getBit<A6>(); uint8_t l_vrefdq_train_enable = i_inst.arr0.getBit<A7>(); mss::swizzle<5, 3, A12>(i_inst.arr0, l_tccd_l_buffer); FAPI_INF("MR6 rank %d decode: TRAIN_V: 0x%x, TRAIN_R: 0x%x, TRAIN_E: 0x%x, TCCD_L: 0x%x", i_rank, uint8_t(l_vrefdq_train_value_buffer), l_vrefdq_train_range, l_vrefdq_train_enable, uint8_t(l_tccd_l_buffer)); return FAPI2_RC_SUCCESS; } } // ns ddr4 } // ns mss
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs06.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mrs06.C /// @brief Run and manage the DDR4 MRS06 loading /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <lib/dimm/ddr4/mrs_load_ddr4.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace ddr4 { /// /// @brief mrs06_data ctor /// @param[in] a fapi2::TARGET_TYPE_DIMM target /// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// mrs06_data::mrs06_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ): iv_tccd_l(0) { FAPI_TRY( mss::eff_vref_dq_train_value(i_target, &(iv_vrefdq_train_value[0])) ); FAPI_TRY( mss::eff_vref_dq_train_range(i_target, &(iv_vrefdq_train_range[0])) ); FAPI_TRY( mss::eff_vref_dq_train_enable(i_target, &(iv_vrefdq_train_enable[0])) ); FAPI_TRY( mss::eff_dram_tccd_l(i_target, iv_tccd_l) ); o_rc = fapi2::FAPI2_RC_SUCCESS; return; fapi_try_exit: o_rc = fapi2::current_err; FAPI_ERR("unable to get attributes for mrs0"); return; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs06 /// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM> /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs06(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { // Check to make sure our ctor worked ok mrs06_data l_data( i_target, fapi2::current_err ); FAPI_TRY( fapi2::current_err, "Unable to construct MRS06 data from attributes"); FAPI_TRY( mrs06(i_target, l_data, io_inst, i_rank) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Configure the ARR0 of the CCS instruction for mrs06, data object as input /// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] i_data an mrs06_data object, filled in /// @param[in,out] io_inst the instruction to fixup /// @param[in] i_rank the rank in question /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode mrs06(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs06_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) { constexpr uint64_t LOWEST_TCCD = 4; constexpr uint64_t TCCD_COUNT = 5; // 4 5 6 7 8 constexpr uint8_t tccd_l_map[TCCD_COUNT] = { 0b000, 0b001, 0b010, 0b011, 0b100 }; fapi2::buffer<uint8_t> l_tccd_l_buffer; fapi2::buffer<uint8_t> l_vrefdq_train_value_buffer; FAPI_ASSERT((i_data.iv_tccd_l >= LOWEST_TCCD) && (i_data.iv_tccd_l < (LOWEST_TCCD + TCCD_COUNT)), fapi2::MSS_BAD_MR_PARAMETER() .set_MR_NUMBER(6) .set_PARAMETER(TCCD) .set_PARAMETER_VALUE(i_data.iv_tccd_l) .set_DIMM_IN_ERROR(i_target), "Bad value for TCCD: %d (%s)", i_data.iv_tccd_l, mss::c_str(i_target)); l_tccd_l_buffer = tccd_l_map[i_data.iv_tccd_l - LOWEST_TCCD]; l_vrefdq_train_value_buffer = i_data.iv_vrefdq_train_value[mss::index(i_rank)]; FAPI_INF("MR6 rank %d attributes: TRAIN_V: 0x%x(0x%x), TRAIN_R: 0x%x, TRAIN_E: 0x%x, TCCD_L: 0x%x(0x%x)", i_rank, i_data.iv_vrefdq_train_value[mss::index(i_rank)], uint8_t(l_vrefdq_train_value_buffer), i_data.iv_vrefdq_train_range[mss::index(i_rank)], i_data.iv_vrefdq_train_enable[mss::index(i_rank)], i_data.iv_tccd_l, uint8_t(l_tccd_l_buffer)); mss::swizzle<A0, 6, 7>(l_vrefdq_train_value_buffer, io_inst.arr0); io_inst.arr0.writeBit<A6>(i_data.iv_vrefdq_train_range[mss::index(i_rank)]); io_inst.arr0.writeBit<A7>(i_data.iv_vrefdq_train_enable[mss::index(i_rank)]); mss::swizzle<A10, 3, 7>(l_tccd_l_buffer, io_inst.arr0); FAPI_INF("MR6: 0x%016llx", uint64_t(io_inst.arr0)); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } /// /// @brief Given a CCS instruction which contains address bits with an encoded MRS6, /// decode and trace the contents /// @param[in] i_inst the CCS instruction /// @param[in] i_rank ths rank in question /// @return void /// fapi2::ReturnCode mrs06_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) { fapi2::buffer<uint8_t> l_tccd_l_buffer; fapi2::buffer<uint8_t> l_vrefdq_train_value_buffer; mss::swizzle<2, 6, A5>(i_inst.arr0, l_vrefdq_train_value_buffer); uint8_t l_vrefdq_train_range = i_inst.arr0.getBit<A6>(); uint8_t l_vrefdq_train_enable = i_inst.arr0.getBit<A7>(); mss::swizzle<5, 3, A12>(i_inst.arr0, l_tccd_l_buffer); FAPI_INF("MR6 rank %d decode: TRAIN_V: 0x%x, TRAIN_R: 0x%x, TRAIN_E: 0x%x, TCCD_L: 0x%x", i_rank, uint8_t(l_vrefdq_train_value_buffer), l_vrefdq_train_range, l_vrefdq_train_enable, uint8_t(l_tccd_l_buffer)); return FAPI2_RC_SUCCESS; } fapi2::ReturnCode (*mrs06_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const mrs06_data& i_data, ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst, const uint64_t i_rank) = &mrs06; fapi2::ReturnCode (*mrs06_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst, const uint64_t i_rank) = &mrs06_decode; } // ns ddr4 } // ns mss
Add mrs_one_shot to the MSS Lab code
Add mrs_one_shot to the MSS Lab code Change-Id: I1bbec5a33dc662a45b0034d2afcd64d0b4d6df79 Original-Change-Id: I84fd2f29f4b3d8581a6ff8c0f8a2688cc0cf645a Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/27373 Tested-by: Jenkins Server <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: ANDRE A. MARIN <[email protected]> Reviewed-by: Brian R. Silver <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
053c261564cf070aa799f42a6c0ee9631f7bd33e
src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.C
src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_proc_gettracearray.C /// /// @brief Collect contents of specified trace array via SCOM. /// /// Collects contents of specified trace array via SCOM. Optionally /// manages chiplet domain trace engine state (start/stop/reset) around /// trace array data collection. Trace array data can be collected only /// when its controlling chiplet trace engine is stopped. /// /// Trace array entries will be packed into data buffer from /// oldest->youngest entry. /// /// Calling code is expected to pass the proper target type based on the /// desired trace resource; a convenience function is provided to find out /// the expected target type for a given trace resource. //------------------------------------------------------------------------------ // *HWP HW Owner : Joachim Fenkes <[email protected]> // *HWP HW Backup Owner : Joe McGill <[email protected]> // *HWP FW Owner : Shakeeb Pasha <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : FSP //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p9_proc_gettracearray.H" //------------------------------------------------------------------------------ // HWP entry point //------------------------------------------------------------------------------ extern "C" fapi2::ReturnCode p9_proc_gettracearray( const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>& i_target, const proc_gettracearray_args& i_args, fapi2::variable_buffer& o_ta_data) { fapi2::ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS; // mark HWP entry FAPI_INF("Entering ..."); fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES> l_target; const uint8_t l_chiplet_num = i_target.getChipletNumber(); if(IS_MCBIST(l_chiplet_num) || IS_OBUS(l_chiplet_num)) { l_target = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); } else { l_target = i_target.get(); } o_ta_data.resize(P9_TRACEARRAY_NUM_ROWS * P9_TRACEARRAY_BITS_PER_ROW).flush<0>(); uint64_t l_data_buffer[P9_TRACEARRAY_NUM_ROWS * P9_TRACEARRAY_BITS_PER_ROW / 8 / sizeof(uint64_t)] = {}; l_fapiRc = p9_sbe_tracearray( l_target, i_args, l_data_buffer, 0, P9_TRACEARRAY_NUM_ROWS); FAPI_TRY(l_fapiRc, "p9_sbe_tracearray failed"); for(uint32_t i = 0; i < P9_TRACEARRAY_NUM_ROWS; i++) { FAPI_TRY(o_ta_data.set<uint64_t>(l_data_buffer[2 * i + 0], 2 * i + 0), "Failed to insert data into trace buffer"); FAPI_TRY(o_ta_data.set<uint64_t>(l_data_buffer[2 * i + 1], 2 * i + 1), "Failed to insert data into trace buffer"); } // mark HWP exit FAPI_INF("Success"); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; }
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_proc_gettracearray.C /// /// @brief Collect contents of specified trace array via SCOM. /// /// Collects contents of specified trace array via SCOM. Optionally /// manages chiplet domain trace engine state (start/stop/reset) around /// trace array data collection. Trace array data can be collected only /// when its controlling chiplet trace engine is stopped. /// /// Trace array entries will be packed into data buffer from /// oldest->youngest entry. /// /// Calling code is expected to pass the proper target type based on the /// desired trace resource; a convenience function is provided to find out /// the expected target type for a given trace resource. //------------------------------------------------------------------------------ // *HWP HW Owner : Joachim Fenkes <[email protected]> // *HWP HW Backup Owner : Joe McGill <[email protected]> // *HWP FW Owner : Shakeeb Pasha <[email protected]> // *HWP Team : Perv // *HWP Level : 3 // *HWP Consumed by : FSP //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p9_proc_gettracearray.H" //------------------------------------------------------------------------------ // HWP entry point //------------------------------------------------------------------------------ extern "C" fapi2::ReturnCode p9_proc_gettracearray( const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>& i_target, const proc_gettracearray_args& i_args, fapi2::variable_buffer& o_ta_data) { fapi2::ReturnCode l_fapiRc = fapi2::FAPI2_RC_SUCCESS; // mark HWP entry FAPI_INF("Entering ..."); fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES> l_target; const uint8_t l_chiplet_num = i_target.getChipletNumber(); if(IS_MCBIST(l_chiplet_num) || IS_OBUS(l_chiplet_num)) { l_target = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); } else { l_target = i_target.get(); } o_ta_data.resize(P9_TRACEARRAY_NUM_ROWS * P9_TRACEARRAY_BITS_PER_ROW).flush<0>(); uint64_t l_data_buffer[P9_TRACEARRAY_NUM_ROWS * P9_TRACEARRAY_BITS_PER_ROW / 8 / sizeof(uint64_t)] = {}; l_fapiRc = p9_sbe_tracearray( l_target, i_args, l_data_buffer, 0, P9_TRACEARRAY_NUM_ROWS); FAPI_TRY(l_fapiRc, "p9_sbe_tracearray failed"); for(uint32_t i = 0; i < P9_TRACEARRAY_NUM_ROWS; i++) { FAPI_TRY(o_ta_data.set<uint64_t>(l_data_buffer[2 * i + 0], 2 * i + 0), "Failed to insert data into trace buffer"); FAPI_TRY(o_ta_data.set<uint64_t>(l_data_buffer[2 * i + 1], 2 * i + 1), "Failed to insert data into trace buffer"); } // mark HWP exit FAPI_INF("Success"); return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; }
Update hardware procedure metadata
Update hardware procedure metadata update the metadata to reflect that HWPs are product ready (HWP Level: 3) Change-Id: I7c78dc9a45c8c603e80fe0afc3f45bdc1b2a0119 Original-Change-Id: I5a7380e9f34865b3e0ef7872d6338a840b08aa4a Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/46789 Tested-by: FSP CI Jenkins <[email protected]> Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: PPE CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Joseph J. McGill <[email protected]> Reviewed-by: SRINIVAS V. POLISETTY <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
2e1b3b61c603321b2c6a3d5d262773ff847e6aeb
jni/main.cpp
jni/main.cpp
#include <jni.h> #include <dlfcn.h> #include <android/log.h> #include <stdlib.h> #include <Substrate.h> #include <string> #include <mcpe/client/resources/I18n.h> #include <mcpe/item/Item.h> #include <mcpe/tile/Tile.h> #include <mcpe/client/renderer/TileTessellator.h> #include <mcpe/util/Matrix.h> #include <mcpe/client/renderer/ItemInHandRenderer.h> #include "PocketPC/tile/BeaconTile.h" bool duelWield = false; //Change game version. static std::string (*getGameVersionString_real)(); static std::string getGameVersionString_hook() { return "PocketPC Addon v1.0"; } //Change item names and edit the lang. static std::string (*I18n_get_real)(std::string const&, std::vector<std::string, std::allocator<std::string>> const&); static std::string I18n_get_hook(std::string const& key, std::vector<std::string, std::allocator<std::string>> const& a) { if(key == "menu.copyright") return "©SmartDEV"; // if(key == "menu.play") return "Singleplayer"; //We don't need this! I'm gonna redo the start menu return I18n_get_real(key, a); } //TileTesellation. bool (*_TileTessellator$tessellateInWorld)(TileTessellator*, Tile*, const TilePos&, bool); bool TileTessellator$tessellateInWorld(TileTessellator* self, Tile* tile, const TilePos& pos, bool b) { switch(tile->id) { case 138: return self->tessellateBeaconInWorld(tile, pos); break; default: return _TileTessellator$tessellateInWorld(self, tile, pos, b); break; } } //Tile Init. void (*_Tile$initTiles)(); void Tile$initTiles() { _Tile$initTiles(); BeaconTile::beacon = (Tile*)((new BeaconTile(138))->init()->setDestroyTime(1.0F)->setLightEmission(0.125F)->setNameId("beacon")->setSoundType(Tile::SOUND_GLASS)); } //Duel wielding. static void (*_ItemInHandRenderer$render)(ItemInHandRenderer*, float); static void ItemInHandRenderer$render(ItemInHandRenderer* renderer, float partialTicks) { if(duelWield){ _ItemInHandRenderer$render(renderer, partialTicks); MatrixStack::Ref matref = MatrixStack::World.push(); Vec3 oneleft {-0.995f, -0.01f, 0.01f}; matref.matrix->translate(oneleft); _ItemInHandRenderer$render(renderer, partialTicks); } } //Hook the functions. JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { void* handle = dlopen("libminecraftpe.so", RTLD_LAZY); void* getGameVersionString = dlsym(RTLD_DEFAULT, "_ZN6Common20getGameVersionStringEv"); MSHookFunction(getGameVersionString, (void*)&getGameVersionString_hook, (void**)&getGameVersionString_real); MSHookFunction((void*) &ItemInHandRenderer::render, (void*) &ItemInHandRenderer$render, (void**) &_ItemInHandRenderer$render); MSHookFunction((void*) &I18n::get, (void*) &I18n_get_hook, (void**) &I18n_get_real); MSHookFunction((void*) &Tile::initTiles, (void*) &Tile$initTiles, (void**) &_Tile$initTiles); MSHookFunction((void*) &TileTessellator::tessellateInWorld, (void*) &TileTessellator$tessellateInWorld, (void**) &_TileTessellator$tessellateInWorld); }
#include <jni.h> #include <dlfcn.h> #include <android/log.h> #include <stdlib.h> #include <Substrate.h> #include <string> #include <mcpe/client/resources/I18n.h> #include <mcpe/item/Item.h> #include <mcpe/tile/Tile.h> #include <mcpe/client/renderer/TileTessellator.h> #include <mcpe/util/Matrix.h> #include <mcpe/client/renderer/ItemInHandRenderer.h> #include "PocketPC/tile/BeaconTile.h" bool duelWield = false; //Change game version. static std::string (*getGameVersionString_real)(); static std::string getGameVersionString_hook() { return "PocketPC Addon v1.0"; } //Change item names and edit the lang. static std::string (*I18n_get_real)(std::string const&, std::vector<std::string, std::allocator<std::string>> const&); static std::string I18n_get_hook(std::string const& key, std::vector<std::string, std::allocator<std::string>> const& a) { if(key == "menu.copyright") return "©SmartDEV"; // if(key == "menu.play") return "Singleplayer"; //We don't need this! I'm gonna redo the start menu return I18n_get_real(key, a); } //TileTesellation. bool (*_TileTessellator$tessellateInWorld)(TileTessellator*, Tile*, const TilePos&, bool); bool TileTessellator$tessellateInWorld(TileTessellator* self, Tile* tile, const TilePos& pos, bool b) { switch(tile->id) { case 138: return self->tessellateBeaconInWorld(tile, pos); break; default: return _TileTessellator$tessellateInWorld(self, tile, pos, b); break; } } //Tile Init. void (*_Tile$initTiles)(); void Tile$initTiles() { _Tile$initTiles(); BeaconTile::beacon = (Tile*)((new BeaconTile(138))->init()->setDestroyTime(1.0F)->setLightEmission(0.125F)->setNameId("beacon")->setSoundType(Tile::SOUND_GLASS)); } //Duel wielding. static void (*_ItemInHandRenderer$render)(ItemInHandRenderer*, float); static void ItemInHandRenderer$render(ItemInHandRenderer* renderer, float partialTicks) { if(duelWield){ _ItemInHandRenderer$render(renderer, partialTicks); MatrixStack::Ref matref = MatrixStack::World.push(); Vec3 oneleft {-0.995f, -0.01f, 0.01f}; matref.matrix->translate(oneleft); _ItemInHandRenderer$render(renderer, partialTicks); } } //Hook the functions. JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { void* handle = dlopen("libminecraftpe.so", RTLD_LAZY); void* getGameVersionString = dlsym(RTLD_DEFAULT, "_ZN6Common20getGameVersionStringEv"); MSHookFunction(getGameVersionString, (void*)&getGameVersionString_hook, (void**)&getGameVersionString_real); MSHookFunction((void*) &ItemInHandRenderer::render, (void*) &ItemInHandRenderer$render, (void**) &_ItemInHandRenderer$render); MSHookFunction((void*) &I18n::get, (void*) &I18n_get_hook, (void**) &I18n_get_real); MSHookFunction((void*) &Tile::initTiles, (void*) &Tile$initTiles, (void**) &_Tile$initTiles); MSHookFunction((void*) &TileTessellator::tessellateInWorld, (void*) &TileTessellator$tessellateInWorld, (void**) &_TileTessellator$tessellateInWorld); return JNI_VERSION_1_2; }
Update main.cpp
Update main.cpp
C++
apache-2.0
byteandahalf/PocketPC,byteandahalf/PocketPC
30de99d4e94f2d06112c235cc5216a4d9103f8f3
test/correctness/skip_stages_external_array_functions.cpp
test/correctness/skip_stages_external_array_functions.cpp
#include <Halide.h> #include <stdio.h> using namespace Halide; #ifdef _MSC_VER #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif int bounds_query_count[4]; int call_count[4]; extern "C" DLLEXPORT int call_counter(buffer_t *input, int x, int idx, buffer_t *output) { if (input->host == NULL) { bounds_query_count[idx]++; input->min[0] = output->min[0]; input->extent[0] = output->extent[0]; input->elem_size = 1; return 0; } call_count[idx]++; for (int32_t i = 0; i < output->extent[0]; i++) { output->host[i] = input->host[i] + x; } return 0; } void reset_counts() { for (int i = 0; i < 4; i++) { bounds_query_count[i] = 0; call_count[i] = 0; } } void check_queries(int a = 0, int b = 0, int c = 0, int d = 0) { int correct[] = {a, b, c, d}; for (int i = 0; i < 4; i++) { if (correct[i] != bounds_query_count[i]) { printf("bounds_query_count[%d] was supposed to be %d but instead is %d\n", i, correct[i], bounds_query_count[i]); exit(-1); } } } void check_counts(int a = 0, int b = 0, int c = 0, int d = 0) { int correct[] = {a, b, c, d}; for (int i = 0; i < 4; i++) { if (correct[i] != call_count[i]) { printf("call_count[%d] was supposed to be %d but instead is %d\n", i, correct[i], call_count[i]); exit(-1); } } } int main(int argc, char **argv) { Var x; Param<bool> toggle1, toggle2; { // Make a diamond-shaped graph where only one of the two // Side-lobes is used. Func f1, f2, f3, f4; f1(x) = cast<uint8_t>(x); f2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1, Expr(1), Expr(0)), UInt(8), 1); f3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1, Expr(2), Expr(1)), UInt(8), 1); f4(x) = select(toggle1, f2(x), f3(x)); f1.compute_root(); f2.compute_root(); f3.compute_root(); f4.compile_jit(); reset_counts(); toggle1.set(true); Image<uint8_t> result1 = f4.realize(10); for (int32_t i = 0; i < 10; i++) { assert(result1(i) == i + 1); } check_queries(1, 1); check_counts(1, 0); reset_counts(); toggle1.set(false); Image<uint8_t> result2 = f4.realize(10); for (int32_t i = 0; i < 10; i++) { assert(result2(i) == i + 2); } check_queries(1, 1); check_counts(0, 1); } { // Make a diamond-shaped graph where the first node can be // used in one of two ways. Func f1, f2, f3, f4; Func identity; identity(x) = x; f1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(0)), UInt(8), 1); Func f1_plus_one; f1_plus_one(x) = f1(x) + 1; f2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1_plus_one, Expr(1), Expr(1)), UInt(8), 1); f3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1_plus_one, Expr(1), Expr(2)), UInt(8), 1); f4(x) = select(toggle1, f2(x), 0) + select(toggle2, f3(x), 0); identity.compute_root(); f1_plus_one.compute_root(); f1.compute_root(); f2.compute_root(); f3.compute_root(); f4.compile_jit(); reset_counts(); toggle1.set(true); toggle2.set(true); f4.realize(10); check_counts(1, 1, 1); reset_counts(); toggle1.set(false); toggle2.set(true); f4.realize(10); check_counts(1, 0, 1); reset_counts(); toggle1.set(true); toggle2.set(false); f4.realize(10); check_counts(1, 1, 0); reset_counts(); toggle1.set(false); toggle2.set(false); f4.realize(10); check_counts(0, 0, 0); } { // Make a tuple-valued func where one value is used but the // other isn't. Currently we need to evaluate both, because we // have no way to turn only one of them off, and there might // be a recursive dependence of one on the other in an update // step. Func identity; identity(x) = x; Func extern1, extern2, f1, f2; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); f1(x) = Tuple(extern1(x), extern2(x+1)); f2(x) = select(toggle1, f1(x)[0], 0) + f1(x)[1]; identity.compute_root(); extern1.compute_root(); extern2.compute_root(); f1.compute_root(); f2.compile_jit(); reset_counts(); toggle1.set(true); f2.realize(10); check_counts(1, 1); reset_counts(); toggle1.set(false); f2.realize(10); check_counts(1, 1); } { // Make a tuple-valued func where neither value is used when // the toggle is false. Func identity; identity(x) = x; Func extern1, extern2, f1, f2; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); f1(x) = Tuple(extern1(x), extern2(x+1)); f2(x) = select(toggle1, f1(x)[0], 0); identity.compute_root(); extern1.compute_root(); extern2.compute_root(); f1.compute_root(); f2.realize(10); f2.compile_jit(); reset_counts(); toggle1.set(true); f2.realize(10); check_counts(1, 1); reset_counts(); toggle1.set(false); f2.realize(10); check_counts(0, 0); } { // Make our two-toggle diamond-shaped graph again, but use a more complex schedule. Func identity; identity(x) = x; Func extern1, extern2, extern3, f1, f2, f3, f4; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); extern3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(2)), UInt(8), 1); f1(x) = extern1(x); f2(x) = extern2(f1(x) + 1); f3(x) = extern3(f1(x) + 1); f4(x) = select(toggle1, f2(x), 0) + select(toggle2, f3(x), 0); identity.compute_root(); extern1.compute_root(); extern2.compute_root(); extern3.compute_root(); Var xo, xi; f4.split(x, xo, xi, 5); f1.compute_at(f4, xo); f2.store_root().compute_at(f4, xo); f3.store_at(f4, xo).compute_at(f4, xi); f4.compile_jit(); reset_counts(); toggle1.set(true); toggle2.set(true); f4.realize(10); check_counts(1, 1, 1); reset_counts(); toggle1.set(false); toggle2.set(true); f4.realize(10); check_counts(1, 0, 1); reset_counts(); toggle1.set(true); toggle2.set(false); f4.realize(10); check_counts(1, 1, 0); reset_counts(); toggle1.set(false); toggle2.set(false); f4.realize(10); check_counts(0, 0, 0); } printf("Success!\n"); return 0; }
#include <Halide.h> #include <stdio.h> using namespace Halide; #ifdef _MSC_VER #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif int bounds_query_count[4]; int call_count[4]; extern "C" DLLEXPORT int call_counter(buffer_t *input, int x, int idx, buffer_t *output) { if (input->host == NULL) { bounds_query_count[idx]++; input->min[0] = output->min[0]; input->extent[0] = output->extent[0]; input->elem_size = 1; return 0; } call_count[idx]++; for (int32_t i = 0; i < output->extent[0]; i++) { output->host[i] = input->host[i] + x; } return 0; } void reset_counts() { for (int i = 0; i < 4; i++) { bounds_query_count[i] = 0; call_count[i] = 0; } } void check_queries(int a = 0, int b = 0, int c = 0, int d = 0) { int correct[] = {a, b, c, d}; for (int i = 0; i < 4; i++) { if (correct[i] != bounds_query_count[i]) { printf("bounds_query_count[%d] was supposed to be %d but instead is %d\n", i, correct[i], bounds_query_count[i]); exit(-1); } } } void check_counts(int a = 0, int b = 0, int c = 0, int d = 0) { int correct[] = {a, b, c, d}; for (int i = 0; i < 4; i++) { if (correct[i] != call_count[i]) { printf("call_count[%d] was supposed to be %d but instead is %d\n", i, correct[i], call_count[i]); exit(-1); } } } int main(int argc, char **argv) { Var x; Param<bool> toggle1, toggle2; { // Make a diamond-shaped graph where only one of the two // Side-lobes is used. Func f1, f2, f3, f4; f1(x) = cast<uint8_t>(x); f2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1, Expr(1), Expr(0)), UInt(8), 1); f3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1, Expr(2), Expr(1)), UInt(8), 1); f4(x) = select(toggle1, f2(x), f3(x)); f1.compute_root(); f2.compute_root(); f3.compute_root(); f4.compile_jit(); reset_counts(); toggle1.set(true); Image<uint8_t> result1 = f4.realize(10); for (int32_t i = 0; i < 10; i++) { assert(result1(i) == i + 1); } check_queries(1, 1); check_counts(1, 0); reset_counts(); toggle1.set(false); Image<uint8_t> result2 = f4.realize(10); for (int32_t i = 0; i < 10; i++) { assert(result2(i) == i + 2); } check_queries(1, 1); check_counts(0, 1); } { // Make a diamond-shaped graph where the first node can be // used in one of two ways. Func f1, f2, f3, f4; Func identity; identity(x) = x; f1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(0)), UInt(8), 1); Func f1_plus_one; f1_plus_one(x) = f1(x) + 1; f2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1_plus_one, Expr(1), Expr(1)), UInt(8), 1); f3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(f1_plus_one, Expr(1), Expr(2)), UInt(8), 1); f4(x) = select(toggle1, f2(x), 0) + select(toggle2, f3(x), 0); identity.compute_root(); f1_plus_one.compute_root(); f1.compute_root(); f2.compute_root(); f3.compute_root(); f4.compile_jit(); reset_counts(); toggle1.set(true); toggle2.set(true); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 1, 1); reset_counts(); toggle1.set(false); toggle2.set(true); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 0, 1); reset_counts(); toggle1.set(true); toggle2.set(false); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 1, 0); reset_counts(); toggle1.set(false); toggle2.set(false); f4.realize(10); check_queries(1, 1, 1); check_counts(0, 0, 0); } { // Make a tuple-valued func where one value is used but the // other isn't. Currently we need to evaluate both, because we // have no way to turn only one of them off, and there might // be a recursive dependence of one on the other in an update // step. Func identity; identity(x) = x; Func extern1, extern2, f1, f2; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); f1(x) = Tuple(extern1(x), extern2(x+1)); f2(x) = select(toggle1, f1(x)[0], 0) + f1(x)[1]; identity.compute_root(); extern1.compute_root(); extern2.compute_root(); f1.compute_root(); f2.compile_jit(); reset_counts(); toggle1.set(true); f2.realize(10); check_queries(1, 1); check_counts(1, 1); reset_counts(); toggle1.set(false); f2.realize(10); check_queries(1, 1); check_counts(1, 1); } { // Make a tuple-valued func where neither value is used when // the toggle is false. Func identity; identity(x) = x; Func extern1, extern2, f1, f2; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); f1(x) = Tuple(extern1(x), extern2(x+1)); f2(x) = select(toggle1, f1(x)[0], 0); identity.compute_root(); extern1.compute_root(); extern2.compute_root(); f1.compute_root(); f2.realize(10); f2.compile_jit(); reset_counts(); toggle1.set(true); f2.realize(10); check_queries(1, 1); check_counts(1, 1); reset_counts(); toggle1.set(false); f2.realize(10); check_queries(1, 1); check_counts(0, 0); } { // Make our two-toggle diamond-shaped graph again, but use a more complex schedule. Func identity; identity(x) = x; Func extern1, extern2, extern3, f1, f2, f3, f4; extern1.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(0), Expr(0)), UInt(8), 1); extern2.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(1)), UInt(8), 1); extern3.define_extern("call_counter", Internal::vec<ExternFuncArgument>(identity, Expr(1), Expr(2)), UInt(8), 1); f1(x) = extern1(x); f2(x) = extern2(f1(x) + 1); f3(x) = extern3(f1(x) + 1); f4(x) = select(toggle1, f2(x), 0) + select(toggle2, f3(x), 0); identity.compute_root(); extern1.compute_root(); extern2.compute_root(); extern3.compute_root(); Var xo, xi; f4.split(x, xo, xi, 5); f1.compute_at(f4, xo); f2.store_root().compute_at(f4, xo); f3.store_at(f4, xo).compute_at(f4, xi); f4.compile_jit(); reset_counts(); toggle1.set(true); toggle2.set(true); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 1, 1); reset_counts(); toggle1.set(false); toggle2.set(true); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 0, 1); reset_counts(); toggle1.set(true); toggle2.set(false); f4.realize(10); check_queries(1, 1, 1); check_counts(1, 1, 0); reset_counts(); toggle1.set(false); toggle2.set(false); f4.realize(10); check_queries(1, 1, 1); check_counts(0, 0, 0); } printf("Success!\n"); return 0; }
Add additional checks to verify the right number of bounds inference queries.
Add additional checks to verify the right number of bounds inference queries. Former-commit-id: 1d13aeb6ce532a06648ca413c7690793275a849b
C++
mit
darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide
a99e49a85676efb25ee53324c4d463f4c3fb76d4
src/modules/landing_target_estimator/LandingTargetEstimator.cpp
src/modules/landing_target_estimator/LandingTargetEstimator.cpp
/**************************************************************************** * * Copyright (c) 2013-2018 PX4 Development Team. 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 PX4 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 OWNER 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. * ****************************************************************************/ /* * @file LandingTargetEstimator.cpp * * @author Nicolas de Palezieux (Sunflower Labs) <[email protected]> * @author Mohammed Kabir <[email protected]> * */ #include <px4_config.h> #include <px4_defines.h> #include <drivers/drv_hrt.h> #include "LandingTargetEstimator.h" #define SEC2USEC 1000000.0f namespace landing_target_estimator { LandingTargetEstimator::LandingTargetEstimator() : _targetPosePub(nullptr), _targetInnovationsPub(nullptr), _paramHandle(), _vehicleLocalPosition_valid(false), _vehicleAttitude_valid(false), _sensorBias_valid(false), _new_irlockReport(false), _estimator_initialized(false), _faulty(false), _last_predict(0), _last_update(0) { _paramHandle.acc_unc = param_find("LTEST_ACC_UNC"); _paramHandle.meas_unc = param_find("LTEST_MEAS_UNC"); _paramHandle.pos_unc_init = param_find("LTEST_POS_UNC_IN"); _paramHandle.vel_unc_init = param_find("LTEST_VEL_UNC_IN"); _paramHandle.mode = param_find("LTEST_MODE"); _paramHandle.scale_x = param_find("LTEST_SCALE_X"); _paramHandle.scale_y = param_find("LTEST_SCALE_Y"); // Initialize uORB topics. _initialize_topics(); _check_params(true); } LandingTargetEstimator::~LandingTargetEstimator() { } void LandingTargetEstimator::update() { _check_params(false); _update_topics(); /* predict */ if (_estimator_initialized) { if (hrt_absolute_time() - _last_update > landing_target_estimator_TIMEOUT_US) { PX4_WARN("Timeout"); _estimator_initialized = false; } else { float dt = (hrt_absolute_time() - _last_predict) / SEC2USEC; // predict target position with the help of accel data matrix::Vector3f a; if (_vehicleAttitude_valid && _sensorBias_valid) { matrix::Quaternion<float> q_att(&_vehicleAttitude.q[0]); _R_att = matrix::Dcm<float>(q_att); a(0) = _sensorBias.accel_x; a(1) = _sensorBias.accel_y; a(2) = _sensorBias.accel_z; a = _R_att * a; } else { a.zero(); } _kalman_filter_x.predict(dt, -a(0), _params.acc_unc); _kalman_filter_y.predict(dt, -a(1), _params.acc_unc); _last_predict = hrt_absolute_time(); } } if (!_new_irlockReport) { // nothing to do return; } // mark this sensor measurement as consumed _new_irlockReport = false; if (!_vehicleAttitude_valid || !_vehicleLocalPosition_valid || !_vehicleLocalPosition.dist_bottom_valid) { // don't have the data needed for an update return; } if (!PX4_ISFINITE(_irlockReport.pos_y) || !PX4_ISFINITE(_irlockReport.pos_x)) { return; } // TODO account for sensor orientation as set by parameter // default orientation has camera x pointing in body y, camera y in body -x matrix::Vector<float, 3> sensor_ray; // ray pointing towards target in body frame sensor_ray(0) = -_irlockReport.pos_y * _params.scale_y; // forward sensor_ray(1) = _irlockReport.pos_x * _params.scale_x; // right sensor_ray(2) = 1.0f; // rotate the unit ray into the navigation frame, assume sensor frame = body frame matrix::Quaternion<float> q_att(&_vehicleAttitude.q[0]); _R_att = matrix::Dcm<float>(q_att); sensor_ray = _R_att * sensor_ray; if (fabsf(sensor_ray(2)) < 1e-6f) { // z component of measurement unsafe, don't use this measurement return; } float dist = _vehicleLocalPosition.dist_bottom; // scale the ray s.t. the z component has length of dist _rel_pos(0) = sensor_ray(0) / sensor_ray(2) * dist; _rel_pos(1) = sensor_ray(1) / sensor_ray(2) * dist; if (!_estimator_initialized) { PX4_INFO("Init"); float vx_init = _vehicleLocalPosition.v_xy_valid ? -_vehicleLocalPosition.vx : 0.f; float vy_init = _vehicleLocalPosition.v_xy_valid ? -_vehicleLocalPosition.vy : 0.f; _kalman_filter_x.init(_rel_pos(0), vx_init, _params.pos_unc_init, _params.vel_unc_init); _kalman_filter_y.init(_rel_pos(1), vy_init, _params.pos_unc_init, _params.vel_unc_init); _estimator_initialized = true; _last_update = hrt_absolute_time(); _last_predict = _last_update; } else { // update bool update_x = _kalman_filter_x.update(_rel_pos(0), _params.meas_unc * dist * dist); bool update_y = _kalman_filter_y.update(_rel_pos(1), _params.meas_unc * dist * dist); if (!update_x || !update_y) { if (!_faulty) { _faulty = true; PX4_WARN("Landing target measurement rejected:%s%s", update_x ? "" : " x", update_y ? "" : " y"); } } else { _faulty = false; } if (!_faulty) { // only publish if both measurements were good _target_pose.timestamp = _irlockReport.timestamp; float x, xvel, y, yvel, covx, covx_v, covy, covy_v; _kalman_filter_x.getState(x, xvel); _kalman_filter_x.getCovariance(covx, covx_v); _kalman_filter_y.getState(y, yvel); _kalman_filter_y.getCovariance(covy, covy_v); _target_pose.is_static = (_params.mode == TargetMode::Stationary); _target_pose.rel_pos_valid = true; _target_pose.rel_vel_valid = true; _target_pose.x_rel = x; _target_pose.y_rel = y; _target_pose.z_rel = dist; _target_pose.vx_rel = xvel; _target_pose.vy_rel = yvel; _target_pose.cov_x_rel = covx; _target_pose.cov_y_rel = covy; _target_pose.cov_vx_rel = covx_v; _target_pose.cov_vy_rel = covy_v; if (_vehicleLocalPosition_valid && _vehicleLocalPosition.xy_valid) { _target_pose.x_abs = x + _vehicleLocalPosition.x; _target_pose.y_abs = y + _vehicleLocalPosition.y; _target_pose.z_abs = dist + _vehicleLocalPosition.z; _target_pose.abs_pos_valid = true; } else { _target_pose.abs_pos_valid = false; } if (_targetPosePub == nullptr) { _targetPosePub = orb_advertise(ORB_ID(landing_target_pose), &_target_pose); } else { orb_publish(ORB_ID(landing_target_pose), _targetPosePub, &_target_pose); } _last_update = hrt_absolute_time(); _last_predict = _last_update; } float innov_x, innov_cov_x, innov_y, innov_cov_y; _kalman_filter_x.getInnovations(innov_x, innov_cov_x); _kalman_filter_y.getInnovations(innov_y, innov_cov_y); _target_innovations.timestamp = _irlockReport.timestamp; _target_innovations.innov_x = innov_x; _target_innovations.innov_cov_x = innov_cov_x; _target_innovations.innov_y = innov_y; _target_innovations.innov_cov_y = innov_cov_y; if (_targetInnovationsPub == nullptr) { _targetInnovationsPub = orb_advertise(ORB_ID(landing_target_innovations), &_target_innovations); } else { orb_publish(ORB_ID(landing_target_innovations), _targetInnovationsPub, &_target_innovations); } } } void LandingTargetEstimator::_check_params(const bool force) { bool updated; parameter_update_s paramUpdate; orb_check(_parameterSub, &updated); if (updated) { orb_copy(ORB_ID(parameter_update), _parameterSub, &paramUpdate); } if (updated || force) { _update_params(); } } void LandingTargetEstimator::_initialize_topics() { _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _sensorBiasSub = orb_subscribe(ORB_ID(sensor_bias)); _irlockReportSub = orb_subscribe(ORB_ID(irlock_report)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); } void LandingTargetEstimator::_update_topics() { _vehicleLocalPosition_valid = _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _vehicleAttitude_valid = _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _sensorBias_valid = _orb_update(ORB_ID(sensor_bias), _sensorBiasSub, &_sensorBias); _new_irlockReport = _orb_update(ORB_ID(irlock_report), _irlockReportSub, &_irlockReport); } bool LandingTargetEstimator::_orb_update(const struct orb_metadata *meta, int handle, void *buffer) { bool newData = false; // check if there is new data to grab if (orb_check(handle, &newData) != OK) { return false; } if (!newData) { return false; } if (orb_copy(meta, handle, buffer) != OK) { return false; } return true; } void LandingTargetEstimator::_update_params() { param_get(_paramHandle.acc_unc, &_params.acc_unc); param_get(_paramHandle.meas_unc, &_params.meas_unc); param_get(_paramHandle.pos_unc_init, &_params.pos_unc_init); param_get(_paramHandle.vel_unc_init, &_params.vel_unc_init); int mode = 0; param_get(_paramHandle.mode, &mode); _params.mode = (TargetMode)mode; param_get(_paramHandle.scale_x, &_params.scale_x); param_get(_paramHandle.scale_y, &_params.scale_y); } } // namespace landing_target_estimator
/**************************************************************************** * * Copyright (c) 2013-2018 PX4 Development Team. 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 PX4 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 OWNER 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. * ****************************************************************************/ /* * @file LandingTargetEstimator.cpp * * @author Nicolas de Palezieux (Sunflower Labs) <[email protected]> * @author Mohammed Kabir <[email protected]> * */ #include <px4_config.h> #include <px4_defines.h> #include <drivers/drv_hrt.h> #include "LandingTargetEstimator.h" #define SEC2USEC 1000000.0f namespace landing_target_estimator { LandingTargetEstimator::LandingTargetEstimator() : _targetPosePub(nullptr), _targetInnovationsPub(nullptr), _paramHandle(), _vehicleLocalPosition_valid(false), _vehicleAttitude_valid(false), _sensorBias_valid(false), _new_irlockReport(false), _estimator_initialized(false), _faulty(false), _last_predict(0), _last_update(0) { _paramHandle.acc_unc = param_find("LTEST_ACC_UNC"); _paramHandle.meas_unc = param_find("LTEST_MEAS_UNC"); _paramHandle.pos_unc_init = param_find("LTEST_POS_UNC_IN"); _paramHandle.vel_unc_init = param_find("LTEST_VEL_UNC_IN"); _paramHandle.mode = param_find("LTEST_MODE"); _paramHandle.scale_x = param_find("LTEST_SCALE_X"); _paramHandle.scale_y = param_find("LTEST_SCALE_Y"); // Initialize uORB topics. _initialize_topics(); _check_params(true); } LandingTargetEstimator::~LandingTargetEstimator() { } void LandingTargetEstimator::update() { _check_params(false); _update_topics(); /* predict */ if (_estimator_initialized) { if (hrt_absolute_time() - _last_update > landing_target_estimator_TIMEOUT_US) { PX4_WARN("Timeout"); _estimator_initialized = false; } else { float dt = (hrt_absolute_time() - _last_predict) / SEC2USEC; // predict target position with the help of accel data matrix::Vector3f a; if (_vehicleAttitude_valid && _sensorBias_valid) { matrix::Quaternion<float> q_att(&_vehicleAttitude.q[0]); _R_att = matrix::Dcm<float>(q_att); a(0) = _sensorBias.accel_x; a(1) = _sensorBias.accel_y; a(2) = _sensorBias.accel_z; a = _R_att * a; } else { a.zero(); } _kalman_filter_x.predict(dt, -a(0), _params.acc_unc); _kalman_filter_y.predict(dt, -a(1), _params.acc_unc); _last_predict = hrt_absolute_time(); } } if (!_new_irlockReport) { // nothing to do return; } // mark this sensor measurement as consumed _new_irlockReport = false; if (!_vehicleAttitude_valid || !_vehicleLocalPosition_valid || !_vehicleLocalPosition.dist_bottom_valid) { // don't have the data needed for an update return; } if (!PX4_ISFINITE(_irlockReport.pos_y) || !PX4_ISFINITE(_irlockReport.pos_x)) { return; } // TODO account for sensor orientation as set by parameter // default orientation has camera x pointing in body y, camera y in body -x matrix::Vector<float, 3> sensor_ray; // ray pointing towards target in body frame sensor_ray(0) = -_irlockReport.pos_y * _params.scale_y; // forward sensor_ray(1) = _irlockReport.pos_x * _params.scale_x; // right sensor_ray(2) = 1.0f; // rotate the unit ray into the navigation frame, assume sensor frame = body frame matrix::Quaternion<float> q_att(&_vehicleAttitude.q[0]); _R_att = matrix::Dcm<float>(q_att); sensor_ray = _R_att * sensor_ray; if (fabsf(sensor_ray(2)) < 1e-6f) { // z component of measurement unsafe, don't use this measurement return; } float dist = _vehicleLocalPosition.dist_bottom; // scale the ray s.t. the z component has length of dist _rel_pos(0) = sensor_ray(0) / sensor_ray(2) * dist; _rel_pos(1) = sensor_ray(1) / sensor_ray(2) * dist; if (!_estimator_initialized) { PX4_INFO("Init"); float vx_init = _vehicleLocalPosition.v_xy_valid ? -_vehicleLocalPosition.vx : 0.f; float vy_init = _vehicleLocalPosition.v_xy_valid ? -_vehicleLocalPosition.vy : 0.f; _kalman_filter_x.init(_rel_pos(0), vx_init, _params.pos_unc_init, _params.vel_unc_init); _kalman_filter_y.init(_rel_pos(1), vy_init, _params.pos_unc_init, _params.vel_unc_init); _estimator_initialized = true; _last_update = hrt_absolute_time(); _last_predict = _last_update; } else { // update bool update_x = _kalman_filter_x.update(_rel_pos(0), _params.meas_unc * dist * dist); bool update_y = _kalman_filter_y.update(_rel_pos(1), _params.meas_unc * dist * dist); if (!update_x || !update_y) { if (!_faulty) { _faulty = true; PX4_WARN("Landing target measurement rejected:%s%s", update_x ? "" : " x", update_y ? "" : " y"); } } else { _faulty = false; } if (!_faulty) { // only publish if both measurements were good _target_pose.timestamp = _irlockReport.timestamp; float x, xvel, y, yvel, covx, covx_v, covy, covy_v; _kalman_filter_x.getState(x, xvel); _kalman_filter_x.getCovariance(covx, covx_v); _kalman_filter_y.getState(y, yvel); _kalman_filter_y.getCovariance(covy, covy_v); _target_pose.is_static = (_params.mode == TargetMode::Stationary); _target_pose.rel_pos_valid = true; _target_pose.rel_vel_valid = true; _target_pose.x_rel = x; _target_pose.y_rel = y; _target_pose.z_rel = dist; _target_pose.vx_rel = xvel; _target_pose.vy_rel = yvel; _target_pose.cov_x_rel = covx; _target_pose.cov_y_rel = covy; _target_pose.cov_vx_rel = covx_v; _target_pose.cov_vy_rel = covy_v; if (_vehicleLocalPosition_valid && _vehicleLocalPosition.xy_valid) { _target_pose.x_abs = x + _vehicleLocalPosition.x; _target_pose.y_abs = y + _vehicleLocalPosition.y; _target_pose.z_abs = dist + _vehicleLocalPosition.z; _target_pose.abs_pos_valid = true; } else { _target_pose.abs_pos_valid = false; } if (_targetPosePub == nullptr) { _targetPosePub = orb_advertise(ORB_ID(landing_target_pose), &_target_pose); } else { orb_publish(ORB_ID(landing_target_pose), _targetPosePub, &_target_pose); } _last_update = hrt_absolute_time(); _last_predict = _last_update; } float innov_x, innov_cov_x, innov_y, innov_cov_y; _kalman_filter_x.getInnovations(innov_x, innov_cov_x); _kalman_filter_y.getInnovations(innov_y, innov_cov_y); _target_innovations.timestamp = _irlockReport.timestamp; _target_innovations.innov_x = innov_x; _target_innovations.innov_cov_x = innov_cov_x; _target_innovations.innov_y = innov_y; _target_innovations.innov_cov_y = innov_cov_y; if (_targetInnovationsPub == nullptr) { _targetInnovationsPub = orb_advertise(ORB_ID(landing_target_innovations), &_target_innovations); } else { orb_publish(ORB_ID(landing_target_innovations), _targetInnovationsPub, &_target_innovations); } } } void LandingTargetEstimator::_check_params(const bool force) { bool updated; parameter_update_s paramUpdate; orb_check(_parameterSub, &updated); if (updated) { orb_copy(ORB_ID(parameter_update), _parameterSub, &paramUpdate); } if (updated || force) { _update_params(); } } void LandingTargetEstimator::_initialize_topics() { _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _sensorBiasSub = orb_subscribe(ORB_ID(sensor_bias)); _irlockReportSub = orb_subscribe(ORB_ID(irlock_report)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); } void LandingTargetEstimator::_update_topics() { _vehicleLocalPosition_valid = _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _vehicleAttitude_valid = _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _sensorBias_valid = _orb_update(ORB_ID(sensor_bias), _sensorBiasSub, &_sensorBias); _new_irlockReport = _orb_update(ORB_ID(irlock_report), _irlockReportSub, &_irlockReport); } bool LandingTargetEstimator::_orb_update(const struct orb_metadata *meta, int handle, void *buffer) { bool newData = false; // check if there is new data to grab if (orb_check(handle, &newData) != OK) { return false; } if (!newData) { return false; } if (orb_copy(meta, handle, buffer) != OK) { return false; } return true; } void LandingTargetEstimator::_update_params() { param_get(_paramHandle.acc_unc, &_params.acc_unc); param_get(_paramHandle.meas_unc, &_params.meas_unc); param_get(_paramHandle.pos_unc_init, &_params.pos_unc_init); param_get(_paramHandle.vel_unc_init, &_params.vel_unc_init); int32_t mode = 0; param_get(_paramHandle.mode, &mode); _params.mode = (TargetMode)mode; param_get(_paramHandle.scale_x, &_params.scale_x); param_get(_paramHandle.scale_y, &_params.scale_y); } } // namespace landing_target_estimator
fix param type: int -> int32_t
landing_target_estimator: fix param type: int -> int32_t
C++
bsd-3-clause
krbeverx/Firmware,dagar/Firmware,dagar/Firmware,krbeverx/Firmware,Aerotenna/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,PX4/Firmware,mje-nz/PX4-Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,dagar/Firmware,krbeverx/Firmware,PX4/Firmware,mcgill-robotics/Firmware,mcgill-robotics/Firmware,acfloria/Firmware,krbeverx/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,dagar/Firmware,Aerotenna/Firmware,dagar/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,PX4/Firmware,PX4/Firmware,dagar/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,dagar/Firmware,mcgill-robotics/Firmware,acfloria/Firmware,PX4/Firmware,mcgill-robotics/Firmware,acfloria/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,acfloria/Firmware,mcgill-robotics/Firmware,PX4/Firmware,krbeverx/Firmware,PX4/Firmware
e9b906eb772a5fad8d33017b99a3a541a26b189f
src/DataViews/DataView.cpp
src/DataViews/DataView.cpp
// Copyright (c) 2021 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "DataViews/DataView.h" #include <absl/strings/str_replace.h> #include <memory> #include "OrbitBase/File.h" #include "OrbitBase/Logging.h" using orbit_client_data::ModuleData; using orbit_client_data::ProcessData; using orbit_client_protos::FunctionInfo; namespace orbit_data_views { std::string FormatValueForCsv(std::string_view value) { std::string result; result.append("\""); result.append(absl::StrReplaceAll(value, {{"\"", "\"\""}})); result.append("\""); return result; } void DataView::InitSortingOrders() { sorting_orders_.clear(); for (const auto& column : GetColumns()) { sorting_orders_.push_back(column.initial_order); } sorting_column_ = GetDefaultSortingColumn(); } void DataView::OnSort(int column, std::optional<SortingOrder> new_order) { if (column < 0) { return; } if (!IsSortingAllowed()) { return; } if (sorting_orders_.empty()) { InitSortingOrders(); } sorting_column_ = column; if (new_order.has_value()) { sorting_orders_[column] = new_order.value(); } DoSort(); } void DataView::OnFilter(const std::string& filter) { filter_ = filter; DoFilter(); OnSort(sorting_column_, {}); } void DataView::SetUiFilterString(const std::string& filter) { if (filter_callback_) { filter_callback_(filter); } } void DataView::OnDataChanged() { DoFilter(); OnSort(sorting_column_, std::optional<SortingOrder>{}); } std::vector<std::vector<std::string>> DataView::GetContextMenuWithGrouping( int /*clicked_index*/, const std::vector<int>& selected_indices) { // GetContextmenuWithGrouping is called when OrbitTreeView::indexAt returns a valid index and // hence the selected_indices retrieved from OrbitTreeView::selectionModel()->selectedIndexes() // should not be empty. CHECK(!selected_indices.empty()); static std::vector<std::string> default_group = {std::string{kMenuActionCopySelection}, std::string{kMenuActionExportToCsv}}; return {default_group}; } void DataView::OnContextMenu(const std::string& action, int /*menu_index*/, const std::vector<int>& item_indices) { if (action == kMenuActionLoadSymbols) { OnLoadSymbolsRequested(item_indices); } else if (action == kMenuActionSelect) { OnSelectRequested(item_indices); } else if (action == kMenuActionUnselect) { OnUnselectRequested(item_indices); } else if (action == kMenuActionEnableFrameTrack) { OnEnableFrameTrackRequested(item_indices); } else if (action == kMenuActionDisableFrameTrack) { OnDisableFrameTrackRequested(item_indices); } else if (action == kMenuActionAddIterator) { OnIteratorRequested(item_indices); } else if (action == kMenuActionVerifyFramePointers) { OnVerifyFramePointersRequested(item_indices); } else if (action == kMenuActionDisassembly) { OnDisassemblyRequested(item_indices); } else if (action == kMenuActionSourceCode) { OnSourceCodeRequested(item_indices); } else if (action == kMenuActionJumpToFirst || action == kMenuActionJumpToLast || action == kMenuActionJumpToMin || action == kMenuActionJumpToMax) { OnJumpToRequested(action, item_indices); } else if (action == kMenuActionLoadPreset) { OnLoadPresetRequested(item_indices); } else if (action == kMenuActionDeletePreset) { OnDeletePresetRequested(item_indices); } else if (action == kMenuActionShowInExplorer) { OnShowInExplorerRequested(item_indices); } else if (action == kMenuActionExportToCsv) { OnExportToCsvRequested(); } else if (action == kMenuActionCopySelection) { OnCopySelectionRequested(item_indices); } else if (action == kMenuActionExportEventsToCsv) { OnExportEventsToCsvRequested(item_indices); } } std::vector<int> DataView::GetVisibleSelectedIndices() { std::vector<int> visible_selected_indices; for (size_t row = 0; row < indices_.size(); ++row) { if (selected_indices_.contains(indices_[row])) { visible_selected_indices.push_back(static_cast<int>(row)); } } return visible_selected_indices; } void DataView::OnLoadSymbolsRequested(const std::vector<int>& selection) { std::vector<ModuleData*> modules_to_load; for (int index : selection) { ModuleData* module_data = GetModuleDataFromRow(index); if (module_data != nullptr && !module_data->is_loaded()) { modules_to_load.push_back(module_data); } } app_->RetrieveModulesAndLoadSymbols(modules_to_load); } void DataView::OnSelectRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); // Only hook functions for which we have symbols loaded. if (function != nullptr) { app_->SelectFunction(*function); } } } void DataView::OnUnselectRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); // If the frame belongs to a function for which no symbol is loaded 'function' is nullptr and // we can skip it since it can't be instrumented. if (function != nullptr) { app_->DeselectFunction(*function); // Unhooking a function implies disabling (and removing) the frame track for this function. // While it would be possible to keep the current frame track in the capture data, this would // lead to a somewhat inconsistent state where the frame track for this function is enabled // for the current capture but disabled for the next one. app_->DisableFrameTrack(*function); app_->RemoveFrameTrack(*function); } } } void DataView::OnEnableFrameTrackRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo& function = *GetFunctionInfoFromRow(i); // Functions used as frame tracks must be hooked (selected), otherwise the // data to produce the frame track will not be captured. if (app_->IsCaptureConnected(app_->GetCaptureData())) { app_->SelectFunction(function); } app_->EnableFrameTrack(function); app_->AddFrameTrack(function); } } void DataView::OnDisableFrameTrackRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo& function = *GetFunctionInfoFromRow(i); // When we remove a frame track, we do not unhook (deselect) the function as // it may have been selected manually (not as part of adding a frame track). // However, disable the frame track, so it is not recreated on the next capture. app_->DisableFrameTrack(function); app_->RemoveFrameTrack(function); } } void DataView::OnVerifyFramePointersRequested(const std::vector<int>& selection) { std::vector<const ModuleData*> modules_to_validate; modules_to_validate.reserve(selection.size()); for (int i : selection) { const ModuleData* module = GetModuleDataFromRow(i); modules_to_validate.push_back(module); } if (!modules_to_validate.empty()) { app_->OnValidateFramePointers(modules_to_validate); } } void DataView::OnDisassemblyRequested(const std::vector<int>& selection) { const ProcessData* process_data = app_->GetTargetProcess(); const uint32_t pid = process_data == nullptr ? app_->GetCaptureData().process_id() : process_data->pid(); for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); if (function != nullptr) app_->Disassemble(pid, *function); } } void DataView::OnSourceCodeRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); if (function != nullptr) app_->ShowSourceCode(*function); } } void DataView::OnExportToCsvRequested() { std::string save_file = app_->GetSaveFile(".csv"); if (save_file.empty()) return; auto send_error = [&](const std::string& error_msg) { app_->SendErrorToUi(std::string{kMenuActionExportToCsv}, error_msg); }; ErrorMessageOr<orbit_base::unique_fd> result = orbit_base::OpenFileForWriting(save_file); if (result.has_error()) { send_error( absl::StrFormat("Failed to open \"%s\" file: %s", save_file, result.error().message())); return; } const orbit_base::unique_fd& fd = result.value(); constexpr const char* kFieldSeparator = ","; // CSV RFC requires lines to end with CRLF constexpr const char* kLineSeparator = "\r\n"; size_t num_columns = GetColumns().size(); { std::string header_line; for (size_t i = 0; i < num_columns; ++i) { header_line.append(FormatValueForCsv(GetColumns()[i].header)); if (i < num_columns - 1) header_line.append(kFieldSeparator); } header_line.append(kLineSeparator); auto write_result = orbit_base::WriteFully(fd, header_line); if (write_result.has_error()) { send_error(absl::StrFormat("Error writing to \"%s\": %s", save_file, write_result.error().message())); return; } } size_t num_elements = GetNumElements(); for (size_t i = 0; i < num_elements; ++i) { std::string line; for (size_t j = 0; j < num_columns; ++j) { line.append(FormatValueForCsv(GetValueForCopy(i, j))); if (j < num_columns - 1) line.append(kFieldSeparator); } line.append(kLineSeparator); auto write_result = orbit_base::WriteFully(fd, line); if (write_result.has_error()) { send_error(absl::StrFormat("Error writing to \"%s\": %s", save_file, write_result.error().message())); return; } } } void DataView::OnCopySelectionRequested(const std::vector<int>& selection) { constexpr const char* kFieldSeparator = "\t"; constexpr const char* kLineSeparator = "\n"; std::string clipboard; size_t num_columns = GetColumns().size(); for (size_t i = 0; i < num_columns; ++i) { clipboard += GetColumns()[i].header; if (i < num_columns - 1) clipboard.append(kFieldSeparator); } clipboard.append(kLineSeparator); size_t num_elements = GetNumElements(); for (size_t i : selection) { if (i >= num_elements) continue; for (size_t j = 0; j < num_columns; ++j) { clipboard += GetValueForCopy(i, j); if (j < num_columns - 1) clipboard.append(kFieldSeparator); } clipboard.append(kLineSeparator); } app_->SetClipboard(clipboard); } } // namespace orbit_data_views
// Copyright (c) 2021 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "DataViews/DataView.h" #include <absl/strings/str_replace.h> #include <memory> #include "OrbitBase/File.h" #include "OrbitBase/Logging.h" using orbit_client_data::ModuleData; using orbit_client_data::ProcessData; using orbit_client_protos::FunctionInfo; namespace orbit_data_views { std::string FormatValueForCsv(std::string_view value) { std::string result; result.append("\""); result.append(absl::StrReplaceAll(value, {{"\"", "\"\""}})); result.append("\""); return result; } void DataView::InitSortingOrders() { sorting_orders_.clear(); for (const auto& column : GetColumns()) { sorting_orders_.push_back(column.initial_order); } sorting_column_ = GetDefaultSortingColumn(); } void DataView::OnSort(int column, std::optional<SortingOrder> new_order) { if (column < 0) { return; } if (!IsSortingAllowed()) { return; } if (sorting_orders_.empty()) { InitSortingOrders(); } sorting_column_ = column; if (new_order.has_value()) { sorting_orders_[column] = new_order.value(); } DoSort(); } void DataView::OnFilter(const std::string& filter) { filter_ = filter; DoFilter(); OnSort(sorting_column_, {}); } void DataView::SetUiFilterString(const std::string& filter) { if (filter_callback_) { filter_callback_(filter); } } void DataView::OnDataChanged() { DoFilter(); OnSort(sorting_column_, std::optional<SortingOrder>{}); } std::vector<std::vector<std::string>> DataView::GetContextMenuWithGrouping( int /*clicked_index*/, const std::vector<int>& selected_indices) { // GetContextmenuWithGrouping is called when OrbitTreeView::indexAt returns a valid index and // hence the selected_indices retrieved from OrbitTreeView::selectionModel()->selectedIndexes() // should not be empty. CHECK(!selected_indices.empty()); static std::vector<std::string> default_group = {std::string{kMenuActionCopySelection}, std::string{kMenuActionExportToCsv}}; return {default_group}; } void DataView::OnContextMenu(const std::string& action, int /*menu_index*/, const std::vector<int>& item_indices) { if (action == kMenuActionLoadSymbols) { OnLoadSymbolsRequested(item_indices); } else if (action == kMenuActionSelect) { OnSelectRequested(item_indices); } else if (action == kMenuActionUnselect) { OnUnselectRequested(item_indices); } else if (action == kMenuActionEnableFrameTrack) { OnEnableFrameTrackRequested(item_indices); } else if (action == kMenuActionDisableFrameTrack) { OnDisableFrameTrackRequested(item_indices); } else if (action == kMenuActionAddIterator) { OnIteratorRequested(item_indices); } else if (action == kMenuActionVerifyFramePointers) { OnVerifyFramePointersRequested(item_indices); } else if (action == kMenuActionDisassembly) { OnDisassemblyRequested(item_indices); } else if (action == kMenuActionSourceCode) { OnSourceCodeRequested(item_indices); } else if (action == kMenuActionJumpToFirst || action == kMenuActionJumpToLast || action == kMenuActionJumpToMin || action == kMenuActionJumpToMax) { OnJumpToRequested(action, item_indices); } else if (action == kMenuActionLoadPreset) { OnLoadPresetRequested(item_indices); } else if (action == kMenuActionDeletePreset) { OnDeletePresetRequested(item_indices); } else if (action == kMenuActionShowInExplorer) { OnShowInExplorerRequested(item_indices); } else if (action == kMenuActionExportToCsv) { OnExportToCsvRequested(); } else if (action == kMenuActionCopySelection) { OnCopySelectionRequested(item_indices); } else if (action == kMenuActionExportEventsToCsv) { OnExportEventsToCsvRequested(item_indices); } } std::vector<int> DataView::GetVisibleSelectedIndices() { std::vector<int> visible_selected_indices; for (size_t row = 0; row < indices_.size(); ++row) { if (selected_indices_.contains(indices_[row])) { visible_selected_indices.push_back(static_cast<int>(row)); } } return visible_selected_indices; } void DataView::OnLoadSymbolsRequested(const std::vector<int>& selection) { std::vector<ModuleData*> modules_to_load; for (int index : selection) { ModuleData* module_data = GetModuleDataFromRow(index); if (module_data != nullptr && !module_data->is_loaded()) { modules_to_load.push_back(module_data); } } app_->RetrieveModulesAndLoadSymbols(modules_to_load); } void DataView::OnSelectRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); // Only hook functions for which we have symbols loaded. if (function != nullptr) { app_->SelectFunction(*function); } } } void DataView::OnUnselectRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); // If the frame belongs to a function for which no symbol is loaded 'function' is nullptr and // we can skip it since it can't be instrumented. if (function != nullptr) { app_->DeselectFunction(*function); // Unhooking a function implies disabling (and removing) the frame track for this function. // While it would be possible to keep the current frame track in the capture data, this would // lead to a somewhat inconsistent state where the frame track for this function is enabled // for the current capture but disabled for the next one. app_->DisableFrameTrack(*function); app_->RemoveFrameTrack(*function); } } } void DataView::OnEnableFrameTrackRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo& function = *GetFunctionInfoFromRow(i); // Functions used as frame tracks must be hooked (selected), otherwise the // data to produce the frame track will not be captured. app_->SelectFunction(function); app_->EnableFrameTrack(function); app_->AddFrameTrack(function); } } void DataView::OnDisableFrameTrackRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo& function = *GetFunctionInfoFromRow(i); // When we remove a frame track, we do not unhook (deselect) the function as // it may have been selected manually (not as part of adding a frame track). // However, disable the frame track, so it is not recreated on the next capture. app_->DisableFrameTrack(function); app_->RemoveFrameTrack(function); } } void DataView::OnVerifyFramePointersRequested(const std::vector<int>& selection) { std::vector<const ModuleData*> modules_to_validate; modules_to_validate.reserve(selection.size()); for (int i : selection) { const ModuleData* module = GetModuleDataFromRow(i); modules_to_validate.push_back(module); } if (!modules_to_validate.empty()) { app_->OnValidateFramePointers(modules_to_validate); } } void DataView::OnDisassemblyRequested(const std::vector<int>& selection) { const ProcessData* process_data = app_->GetTargetProcess(); const uint32_t pid = process_data == nullptr ? app_->GetCaptureData().process_id() : process_data->pid(); for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); if (function != nullptr) app_->Disassemble(pid, *function); } } void DataView::OnSourceCodeRequested(const std::vector<int>& selection) { for (int i : selection) { const FunctionInfo* function = GetFunctionInfoFromRow(i); if (function != nullptr) app_->ShowSourceCode(*function); } } void DataView::OnExportToCsvRequested() { std::string save_file = app_->GetSaveFile(".csv"); if (save_file.empty()) return; auto send_error = [&](const std::string& error_msg) { app_->SendErrorToUi(std::string{kMenuActionExportToCsv}, error_msg); }; ErrorMessageOr<orbit_base::unique_fd> result = orbit_base::OpenFileForWriting(save_file); if (result.has_error()) { send_error( absl::StrFormat("Failed to open \"%s\" file: %s", save_file, result.error().message())); return; } const orbit_base::unique_fd& fd = result.value(); constexpr const char* kFieldSeparator = ","; // CSV RFC requires lines to end with CRLF constexpr const char* kLineSeparator = "\r\n"; size_t num_columns = GetColumns().size(); { std::string header_line; for (size_t i = 0; i < num_columns; ++i) { header_line.append(FormatValueForCsv(GetColumns()[i].header)); if (i < num_columns - 1) header_line.append(kFieldSeparator); } header_line.append(kLineSeparator); auto write_result = orbit_base::WriteFully(fd, header_line); if (write_result.has_error()) { send_error(absl::StrFormat("Error writing to \"%s\": %s", save_file, write_result.error().message())); return; } } size_t num_elements = GetNumElements(); for (size_t i = 0; i < num_elements; ++i) { std::string line; for (size_t j = 0; j < num_columns; ++j) { line.append(FormatValueForCsv(GetValueForCopy(i, j))); if (j < num_columns - 1) line.append(kFieldSeparator); } line.append(kLineSeparator); auto write_result = orbit_base::WriteFully(fd, line); if (write_result.has_error()) { send_error(absl::StrFormat("Error writing to \"%s\": %s", save_file, write_result.error().message())); return; } } } void DataView::OnCopySelectionRequested(const std::vector<int>& selection) { constexpr const char* kFieldSeparator = "\t"; constexpr const char* kLineSeparator = "\n"; std::string clipboard; size_t num_columns = GetColumns().size(); for (size_t i = 0; i < num_columns; ++i) { clipboard += GetColumns()[i].header; if (i < num_columns - 1) clipboard.append(kFieldSeparator); } clipboard.append(kLineSeparator); size_t num_elements = GetNumElements(); for (size_t i : selection) { if (i >= num_elements) continue; for (size_t j = 0; j < num_columns; ++j) { clipboard += GetValueForCopy(i, j); if (j < num_columns - 1) clipboard.append(kFieldSeparator); } clipboard.append(kLineSeparator); } app_->SetClipboard(clipboard); } } // namespace orbit_data_views
Fix frametrack creation before capturing (#3172)
Fix frametrack creation before capturing (#3172) Bug: b/209611981
C++
bsd-2-clause
google/orbit,google/orbit,google/orbit,google/orbit
4ade0bdbea45b03492764c19dd84569c7204751a
connectivity/netsocket/tests/UNITTESTS/netsocket/DTLSSocket/test_DTLSSocket.cpp
connectivity/netsocket/tests/UNITTESTS/netsocket/DTLSSocket/test_DTLSSocket.cpp
/* * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * 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 "gtest/gtest.h" #include "netsocket/DTLSSocket.h" #include "NetworkStack_stub.h" #include "mbed_error.h" mbed_error_status_t mbed_error(mbed_error_status_t error_status, const char *error_msg, unsigned int error_value, const char *filename, int line_number) { return 0; } // Control the rtos EventFlags stub. See EventFlags_stub.cpp extern std::list<uint32_t> eventFlagsStubNextRetval; class TestDTLSSocket : public testing::Test { public: unsigned int dataSize = 10; char dataBuf[10]; protected: DTLSSocket *socket; NetworkStackstub stack; virtual void SetUp() { socket = new DTLSSocket(); } virtual void TearDown() { stack.return_values.clear(); eventFlagsStubNextRetval.clear(); delete socket; } }; TEST_F(TestDTLSSocket, constructor) { EXPECT_TRUE(socket); } /* connect */ TEST_F(TestDTLSSocket, connect) { socket->open(&stack); stack.return_value = NSAPI_ERROR_OK; SocketAddress a("127.0.0.1", 1024); EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); }
/* * Copyright (c) 2018, Arm Limited and affiliates * SPDX-License-Identifier: Apache-2.0 * * 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 "gtest/gtest.h" #include "netsocket/DTLSSocket.h" #include "NetworkStack_stub.h" #include "mbed_error.h" mbed_error_status_t mbed_error(mbed_error_status_t error_status, const char *error_msg, unsigned int error_value, const char *filename, int line_number) { return 0; } // Control the rtos EventFlags stub. See EventFlags_stub.cpp extern std::list<uint32_t> eventFlagsStubNextRetval; class TestDTLSSocket : public testing::Test { public: unsigned int dataSize = 10; char dataBuf[10]; protected: DTLSSocket *socket; NetworkStackstub stack; virtual void SetUp() { socket = new DTLSSocket(); } virtual void TearDown() { stack.return_values.clear(); eventFlagsStubNextRetval.clear(); delete socket; } }; TEST_F(TestDTLSSocket, constructor) { EXPECT_TRUE(socket); } /* connect */ TEST_F(TestDTLSSocket, connect) { socket->open(&stack); stack.return_value = NSAPI_ERROR_OK; SocketAddress a("127.0.0.1", 1024); stack.return_socketAddress = a; EXPECT_EQ(socket->connect(a), NSAPI_ERROR_OK); }
Fix DTLS socket unittest
CMake: Fix DTLS socket unittest - Binding the socket address into network stack to avoid socket connect API call hangs in the unittest
C++
apache-2.0
mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed
f376f470550edf8cb054fe4d78bf053319cf3149
src/accounts.cpp
src/accounts.cpp
//======================================================================= // Copyright Baptiste Wicht 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include "accounts.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "money.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" using namespace budget; namespace { static data_handler<account> accounts; void show_accounts(){ std::vector<std::string> columns = {"ID", "Name", "Amount"}; std::vector<std::vector<std::string>> contents; money total; for(auto& account : accounts.data){ if(account.until == boost::gregorian::date(2099,12,31)){ contents.push_back({to_string(account.id), account.name, to_string(account.amount)}); total += account.amount; } } contents.push_back({"", "Total", to_string(total)}); display_table(columns, contents); } void show_all_accounts(){ std::vector<std::string> columns = {"ID", "Name", "Amount", "Since", "Until"}; std::vector<std::vector<std::string>> contents; for(auto& account : accounts.data){ contents.push_back({to_string(account.id), account.name, to_string(account.amount), to_string(account.since), to_string(account.until)}); } display_table(columns, contents); } boost::gregorian::date find_new_since(){ boost::gregorian::date date(1400,1,1); for(auto& account : all_accounts()){ if(account.until != boost::gregorian::date(2099,12,31)){ if(account.until - boost::gregorian::date_duration(1) > date){ date = account.until - boost::gregorian::date_duration(1); } } } return date; } } //end of anonymous namespace void budget::accounts_module::handle(const std::vector<std::string>& args){ load_accounts(); if(args.size() == 1){ show_accounts(); } else { auto& subcommand = args[1]; if(subcommand == "show"){ show_accounts(); } else if(subcommand == "all"){ show_all_accounts(); } else if(subcommand == "add"){ enough_args(args, 4); account account; account.guid = generate_guid(); account.name = args[2]; account.since = find_new_since(); account.until = boost::gregorian::date(2099,12,31); if(account_exists(account.name)){ throw budget_exception("An account with this name already exists"); } account.amount = parse_money(args[3]); not_negative(account.amount); add_data(accounts, std::move(account)); } else if(subcommand == "delete"){ enough_args(args, 3); std::size_t id = to_number<std::size_t>(args[2]); if(!exists(accounts, id)){ throw budget_exception("There are no account with id " + args[2]); } load_expenses(); for(auto& expense : all_expenses()){ if(expense.account == id){ throw budget_exception("There are still some expenses linked to this account, cannot delete it"); } } load_earnings(); for(auto& earning : all_earnings()){ if(earning.account == id){ throw budget_exception("There are still some earnings linked to this account, cannot delete it"); } } remove(accounts, id); std::cout << "Account " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ enough_args(args, 3); std::size_t id = to_number<std::size_t>(args[2]); if(!exists(accounts, id)){ throw budget_exception("There are no account with id " + args[2]); } auto& account = get(accounts, id); edit_string(account.name, "Name"); edit_money(account.amount, "Amount"); std::cout << "Account " << id << " has been modified" << std::endl; } else if(subcommand == "archive"){ std::cout << "This command will create new accounts that will be used starting from the beginning of the current month. Are you sure you want to proceed ? [yes/no] ? "; std::string answer; std::cin >> answer; if(answer == "yes" || answer == "y"){ std::vector<budget::account> copies; auto tmp = boost::gregorian::day_clock::local_day() - boost::gregorian::months(1); boost::gregorian::date until_date(tmp.year(), tmp.month(), tmp.end_of_month().day()); for(auto& account : all_accounts()){ if(account.until == boost::gregorian::date(2099,12,31)){ budget::account copy; copy.guid = generate_guid(); copy.name = account.name; copy.amount = account.amount; copy.until = boost::gregorian::date(2099,12,31); copy.since = until_date + boost::gregorian::date_duration(1); account.until = until_date; copies.push_back(std::move(copy)); } } for(auto& copy : copies){ add_data(accounts, std::move(copy)); } } else { //No need to save anything return; } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } save_accounts(); } void budget::load_accounts(){ load_data(accounts, "accounts.data"); } void budget::save_accounts(){ save_data(accounts, "accounts.data"); } budget::account& budget::get_account(std::size_t id){ return get(accounts, id); } budget::account& budget::get_account(std::string name){ for(auto& account : accounts.data){ if(account.name == name){ return account; } } budget_unreachable("The account does not exist"); } std::ostream& budget::operator<<(std::ostream& stream, const account& account){ return stream << account.id << ':' << account.guid << ':' << account.name << ':' << account.amount << ':' << to_string(account.since) << ':' << to_string(account.until); } void budget::operator>>(const std::vector<std::string>& parts, account& account){ account.id = to_number<std::size_t>(parts[0]); account.guid = parts[1]; account.name = parts[2]; account.amount = parse_money(parts[3]); account.since = boost::gregorian::from_string(parts[4]); account.until = boost::gregorian::from_string(parts[5]); } bool budget::account_exists(const std::string& name){ for(auto& account : accounts.data){ if(account.name == name){ return true; } } return false; } std::vector<account>& budget::all_accounts(){ return accounts.data; } std::vector<account> all_accounts(boost::gregorian::greg_year year, boost::gregorian::greg_month month){ std::vector<account> accounts; for(auto& account : all_accounts()){ //TODO } return std::move(accounts); }
//======================================================================= // Copyright Baptiste Wicht 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include "accounts.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "money.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" using namespace budget; namespace { static data_handler<account> accounts; void show_accounts(){ std::vector<std::string> columns = {"ID", "Name", "Amount"}; std::vector<std::vector<std::string>> contents; money total; for(auto& account : accounts.data){ if(account.until == boost::gregorian::date(2099,12,31)){ contents.push_back({to_string(account.id), account.name, to_string(account.amount)}); total += account.amount; } } contents.push_back({"", "Total", to_string(total)}); display_table(columns, contents); } void show_all_accounts(){ std::vector<std::string> columns = {"ID", "Name", "Amount", "Since", "Until"}; std::vector<std::vector<std::string>> contents; for(auto& account : accounts.data){ contents.push_back({to_string(account.id), account.name, to_string(account.amount), to_string(account.since), to_string(account.until)}); } display_table(columns, contents); } boost::gregorian::date find_new_since(){ boost::gregorian::date date(1400,1,1); for(auto& account : all_accounts()){ if(account.until != boost::gregorian::date(2099,12,31)){ if(account.until - boost::gregorian::date_duration(1) > date){ date = account.until - boost::gregorian::date_duration(1); } } } return date; } } //end of anonymous namespace void budget::accounts_module::handle(const std::vector<std::string>& args){ load_accounts(); if(args.size() == 1){ show_accounts(); } else { auto& subcommand = args[1]; if(subcommand == "show"){ show_accounts(); } else if(subcommand == "all"){ show_all_accounts(); } else if(subcommand == "add"){ enough_args(args, 4); account account; account.guid = generate_guid(); account.name = args[2]; account.since = find_new_since(); account.until = boost::gregorian::date(2099,12,31); if(account_exists(account.name)){ throw budget_exception("An account with this name already exists"); } account.amount = parse_money(args[3]); not_negative(account.amount); add_data(accounts, std::move(account)); } else if(subcommand == "delete"){ enough_args(args, 3); std::size_t id = to_number<std::size_t>(args[2]); if(!exists(accounts, id)){ throw budget_exception("There are no account with id " + args[2]); } load_expenses(); for(auto& expense : all_expenses()){ if(expense.account == id){ throw budget_exception("There are still some expenses linked to this account, cannot delete it"); } } load_earnings(); for(auto& earning : all_earnings()){ if(earning.account == id){ throw budget_exception("There are still some earnings linked to this account, cannot delete it"); } } remove(accounts, id); std::cout << "Account " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ enough_args(args, 3); std::size_t id = to_number<std::size_t>(args[2]); if(!exists(accounts, id)){ throw budget_exception("There are no account with id " + args[2]); } auto& account = get(accounts, id); edit_string(account.name, "Name"); edit_money(account.amount, "Amount"); std::cout << "Account " << id << " has been modified" << std::endl; } else if(subcommand == "archive"){ std::cout << "This command will create new accounts that will be used starting from the beginning of the current month. Are you sure you want to proceed ? [yes/no] ? "; std::string answer; std::cin >> answer; if(answer == "yes" || answer == "y"){ std::vector<budget::account> copies; auto tmp = boost::gregorian::day_clock::local_day() - boost::gregorian::months(1); boost::gregorian::date until_date(tmp.year(), tmp.month(), tmp.end_of_month().day()); for(auto& account : all_accounts()){ if(account.until == boost::gregorian::date(2099,12,31)){ budget::account copy; copy.guid = generate_guid(); copy.name = account.name; copy.amount = account.amount; copy.until = boost::gregorian::date(2099,12,31); copy.since = until_date + boost::gregorian::date_duration(1); account.until = until_date; copies.push_back(std::move(copy)); } } for(auto& copy : copies){ add_data(accounts, std::move(copy)); } } else { //No need to save anything return; } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } save_accounts(); } void budget::load_accounts(){ load_data(accounts, "accounts.data"); } void budget::save_accounts(){ save_data(accounts, "accounts.data"); } budget::account& budget::get_account(std::size_t id){ return get(accounts, id); } budget::account& budget::get_account(std::string name){ for(auto& account : accounts.data){ if(account.name == name){ return account; } } budget_unreachable("The account does not exist"); } std::ostream& budget::operator<<(std::ostream& stream, const account& account){ return stream << account.id << ':' << account.guid << ':' << account.name << ':' << account.amount << ':' << to_string(account.since) << ':' << to_string(account.until); } void budget::operator>>(const std::vector<std::string>& parts, account& account){ account.id = to_number<std::size_t>(parts[0]); account.guid = parts[1]; account.name = parts[2]; account.amount = parse_money(parts[3]); account.since = boost::gregorian::from_string(parts[4]); account.until = boost::gregorian::from_string(parts[5]); } bool budget::account_exists(const std::string& name){ for(auto& account : accounts.data){ if(account.name == name){ return true; } } return false; } std::vector<account>& budget::all_accounts(){ return accounts.data; } std::vector<account> budget::all_accounts(boost::gregorian::greg_year year, boost::gregorian::greg_month month){ std::vector<account> accounts; boost::gregorian::date date(year, month, 5); for(auto& account : all_accounts()){ if(account.since < date && account.until > date){ accounts.push_back(account); } } return std::move(accounts); }
Implement function to get the accounts of a specific month
Implement function to get the accounts of a specific month
C++
mit
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
43f249adb711b7f05f16c8be1549323ccff21a50
tools/lli/lli.cpp
tools/lli/lli.cpp
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Type.h" #include "llvm/Bytecode/Reader.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/System/Signals.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { try { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); sys::PrintStackTraceOnErrorSignal(); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; MP = getBytecodeModuleProvider(InputFile, &ErrorMsg); if (!MP) { std::cerr << "Error loading program '" << InputFile << "': " << ErrorMsg << "\n"; exit(1); } // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) MP->getModule()->setTargetTriple(TargetTriple); ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE &&"Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn) { std::cerr << "'main' function not found in module.\n"; return -1; } // Run static constructors. EE->runStaticConstructorsDestructors(false); // Run main. int Result = EE->runFunctionAsMain(Fn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't explicitly call exit, call exit now, for the // program. This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, (Type *)0); std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = Result; Args.push_back(ResultGV); EE->runFunction(Exit, Args); std::cerr << "ERROR: exit(" << Result << ") returned!\n"; abort(); } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } abort(); }
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Type.h" #include "llvm/Bytecode/Reader.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/System/Process.h" #include "llvm/System/Signals.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { try { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); sys::PrintStackTraceOnErrorSignal(); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; MP = getBytecodeModuleProvider(InputFile, &ErrorMsg); if (!MP) { std::cerr << "Error loading program '" << InputFile << "': " << ErrorMsg << "\n"; exit(1); } // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) MP->getModule()->setTargetTriple(TargetTriple); ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE &&"Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn) { std::cerr << "'main' function not found in module.\n"; return -1; } // Run static constructors. EE->runStaticConstructorsDestructors(false); // Run main. int Result = EE->runFunctionAsMain(Fn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't explicitly call exit, call exit now, for the // program. This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, (Type *)0); std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = Result; Args.push_back(ResultGV); EE->runFunction(Exit, Args); std::cerr << "ERROR: exit(" << Result << ") returned!\n"; abort(); } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } abort(); }
add a new (hidden) -disable-core-files option
add a new (hidden) -disable-core-files option git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@30318 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm
30183bf04273127dedd4342c49f7612214c57181
tools/lli/lli.cpp
tools/lli/lli.cpp
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an interpreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include <cerrno> #ifdef __CYGWIN__ #include <cygwin/version.h> #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 #define DO_NOTHING_ATEXIT 1 #endif #endif using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<bool> UseMCJIT( "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), cl::init(false)); // Determine optimization level. cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> MArch("march", cl::desc("Architecture to generate assembly for (see --version)")); cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<std::string> EntryFunc("entry-function", cl::desc("Specify the entry function (default = 'main') " "of the executable"), cl::value_desc("function"), cl::init("main")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); cl::opt<bool> NoLazyCompilation("disable-lazy-compilation", cl::desc("Disable JIT lazy compilation"), cl::init(false)); cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::JITDefault), cl::values(clEnumValN(CodeModel::JITDefault, "default", "Target default JIT code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); cl::opt<bool> EnableJITExceptionHandling("jit-enable-eh", cl::desc("Emit exception handling information"), cl::init(false)); cl::opt<bool> // In debug builds, make this default to true. #ifdef NDEBUG #define EMIT_DEBUG false #else #define EMIT_DEBUG true #endif EmitJitDebugInfo("jit-emit-debug", cl::desc("Emit debug information to debugger"), cl::init(EMIT_DEBUG)); #undef EMIT_DEBUG static cl::opt<bool> EmitJitDebugInfoToDisk("jit-emit-debug-to-disk", cl::Hidden, cl::desc("Emit debug info objfiles to disk"), cl::init(false)); } static ExecutionEngine *EE = 0; static void do_shutdown() { // Cygwin-1.5 invokes DLL's dtors before atexit handler. #ifndef DO_NOTHING_ATEXIT delete EE; llvm_shutdown(); #endif } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); atexit(do_shutdown); // Call llvm_shutdown() on exit. // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); // Load the bitcode... SMDiagnostic Err; Module *Mod = ParseIRFile(InputFile, Err, Context); if (!Mod) { Err.print(argv[0], errs()); return 1; } // If not jitting lazily, load the whole bitcode file eagerly too. std::string ErrorMsg; if (NoLazyCompilation) { if (Mod->MaterializeAllPermanently(&ErrorMsg)) { errs() << argv[0] << ": bitcode didn't read correctly.\n"; errs() << "Reason: " << ErrorMsg << "\n"; exit(1); } } EngineBuilder builder(Mod); builder.setMArch(MArch); builder.setMCPU(MCPU); builder.setMAttrs(MAttrs); builder.setRelocationModel(RelocModel); builder.setCodeModel(CMModel); builder.setErrorStr(&ErrorMsg); builder.setJITMemoryManager(ForceInterpreter ? 0 : JITMemoryManager::CreateDefaultMemManager()); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter : EngineKind::JIT); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) Mod->setTargetTriple(Triple::normalize(TargetTriple)); // Enable MCJIT if desired. if (UseMCJIT && !ForceInterpreter) { builder.setUseMCJIT(true); builder.setJITMemoryManager(JITMemoryManager::CreateDefaultMemManager()); } CodeGenOpt::Level OLvl = CodeGenOpt::Default; switch (OptLevel) { default: errs() << argv[0] << ": invalid optimization level.\n"; return 1; case ' ': break; case '0': OLvl = CodeGenOpt::None; break; case '1': OLvl = CodeGenOpt::Less; break; case '2': OLvl = CodeGenOpt::Default; break; case '3': OLvl = CodeGenOpt::Aggressive; break; } builder.setOptLevel(OLvl); TargetOptions Options; Options.JITExceptionHandling = EnableJITExceptionHandling; Options.JITEmitDebugInfo = EmitJitDebugInfo; Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk; builder.setTargetOptions(Options); EE = builder.create(); if (!EE) { if (!ErrorMsg.empty()) errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; else errs() << argv[0] << ": unknown error creating EE!\n"; exit(1); } // The following functions have no effect if their respective profiling // support wasn't enabled in the build configuration. EE->RegisterJITEventListener( JITEventListener::createOProfileJITEventListener()); EE->RegisterJITEventListener( JITEventListener::createIntelJITEventListener()); EE->DisableLazyCompilation(NoLazyCompilation); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (StringRef(InputFile).endswith(".bc")) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *EntryFn = Mod->getFunction(EntryFunc); if (!EntryFn) { errs() << '\'' << EntryFunc << "\' function not found in module.\n"; return -1; } // If the program doesn't explicitly call exit, we will need the Exit // function later on to make an explicit call, so get the function now. Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), Type::getInt32Ty(Context), NULL); // Reset errno to zero on entry to main. errno = 0; // Run static constructors. EE->runStaticConstructorsDestructors(false); if (NoLazyCompilation) { for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { Function *Fn = &*I; if (Fn != EntryFn && !Fn->isDeclaration()) EE->getPointerToFunction(Fn); } } // Run main. int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't call exit explicitly, we should call it now. // This ensures that any atexit handlers get called correctly. if (Function *ExitF = dyn_cast<Function>(Exit)) { std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = APInt(32, Result); Args.push_back(ResultGV); EE->runFunction(ExitF, Args); errs() << "ERROR: exit(" << Result << ") returned!\n"; abort(); } else { errs() << "ERROR: exit defined with wrong prototype!\n"; abort(); } }
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an interpreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include <cerrno> #ifdef __CYGWIN__ #include <cygwin/version.h> #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 #define DO_NOTHING_ATEXIT 1 #endif #endif using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<bool> UseMCJIT( "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), cl::init(false)); // Determine optimization level. cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> MArch("march", cl::desc("Architecture to generate assembly for (see --version)")); cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<std::string> EntryFunc("entry-function", cl::desc("Specify the entry function (default = 'main') " "of the executable"), cl::value_desc("function"), cl::init("main")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); cl::opt<bool> NoLazyCompilation("disable-lazy-compilation", cl::desc("Disable JIT lazy compilation"), cl::init(false)); cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::JITDefault), cl::values(clEnumValN(CodeModel::JITDefault, "default", "Target default JIT code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); cl::opt<bool> EnableJITExceptionHandling("jit-enable-eh", cl::desc("Emit exception handling information"), cl::init(false)); cl::opt<bool> // In debug builds, make this default to true. #ifdef NDEBUG #define EMIT_DEBUG false #else #define EMIT_DEBUG true #endif EmitJitDebugInfo("jit-emit-debug", cl::desc("Emit debug information to debugger"), cl::init(EMIT_DEBUG)); #undef EMIT_DEBUG static cl::opt<bool> EmitJitDebugInfoToDisk("jit-emit-debug-to-disk", cl::Hidden, cl::desc("Emit debug info objfiles to disk"), cl::init(false)); } static ExecutionEngine *EE = 0; static void do_shutdown() { // Cygwin-1.5 invokes DLL's dtors before atexit handler. #ifndef DO_NOTHING_ATEXIT delete EE; llvm_shutdown(); #endif } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); atexit(do_shutdown); // Call llvm_shutdown() on exit. // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); // Load the bitcode... SMDiagnostic Err; Module *Mod = ParseIRFile(InputFile, Err, Context); if (!Mod) { Err.print(argv[0], errs()); return 1; } // If not jitting lazily, load the whole bitcode file eagerly too. std::string ErrorMsg; if (NoLazyCompilation) { if (Mod->MaterializeAllPermanently(&ErrorMsg)) { errs() << argv[0] << ": bitcode didn't read correctly.\n"; errs() << "Reason: " << ErrorMsg << "\n"; exit(1); } } EngineBuilder builder(Mod); builder.setMArch(MArch); builder.setMCPU(MCPU); builder.setMAttrs(MAttrs); builder.setRelocationModel(RelocModel); builder.setCodeModel(CMModel); builder.setErrorStr(&ErrorMsg); builder.setJITMemoryManager(ForceInterpreter ? 0 : JITMemoryManager::CreateDefaultMemManager()); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter : EngineKind::JIT); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) Mod->setTargetTriple(Triple::normalize(TargetTriple)); // Enable MCJIT if desired. if (UseMCJIT && !ForceInterpreter) { builder.setUseMCJIT(true); } CodeGenOpt::Level OLvl = CodeGenOpt::Default; switch (OptLevel) { default: errs() << argv[0] << ": invalid optimization level.\n"; return 1; case ' ': break; case '0': OLvl = CodeGenOpt::None; break; case '1': OLvl = CodeGenOpt::Less; break; case '2': OLvl = CodeGenOpt::Default; break; case '3': OLvl = CodeGenOpt::Aggressive; break; } builder.setOptLevel(OLvl); TargetOptions Options; Options.JITExceptionHandling = EnableJITExceptionHandling; Options.JITEmitDebugInfo = EmitJitDebugInfo; Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk; builder.setTargetOptions(Options); EE = builder.create(); if (!EE) { if (!ErrorMsg.empty()) errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; else errs() << argv[0] << ": unknown error creating EE!\n"; exit(1); } // The following functions have no effect if their respective profiling // support wasn't enabled in the build configuration. EE->RegisterJITEventListener( JITEventListener::createOProfileJITEventListener()); EE->RegisterJITEventListener( JITEventListener::createIntelJITEventListener()); EE->DisableLazyCompilation(NoLazyCompilation); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (StringRef(InputFile).endswith(".bc")) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *EntryFn = Mod->getFunction(EntryFunc); if (!EntryFn) { errs() << '\'' << EntryFunc << "\' function not found in module.\n"; return -1; } // If the program doesn't explicitly call exit, we will need the Exit // function later on to make an explicit call, so get the function now. Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), Type::getInt32Ty(Context), NULL); // Reset errno to zero on entry to main. errno = 0; // Run static constructors. EE->runStaticConstructorsDestructors(false); if (NoLazyCompilation) { for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { Function *Fn = &*I; if (Fn != EntryFn && !Fn->isDeclaration()) EE->getPointerToFunction(Fn); } } // Run main. int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't call exit explicitly, we should call it now. // This ensures that any atexit handlers get called correctly. if (Function *ExitF = dyn_cast<Function>(Exit)) { std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = APInt(32, Result); Args.push_back(ResultGV); EE->runFunction(ExitF, Args); errs() << "ERROR: exit(" << Result << ") returned!\n"; abort(); } else { errs() << "ERROR: exit defined with wrong prototype!\n"; abort(); } }
Remove redundant line (the memory manager is set above to the same object if !ForceInterpreteri). It has no effect (apart from a memory leak...)
Remove redundant line (the memory manager is set above to the same object if !ForceInterpreteri). It has no effect (apart from a memory leak...) git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@155792 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm
0713a1d8fa66b35bedeed6fdcdb0cd3328610f77
applications/util/format/format.cpp
applications/util/format/format.cpp
#include <Grappa.hpp> #include <graph/Graph.hpp> using namespace Grappa; // file specifications DEFINE_string(input_path, "", "Path to graph source file"); DEFINE_string(input_format, "bintsv4", "Format of graph source file"); DEFINE_string(output_path, "", "Path to graph destination file"); DEFINE_string(output_format, "bintsv4", "Format of graph destination file"); // settings for generator DEFINE_uint64( nnz_factor, 16, "Approximate number of non-zeros per matrix row" ); DEFINE_uint64( scale, 16, "logN dimension of square matrix" ); int main(int argc, char* argv[]) { Grappa::init(&argc, &argv); Grappa::run([]{ TupleGraph tg; double t = walltime(); if( FLAGS_input_path.empty() ) { uint64_t N = (1L<<FLAGS_scale); uint64_t desired_nnz = FLAGS_nnz_factor * N; long userseed = 0xDECAFBAD; // from (prng.c: default seed) tg = TupleGraph::Kronecker(FLAGS_scale, desired_nnz, userseed, userseed); } else { // load from file tg = TupleGraph::Load( FLAGS_input_path, FLAGS_input_format ); } t = walltime() - t; LOG(INFO) << "make_graph: " << t; if( !FLAGS_output_path.empty() ) { tg.save( FLAGS_output_path, FLAGS_output_format ); } }); Grappa::finalize(); }
#include <Grappa.hpp> #include <graph/Graph.hpp> using namespace Grappa; // file specifications DEFINE_string(input_path, "", "Path to graph source file"); DEFINE_string(input_format, "bintsv4", "Format of graph source file"); DEFINE_string(output_path, "", "Path to graph destination file"); DEFINE_string(output_format, "bintsv4", "Format of graph destination file"); // settings for generator DEFINE_uint64( nnz_factor, 16, "Approximate number of non-zeros per matrix row" ); DEFINE_uint64( scale, 16, "logN dimension of square matrix" ); int main(int argc, char* argv[]) { Grappa::init(&argc, &argv); Grappa::run([]{ TupleGraph tg; double t = walltime(); if( FLAGS_input_path.empty() ) { uint64_t N = (1L<<FLAGS_scale); uint64_t desired_nnz = FLAGS_nnz_factor * N; long userseed = 0xDECAFBAD; // from (prng.c: default seed) tg = TupleGraph::Kronecker(FLAGS_scale, desired_nnz, userseed, userseed); } else { // load from file tg = TupleGraph::Load( FLAGS_input_path, FLAGS_input_format ); } t = walltime() - t; LOG(INFO) << "Loaded " << tg.nedge << " edges in " << t << " seconds."; if( !FLAGS_output_path.empty() ) { t = walltime(); tg.save( FLAGS_output_path, FLAGS_output_format ); t = walltime() - t; LOG(INFO) << "Saved " << tg.nedge << " edges in " << t << " seconds."; } }); Grappa::finalize(); }
add some info about conversion
add some info about conversion
C++
bsd-3-clause
buaasun/grappa,uwsampa/grappa,uwsampa/grappa,alexfrolov/grappa,alexfrolov/grappa,uwsampa/grappa,uwsampa/grappa,alexfrolov/grappa,alexfrolov/grappa,buaasun/grappa,alexfrolov/grappa,uwsampa/grappa,buaasun/grappa,buaasun/grappa,uwsampa/grappa,buaasun/grappa,alexfrolov/grappa,uwsampa/grappa,alexfrolov/grappa,buaasun/grappa,buaasun/grappa
72fcbf9d4556a98d160e4cc46134b44d6686008e
tensorflow/core/kernels/data/experimental/rebatch_dataset_op.cc
tensorflow/core/kernels/data/experimental/rebatch_dataset_op.cc
/* Copyright 2019 The TensorFlow Authors. 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 "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/kernels/data/name_utils.h" namespace tensorflow { namespace data { namespace experimental { namespace { inline int64 CeilDiv(int64 dividend, int64 divisor) { return (dividend - 1 + divisor) / divisor; } constexpr const char* const kDatasetType = "Rebatch"; class RebatchDatasetOp : public UnaryDatasetOpKernel { public: explicit RebatchDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_)); } protected: void MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) override { int64 num_replicas; OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, "num_replicas", &num_replicas)); OP_REQUIRES( ctx, num_replicas > 0, errors::InvalidArgument("num_replicas must be greater than zero.")); *output = new Dataset(ctx, input, num_replicas, output_types_, output_shapes_); } private: class Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const DatasetBase* input, const int64 num_replicas, const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes) : DatasetBase(DatasetContext(ctx)), input_(input), num_replicas_(num_replicas), output_types_(output_types), output_shapes_(output_shapes) { input_->Ref(); } ~Dataset() override { input_->Unref(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { name_utils::IteratorPrefixParams params; return absl::make_unique<Iterator>(Iterator::Params{ this, name_utils::IteratorPrefix(kDatasetType, prefix, params)}); } const DataTypeVector& output_dtypes() const override { return output_types_; } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { name_utils::DatasetDebugStringParams params; params.set_args(num_replicas_); return name_utils::DatasetDebugString(kDatasetType, params); } Status CheckExternalState() const override { return input_->CheckExternalState(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* input_graph_node = nullptr; TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node)); Node* num_replicas = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(num_replicas_, &num_replicas)); TF_RETURN_IF_ERROR( b->AddDataset(this, {input_graph_node, num_replicas}, output)); return Status::OK(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ~Iterator() override {} Status Initialize(IteratorContext* ctx) override { return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { mutex_lock l(mu_); *end_of_sequence = false; if (slice_number_ % dataset()->num_replicas_ == 0) { input_descriptors_.clear(); std::vector<Tensor> input_tensors; TF_RETURN_IF_ERROR( input_impl_->GetNext(ctx, &input_tensors, end_of_sequence)); if (*end_of_sequence) { return Status::OK(); } input_descriptors_.reserve(input_tensors.size()); for (int i = 0; i < input_tensors.size(); ++i) { if (input_tensors[i].dims() == 0) { return errors::InvalidArgument( "Cannot rebatch dataset: All components must have at least " "one dimension. Perhaps your input dataset is not batched? " "Component ", i, " is scalar."); } int64 original_batch_dim = input_tensors[i].dim_size(0); int64 interval = CeilDiv(original_batch_dim, dataset()->num_replicas_); input_descriptors_.push_back( {std::move(input_tensors[i]), original_batch_dim, interval}); } } out_tensors->reserve(input_descriptors_.size()); // We slice each component independently because they may have // different batch dimensions. for (const auto& input_desc : input_descriptors_) { int64 start = input_desc.interval * slice_number_; int64 end = std::min(start + input_desc.interval, input_desc.original_batch_dim); if (start >= end) { // We can get here if ceil(original_batch_dim_ / new batch dim) < // num_replicas_, i.e. the batch isn't big enough to distribute over // num replicas. In this case, we return empty tensors for the // remaining iterations that correspond to this batch. start = end; } Tensor slice = input_desc.whole_tensor.Slice(start, end); if (slice.IsAligned()) { out_tensors->push_back(std::move(slice)); } else { out_tensors->push_back(tensor::DeepCopy(std::move(slice))); } } slice_number_ = (slice_number_ + 1) % dataset()->num_replicas_; return Status::OK(); } protected: Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(mu_); if (!input_impl_) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("input_impl_empty"), "")); } else { TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_)); } TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("slice_number"), slice_number_)); if (slice_number_ % dataset()->num_replicas_ != 0) { // Save state of input tensors. for (int i = 0; i < input_descriptors_.size(); ++i) { TF_RETURN_IF_ERROR(writer->WriteTensor( full_name(strings::StrCat("tensors[", i, "]")), input_descriptors_[i].whole_tensor)); } } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); if (!reader->Contains(full_name("input_impl_empty"))) { TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); } else { input_impl_.reset(); } TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("slice_number"), &slice_number_)); input_descriptors_.clear(); input_descriptors_.resize(dataset()->output_dtypes().size()); if (slice_number_ % dataset()->num_replicas_ != 0) { for (int i = 0; i < input_descriptors_.size(); ++i) { TF_RETURN_IF_ERROR(reader->ReadTensor( full_name(strings::StrCat("tensors[", i, "]")), &input_descriptors_[i].whole_tensor)); input_descriptors_[i].original_batch_dim = input_descriptors_[i].whole_tensor.dim_size(0); input_descriptors_[i].interval = CeilDiv(input_descriptors_[i].original_batch_dim, dataset()->num_replicas_); } } return Status::OK(); } private: // Describes one component of the input. struct InputDescriptor { InputDescriptor() {} InputDescriptor(Tensor&& whole_tensor, int64 original_batch_dim, int64 interval) : whole_tensor(std::move(whole_tensor)), original_batch_dim(original_batch_dim), interval(interval) {} Tensor whole_tensor; int64 original_batch_dim; int64 interval; }; mutex mu_; std::unique_ptr<IteratorBase> input_impl_; std::vector<InputDescriptor> input_descriptors_ GUARDED_BY(mu_); int64 slice_number_ GUARDED_BY(mu_) = 0; }; const DatasetBase* const input_; const int64 num_replicas_; const DataTypeVector output_types_; const std::vector<PartialTensorShape> output_shapes_; }; DataTypeVector output_types_; std::vector<PartialTensorShape> output_shapes_; }; REGISTER_KERNEL_BUILDER(Name("RebatchDataset").Device(DEVICE_CPU), RebatchDatasetOp); REGISTER_KERNEL_BUILDER(Name("ExperimentalRebatchDataset").Device(DEVICE_CPU), RebatchDatasetOp); } // anonymous namespace } // namespace experimental } // namespace data } // namespace tensorflow
/* Copyright 2019 The TensorFlow Authors. 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 "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/kernels/data/name_utils.h" namespace tensorflow { namespace data { namespace experimental { namespace { inline int64 CeilDiv(int64 dividend, int64 divisor) { return (dividend - 1 + divisor) / divisor; } constexpr const char* const kDatasetType = "Rebatch"; class RebatchDatasetOp : public UnaryDatasetOpKernel { public: explicit RebatchDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_)); } protected: void MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) override { int64 num_replicas; OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, "num_replicas", &num_replicas)); OP_REQUIRES( ctx, num_replicas > 0, errors::InvalidArgument("num_replicas must be greater than zero.")); *output = new Dataset(ctx, input, num_replicas, output_types_, output_shapes_); } private: class Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const DatasetBase* input, const int64 num_replicas, const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes) : DatasetBase(DatasetContext(ctx)), input_(input), num_replicas_(num_replicas), output_types_(output_types), output_shapes_(output_shapes) { input_->Ref(); } ~Dataset() override { input_->Unref(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { name_utils::IteratorPrefixParams params; return absl::make_unique<Iterator>(Iterator::Params{ this, name_utils::IteratorPrefix(kDatasetType, prefix, params)}); } const DataTypeVector& output_dtypes() const override { return output_types_; } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { name_utils::DatasetDebugStringParams params; params.set_args(num_replicas_); return name_utils::DatasetDebugString(kDatasetType, params); } Status CheckExternalState() const override { return input_->CheckExternalState(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* input_graph_node = nullptr; TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node)); Node* num_replicas = nullptr; TF_RETURN_IF_ERROR(b->AddScalar(num_replicas_, &num_replicas)); TF_RETURN_IF_ERROR( b->AddDataset(this, {input_graph_node, num_replicas}, output)); return Status::OK(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ~Iterator() override {} Status Initialize(IteratorContext* ctx) override { return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_); } string BuildTraceMeName() override { return strings::StrCat(prefix(), "#num_replicas=", dataset()->num_replicas_, "#"); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { mutex_lock l(mu_); *end_of_sequence = false; if (slice_number_ % dataset()->num_replicas_ == 0) { input_descriptors_.clear(); std::vector<Tensor> input_tensors; TF_RETURN_IF_ERROR( input_impl_->GetNext(ctx, &input_tensors, end_of_sequence)); if (*end_of_sequence) { return Status::OK(); } input_descriptors_.reserve(input_tensors.size()); for (int i = 0; i < input_tensors.size(); ++i) { if (input_tensors[i].dims() == 0) { return errors::InvalidArgument( "Cannot rebatch dataset: All components must have at least " "one dimension. Perhaps your input dataset is not batched? " "Component ", i, " is scalar."); } int64 original_batch_dim = input_tensors[i].dim_size(0); int64 interval = CeilDiv(original_batch_dim, dataset()->num_replicas_); input_descriptors_.push_back( {std::move(input_tensors[i]), original_batch_dim, interval}); } } out_tensors->reserve(input_descriptors_.size()); // We slice each component independently because they may have // different batch dimensions. for (const auto& input_desc : input_descriptors_) { int64 start = input_desc.interval * slice_number_; int64 end = std::min(start + input_desc.interval, input_desc.original_batch_dim); if (start >= end) { // We can get here if ceil(original_batch_dim_ / new batch dim) < // num_replicas_, i.e. the batch isn't big enough to distribute // over num replicas. In this case, we return empty tensors for // the remaining iterations that correspond to this batch. start = end; } Tensor slice = input_desc.whole_tensor.Slice(start, end); if (slice.IsAligned()) { out_tensors->push_back(std::move(slice)); } else { out_tensors->push_back(tensor::DeepCopy(std::move(slice))); } } slice_number_ = (slice_number_ + 1) % dataset()->num_replicas_; return Status::OK(); } protected: Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(mu_); if (!input_impl_) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("input_impl_empty"), "")); } else { TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_)); } TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("slice_number"), slice_number_)); if (slice_number_ % dataset()->num_replicas_ != 0) { // Save state of input tensors. for (int i = 0; i < input_descriptors_.size(); ++i) { TF_RETURN_IF_ERROR(writer->WriteTensor( full_name(strings::StrCat("tensors[", i, "]")), input_descriptors_[i].whole_tensor)); } } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); if (!reader->Contains(full_name("input_impl_empty"))) { TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); } else { input_impl_.reset(); } TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("slice_number"), &slice_number_)); input_descriptors_.clear(); input_descriptors_.resize(dataset()->output_dtypes().size()); if (slice_number_ % dataset()->num_replicas_ != 0) { for (int i = 0; i < input_descriptors_.size(); ++i) { TF_RETURN_IF_ERROR(reader->ReadTensor( full_name(strings::StrCat("tensors[", i, "]")), &input_descriptors_[i].whole_tensor)); input_descriptors_[i].original_batch_dim = input_descriptors_[i].whole_tensor.dim_size(0); input_descriptors_[i].interval = CeilDiv(input_descriptors_[i].original_batch_dim, dataset()->num_replicas_); } } return Status::OK(); } private: // Describes one component of the input. struct InputDescriptor { InputDescriptor() {} InputDescriptor(Tensor&& whole_tensor, int64 original_batch_dim, int64 interval) : whole_tensor(std::move(whole_tensor)), original_batch_dim(original_batch_dim), interval(interval) {} Tensor whole_tensor; int64 original_batch_dim; int64 interval; }; mutex mu_; std::unique_ptr<IteratorBase> input_impl_; std::vector<InputDescriptor> input_descriptors_ GUARDED_BY(mu_); int64 slice_number_ GUARDED_BY(mu_) = 0; }; const DatasetBase* const input_; const int64 num_replicas_; const DataTypeVector output_types_; const std::vector<PartialTensorShape> output_shapes_; }; DataTypeVector output_types_; std::vector<PartialTensorShape> output_shapes_; }; REGISTER_KERNEL_BUILDER(Name("RebatchDataset").Device(DEVICE_CPU), RebatchDatasetOp); REGISTER_KERNEL_BUILDER(Name("ExperimentalRebatchDataset").Device(DEVICE_CPU), RebatchDatasetOp); } // anonymous namespace } // namespace experimental } // namespace data } // namespace tensorflow
Add traceme on rebatch to log num_replicas param
[tf.data] Add traceme on rebatch to log num_replicas param PiperOrigin-RevId: 273855865
C++
apache-2.0
tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,xzturn/tensorflow,aam-at/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,xzturn/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,xzturn/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,renyi533/tensorflow,aldian/tensorflow,annarev/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,sarvex/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aldian/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,aam-at/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,gunan/tensorflow,jhseu/tensorflow,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,arborh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,arborh/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,annarev/tensorflow,jhseu/tensorflow,xzturn/tensorflow,gautam1858/tensorflow,aldian/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,jhseu/tensorflow,sarvex/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,gunan/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,adit-chandra/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,jhseu/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,sarvex/tensorflow,adit-chandra/tensorflow,freedomtan/tensorflow,arborh/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,karllessard/tensorflow,ppwwyyxx/tensorflow,aldian/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,xzturn/tensorflow,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,arborh/tensorflow,petewarden/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,cxxgtxy/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,karllessard/tensorflow,jhseu/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow,arborh/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,annarev/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,jhseu/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,arborh/tensorflow,karllessard/tensorflow,renyi533/tensorflow,aam-at/tensorflow,petewarden/tensorflow,annarev/tensorflow,gunan/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,yongtang/tensorflow,yongtang/tensorflow,petewarden/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,karllessard/tensorflow,sarvex/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,aldian/tensorflow,renyi533/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,xzturn/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,xzturn/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,aldian/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,jhseu/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,aldian/tensorflow,annarev/tensorflow,aam-at/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,xzturn/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,xzturn/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,adit-chandra/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,aldian/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,cxxgtxy/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow
83de1012a975916b7804f9a4a89f35d95fb2ef54
test/std/utilities/function.objects/func.invoke/invoke.pass.cpp
test/std/utilities/function.objects/func.invoke/invoke.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // <functional> // template <class F, class ...Args> // result_of_t<F&&(Args&&...)> invoke(F&&, Args&&...); /// C++14 [func.def] 20.9.0 /// (1) The following definitions apply to this Clause: /// (2) A call signature is the name of a return type followed by a parenthesized /// comma-separated list of zero or more argument types. /// (3) A callable type is a function object type (20.9) or a pointer to member. /// (4) A callable object is an object of a callable type. /// (5) A call wrapper type is a type that holds a callable object and supports /// a call operation that forwards to that object. /// (6) A call wrapper is an object of a call wrapper type. /// (7) A target object is the callable object held by a call wrapper. /// C++14 [func.require] 20.9.1 /// /// Define INVOKE (f, t1, t2, ..., tN) as follows: /// (1.1) — (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of /// type T or a reference to an object of type T or a reference to an object of a type derived from T; /// (1.2) — ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of /// the types described in the previous item; /// (1.3) — t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is an object of type T or a /// reference to an object of type T or a reference to an object of a type derived from T; /// (1.4) — (*t1).*f when N == 1 and f is a pointer to member data of a class T and t1 is not one of the types /// described in the previous item; /// (1.5) — f(t1, t2, ..., tN) in all other cases. #include <functional> #include <type_traits> #include <cassert> struct NonCopyable { NonCopyable() {} private: NonCopyable(NonCopyable const&) = delete; NonCopyable& operator=(NonCopyable const&) = delete; }; struct TestClass { explicit TestClass(int x) : data(x) {} int& operator()(NonCopyable&&) & { return data; } int const& operator()(NonCopyable&&) const & { return data; } int volatile& operator()(NonCopyable&&) volatile & { return data; } int const volatile& operator()(NonCopyable&&) const volatile & { return data; } int&& operator()(NonCopyable&&) && { return std::move(data); } int const&& operator()(NonCopyable&&) const && { return std::move(data); } int volatile&& operator()(NonCopyable&&) volatile && { return std::move(data); } int const volatile&& operator()(NonCopyable&&) const volatile && { return std::move(data); } int data; private: TestClass(TestClass const&) = delete; TestClass& operator=(TestClass const&) = delete; }; struct DerivedFromTestClass : public TestClass { explicit DerivedFromTestClass(int x) : TestClass(x) {} }; int& foo(NonCopyable&&) { static int data = 42; return data; } template <class Signature, class Expect, class Functor> void test_b12(Functor&& f) { // Create the callable object. typedef Signature TestClass::*ClassFunc; ClassFunc func_ptr = &TestClass::operator(); // Create the dummy arg. NonCopyable arg; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(func_ptr, std::forward<Functor>(f), std::move(arg)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<ClassFunc&&(Functor&&, NonCopyable&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(func_ptr, std::forward<Functor>(f), std::move(arg)); assert(ret == 42); } template <class Expect, class Functor> void test_b34(Functor&& f) { // Create the callable object. typedef int TestClass::*ClassFunc; ClassFunc func_ptr = &TestClass::data; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(func_ptr, std::forward<Functor>(f)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<ClassFunc&&(Functor&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(func_ptr, std::forward<Functor>(f)); assert(ret == 42); } template <class Expect, class Functor> void test_b5(Functor&& f) { NonCopyable arg; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(std::forward<Functor>(f), std::move(arg)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<Functor&&(NonCopyable&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(std::forward<Functor>(f), std::move(arg)); assert(ret == 42); } void bullet_one_two_tests() { { TestClass cl(42); test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); test_b12<int&&(NonCopyable&&) &&, int&&>(std::move(cl)); test_b12<int const&&(NonCopyable&&) const &&, int const&&>(std::move(cl)); test_b12<int volatile&&(NonCopyable&&) volatile &&, int volatile&&>(std::move(cl)); test_b12<int const volatile&&(NonCopyable&&) const volatile &&, int const volatile&&>(std::move(cl)); } { DerivedFromTestClass cl(42); test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); test_b12<int&&(NonCopyable&&) &&, int&&>(std::move(cl)); test_b12<int const&&(NonCopyable&&) const &&, int const&&>(std::move(cl)); test_b12<int volatile&&(NonCopyable&&) volatile &&, int volatile&&>(std::move(cl)); test_b12<int const volatile&&(NonCopyable&&) const volatile &&, int const volatile&&>(std::move(cl)); } { TestClass cl_obj(42); TestClass *cl = &cl_obj; test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); } { DerivedFromTestClass cl_obj(42); DerivedFromTestClass *cl = &cl_obj; test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); } } void bullet_three_four_tests() { { typedef TestClass Fn; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b34<int&&>(static_cast<Fn &&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { typedef DerivedFromTestClass Fn; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b34<int&&>(static_cast<Fn &&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { typedef TestClass Fn; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile *>(cl)); } { typedef DerivedFromTestClass Fn; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile *>(cl)); } } void bullet_five_tests() { using FooType = int&(NonCopyable&&); { FooType& fn = foo; test_b5<int &>(fn); } { FooType* fn = foo; test_b5<int &>(fn); } { typedef TestClass Fn; Fn cl(42); test_b5<int&>(cl); test_b5<int const&>(static_cast<Fn const&>(cl)); test_b5<int volatile&>(static_cast<Fn volatile&>(cl)); test_b5<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b5<int&&>(static_cast<Fn &&>(cl)); test_b5<int const&&>(static_cast<Fn const&&>(cl)); test_b5<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b5<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } } int main() { bullet_one_two_tests(); bullet_three_four_tests(); bullet_five_tests(); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // <functional> // template <class F, class ...Args> // result_of_t<F&&(Args&&...)> invoke(F&&, Args&&...); /// C++14 [func.def] 20.9.0 /// (1) The following definitions apply to this Clause: /// (2) A call signature is the name of a return type followed by a parenthesized /// comma-separated list of zero or more argument types. /// (3) A callable type is a function object type (20.9) or a pointer to member. /// (4) A callable object is an object of a callable type. /// (5) A call wrapper type is a type that holds a callable object and supports /// a call operation that forwards to that object. /// (6) A call wrapper is an object of a call wrapper type. /// (7) A target object is the callable object held by a call wrapper. /// C++14 [func.require] 20.9.1 /// /// Define INVOKE (f, t1, t2, ..., tN) as follows: /// (1.1) - (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of /// type T or a reference to an object of type T or a reference to an object of a type derived from T; /// (1.2) - ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of /// the types described in the previous item; /// (1.3) - t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is an object of type T or a /// reference to an object of type T or a reference to an object of a type derived from T; /// (1.4) - (*t1).*f when N == 1 and f is a pointer to member data of a class T and t1 is not one of the types /// described in the previous item; /// (1.5) - f(t1, t2, ..., tN) in all other cases. #include <functional> #include <type_traits> #include <cassert> struct NonCopyable { NonCopyable() {} private: NonCopyable(NonCopyable const&) = delete; NonCopyable& operator=(NonCopyable const&) = delete; }; struct TestClass { explicit TestClass(int x) : data(x) {} int& operator()(NonCopyable&&) & { return data; } int const& operator()(NonCopyable&&) const & { return data; } int volatile& operator()(NonCopyable&&) volatile & { return data; } int const volatile& operator()(NonCopyable&&) const volatile & { return data; } int&& operator()(NonCopyable&&) && { return std::move(data); } int const&& operator()(NonCopyable&&) const && { return std::move(data); } int volatile&& operator()(NonCopyable&&) volatile && { return std::move(data); } int const volatile&& operator()(NonCopyable&&) const volatile && { return std::move(data); } int data; private: TestClass(TestClass const&) = delete; TestClass& operator=(TestClass const&) = delete; }; struct DerivedFromTestClass : public TestClass { explicit DerivedFromTestClass(int x) : TestClass(x) {} }; int& foo(NonCopyable&&) { static int data = 42; return data; } template <class Signature, class Expect, class Functor> void test_b12(Functor&& f) { // Create the callable object. typedef Signature TestClass::*ClassFunc; ClassFunc func_ptr = &TestClass::operator(); // Create the dummy arg. NonCopyable arg; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(func_ptr, std::forward<Functor>(f), std::move(arg)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<ClassFunc&&(Functor&&, NonCopyable&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(func_ptr, std::forward<Functor>(f), std::move(arg)); assert(ret == 42); } template <class Expect, class Functor> void test_b34(Functor&& f) { // Create the callable object. typedef int TestClass::*ClassFunc; ClassFunc func_ptr = &TestClass::data; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(func_ptr, std::forward<Functor>(f)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<ClassFunc&&(Functor&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(func_ptr, std::forward<Functor>(f)); assert(ret == 42); } template <class Expect, class Functor> void test_b5(Functor&& f) { NonCopyable arg; // Check that the deduced return type of invoke is what is expected. typedef decltype( std::invoke(std::forward<Functor>(f), std::move(arg)) ) DeducedReturnType; static_assert((std::is_same<DeducedReturnType, Expect>::value), ""); // Check that result_of_t matches Expect. typedef typename std::result_of<Functor&&(NonCopyable&&)>::type ResultOfReturnType; static_assert((std::is_same<ResultOfReturnType, Expect>::value), ""); // Run invoke and check the return value. DeducedReturnType ret = std::invoke(std::forward<Functor>(f), std::move(arg)); assert(ret == 42); } void bullet_one_two_tests() { { TestClass cl(42); test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); test_b12<int&&(NonCopyable&&) &&, int&&>(std::move(cl)); test_b12<int const&&(NonCopyable&&) const &&, int const&&>(std::move(cl)); test_b12<int volatile&&(NonCopyable&&) volatile &&, int volatile&&>(std::move(cl)); test_b12<int const volatile&&(NonCopyable&&) const volatile &&, int const volatile&&>(std::move(cl)); } { DerivedFromTestClass cl(42); test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); test_b12<int&&(NonCopyable&&) &&, int&&>(std::move(cl)); test_b12<int const&&(NonCopyable&&) const &&, int const&&>(std::move(cl)); test_b12<int volatile&&(NonCopyable&&) volatile &&, int volatile&&>(std::move(cl)); test_b12<int const volatile&&(NonCopyable&&) const volatile &&, int const volatile&&>(std::move(cl)); } { TestClass cl_obj(42); TestClass *cl = &cl_obj; test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); } { DerivedFromTestClass cl_obj(42); DerivedFromTestClass *cl = &cl_obj; test_b12<int&(NonCopyable&&) &, int&>(cl); test_b12<int const&(NonCopyable&&) const &, int const&>(cl); test_b12<int volatile&(NonCopyable&&) volatile &, int volatile&>(cl); test_b12<int const volatile&(NonCopyable&&) const volatile &, int const volatile&>(cl); } } void bullet_three_four_tests() { { typedef TestClass Fn; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b34<int&&>(static_cast<Fn &&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { typedef DerivedFromTestClass Fn; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b34<int&&>(static_cast<Fn &&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { typedef TestClass Fn; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile *>(cl)); } { typedef DerivedFromTestClass Fn; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile *>(cl)); } } void bullet_five_tests() { using FooType = int&(NonCopyable&&); { FooType& fn = foo; test_b5<int &>(fn); } { FooType* fn = foo; test_b5<int &>(fn); } { typedef TestClass Fn; Fn cl(42); test_b5<int&>(cl); test_b5<int const&>(static_cast<Fn const&>(cl)); test_b5<int volatile&>(static_cast<Fn volatile&>(cl)); test_b5<int const volatile&>(static_cast<Fn const volatile &>(cl)); test_b5<int&&>(static_cast<Fn &&>(cl)); test_b5<int const&&>(static_cast<Fn const&&>(cl)); test_b5<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b5<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } } int main() { bullet_one_two_tests(); bullet_three_four_tests(); bullet_five_tests(); }
Remove non-ascii characters
Remove non-ascii characters git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@242197 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
2337443034d7cc92c1a61b2347fefeb5cdc8ad72
api/impl/defaultMappedSegment.cpp
api/impl/defaultMappedSegment.cpp
/* * Copyright (C) 2013 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include <string> #include <sstream> #include <iostream> #include <limits> #include <algorithm> #include "hal.h" #include "defaultMappedSegment.h" #include "defaultTopSegmentIterator.h" #include "defaultBottomSegmentIterator.h" using namespace std; using namespace hal; DefaultMappedSegment::DefaultMappedSegment( SegmentIteratorConstPtr source, SegmentIteratorConstPtr target) : _source(source.downCast<DefaultSegmentIteratorConstPtr>()), _target(target.downCast<DefaultSegmentIteratorConstPtr>()) { assert(_source->getLength() == _target->getLength()); } DefaultMappedSegment::~DefaultMappedSegment() { } ////////////////////////////////////////////////////////////////////////////// // MAPPED SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// SlicedSegmentConstPtr DefaultMappedSegment::getSource() const { return _source; } ////////////////////////////////////////////////////////////////////////////// // INTERNAL FUNCTIONS ////////////////////////////////////////////////////////////////////////////// hal_size_t DefaultMappedSegment::map(const DefaultSegmentIterator* source, vector<MappedSegmentConstPtr>& results, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) { assert(source != NULL); SegmentIteratorConstPtr startSource; SegmentIteratorConstPtr startTarget; if (source->isTop()) { startSource = dynamic_cast<const DefaultTopSegmentIterator*>(source)->copy(); startTarget = dynamic_cast<const DefaultTopSegmentIterator*>(source)->copy(); } else { startSource = dynamic_cast<const DefaultBottomSegmentIterator*>(source)->copy(); startTarget = dynamic_cast<const DefaultBottomSegmentIterator*>(source)->copy(); } DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(startSource, startTarget)); vector<DefaultMappedSegmentConstPtr> input(1, newMappedSeg); vector<DefaultMappedSegmentConstPtr> output; mapRecursive(NULL, input, output, tgtGenome, genomesOnPath, doDupes); results.insert(results.end(), output.begin(), output.end()); return output.size(); } hal_size_t DefaultMappedSegment::mapRecursive( const Genome* prevGenome, vector<DefaultMappedSegmentConstPtr>& input, vector<DefaultMappedSegmentConstPtr>& results, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) { vector<DefaultMappedSegmentConstPtr>* inputPtr = &input; vector<DefaultMappedSegmentConstPtr>* outputPtr = &results; const Genome* srcGenome = NULL; const Genome* genome = NULL; const Genome* nextGenome = NULL; hal_size_t nextChildIndex = numeric_limits<hal_size_t>::max(); if (!inputPtr->empty()) { srcGenome = inputPtr->at(0)->getSource()->getGenome(); genome = inputPtr->at(0)->getGenome(); const Genome* parentGenome = genome->getParent(); if (parentGenome != NULL && parentGenome != prevGenome && ( parentGenome == tgtGenome || genomesOnPath->find(parentGenome) != genomesOnPath->end())) { nextGenome = parentGenome; } for (hal_size_t child = 0; nextGenome == NULL && child < genome->getNumChildren(); ++child) { // note that this code is potentially unfriendly to the // inmemory option where entire child genomes get loaded // when they may not be needed. but since the column iterator // does the same thing, we don't worry for now const Genome* childGenome = genome->getChild(child); if (childGenome != prevGenome && ( childGenome == tgtGenome || genomesOnPath->find(childGenome) != genomesOnPath->end())) { nextGenome = childGenome; nextChildIndex = child; } } } if (nextGenome != NULL) { outputPtr->clear(); if (nextGenome == genome->getParent()) { for (size_t i = 0; i < inputPtr->size(); ++i) { mapUp(inputPtr->at(i), *outputPtr); } } else { for (size_t i = 0; i < inputPtr->size(); ++i) { mapDown(inputPtr->at(i), nextChildIndex, *outputPtr); } if (doDupes == true) { size_t outputSize = outputPtr->size(); for (size_t i = 0; i <outputSize; ++i) { mapSelf(outputPtr->at(i), *outputPtr); } } } swap(inputPtr, outputPtr); assert(genome != NULL); mapRecursive(genome, *inputPtr, *outputPtr, tgtGenome, genomesOnPath, doDupes); } else { swap(inputPtr, outputPtr); } // could potentially save this copy but dont care for now if (outputPtr != &results) { results = *outputPtr; } return results.size(); } hal_size_t DefaultMappedSegment::mapUp( DefaultMappedSegmentConstPtr mappedSeg, vector<DefaultMappedSegmentConstPtr>& results) { const Genome* parent = mappedSeg->getGenome()->getParent(); assert(parent != NULL); hal_size_t added = 0; if (mappedSeg->isTop() == true) { BottomSegmentIteratorConstPtr bottom = parent->getBottomSegmentIterator(); TopSegmentIteratorConstPtr top = mappedSeg->targetAsTop(); if (top->hasParent() == true) { bottom->toParent(top); mappedSeg->_target = bottom.downCast<DefaultSegmentIteratorConstPtr>(); results.push_back(mappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); BottomSegmentIteratorConstPtr bottom = mappedSeg->targetAsBottom(); hal_index_t startOffset = (hal_index_t)bottom->getStartOffset(); hal_index_t endOffset = (hal_index_t)bottom->getEndOffset(); TopSegmentIteratorConstPtr top = mappedSeg->getGenome()->getTopSegmentIterator(); top->toParseUp(bottom); do { TopSegmentIteratorConstPtr topNew = top->copy(); // we map the new target back to see how the offsets have // changed. these changes are then applied to the source segment // as deltas BottomSegmentIteratorConstPtr bottomBack = bottom->copy(); bottomBack->toParseDown(topNew); hal_index_t startBack = (hal_index_t)bottomBack->getStartOffset(); hal_index_t endBack = (hal_index_t)bottomBack->getEndOffset(); assert(startBack >= startOffset); assert(endBack >= endOffset); SegmentIteratorConstPtr newSource = mappedSeg->sourceCopy(); hal_index_t startDelta = startBack - startOffset; hal_index_t endDelta = endBack - endOffset; assert(newSource->getLength() > startDelta + endDelta); newSource->slice(newSource->getStartOffset() + startDelta, newSource->getEndOffset() + endDelta); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(newSource, topNew)); assert(newMappedSeg->isTop() == true); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapUp(newMappedSeg, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (top->getEndPosition() != rightCutoff) { top->toRight(rightCutoff); } } while (top->getEndPosition() != rightCutoff); } return added; } hal_size_t DefaultMappedSegment::mapDown( DefaultMappedSegmentConstPtr mappedSeg, hal_size_t childIndex, vector<DefaultMappedSegmentConstPtr>& results) { const Genome* child = mappedSeg->getGenome()->getChild(childIndex); assert(child != NULL); hal_size_t added = 0; if (mappedSeg->isTop() == false) { TopSegmentIteratorConstPtr top = child->getTopSegmentIterator(); SegmentIteratorConstPtr target = mappedSeg->_target; BottomSegmentIteratorConstPtr bottom = target.downCast<BottomSegmentIteratorConstPtr>(); if (bottom->hasChild(childIndex) == true) { top->toChild(bottom, childIndex); mappedSeg->_target = top.downCast<DefaultSegmentIteratorConstPtr>(); results.push_back(mappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); TopSegmentIteratorConstPtr top = mappedSeg->targetAsTop(); hal_index_t startOffset = (hal_index_t)top->getStartOffset(); hal_index_t endOffset = (hal_index_t)top->getEndOffset(); BottomSegmentIteratorConstPtr bottom = mappedSeg->getGenome()->getBottomSegmentIterator(); bottom->toParseDown(top); do { BottomSegmentIteratorConstPtr bottomNew = bottom->copy(); // we map the new target back to see how the offsets have // changed. these changes are then applied to the source segment // as deltas TopSegmentIteratorConstPtr topBack = top->copy(); topBack->toParseUp(bottomNew); hal_index_t startBack = (hal_index_t)topBack->getStartOffset(); hal_index_t endBack = (hal_index_t)topBack->getEndOffset(); assert(startBack >= startOffset); assert(endBack >= endOffset); SegmentIteratorConstPtr newSource = mappedSeg->sourceCopy(); hal_index_t startDelta = startBack - startOffset; hal_index_t endDelta = endBack - endOffset; assert((hal_index_t)newSource->getLength() > startDelta + endDelta); newSource->slice(newSource->getStartOffset() + startDelta, newSource->getEndOffset() + endDelta); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(newSource, bottomNew)); assert(newMappedSeg->isTop() == false); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapDown(newMappedSeg, childIndex, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (bottom->getEndPosition() != rightCutoff) { bottom->toRight(rightCutoff); } } while (bottom->getEndPosition() != rightCutoff); } return added; } hal_size_t DefaultMappedSegment::mapSelf( DefaultMappedSegmentConstPtr mappedSeg, vector<DefaultMappedSegmentConstPtr>& results) { hal_size_t added = 0; if (mappedSeg->isTop() == true) { SegmentIteratorConstPtr target = mappedSeg->_target; TopSegmentIteratorConstPtr top = target.downCast<TopSegmentIteratorConstPtr>(); TopSegmentIteratorConstPtr topCopy = top->copy(); while (topCopy->hasNextParalogy() == true) { topCopy->toNextParalogy(); if (topCopy->getArrayIndex() == top->getArrayIndex()) { break; } SegmentIteratorConstPtr source = mappedSeg->_source; TopSegmentIteratorConstPtr newTop = topCopy->copy(); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment( mappedSeg->_source, newTop.downCast<DefaultSegmentIteratorConstPtr>())); results.push_back(newMappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); TopSegmentIteratorConstPtr top = mappedSeg->getGenome()->getTopSegmentIterator(); SegmentIteratorConstPtr target = mappedSeg->_target; BottomSegmentIteratorConstPtr bottom = target.downCast<BottomSegmentIteratorConstPtr>(); top->toParseUp(bottom); do { TopSegmentIteratorConstPtr topNew = top->copy(); BottomSegmentIteratorConstPtr bottomNew = bottom->copy(); bottomNew->toParseDown(top); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(bottomNew, topNew)); assert(newMappedSeg->isTop() == true); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapUp(newMappedSeg, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (top->getEndPosition() != rightCutoff) { top->toRight(rightCutoff); } } while (top->getEndPosition() != rightCutoff); } return added; } ////////////////////////////////////////////////////////////////////////////// // SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// void DefaultMappedSegment::setArrayIndex(Genome* genome, hal_index_t arrayIndex) { _target->setArrayIndex(genome, arrayIndex); } void DefaultMappedSegment::setArrayIndex(const Genome* genome, hal_index_t arrayIndex) const { _target->setArrayIndex(genome, arrayIndex); } const Genome* DefaultMappedSegment::getGenome() const { return _target->getGenome(); } Genome* DefaultMappedSegment::getGenome() { return const_cast<Genome*>(_target->getGenome()); } const Sequence* DefaultMappedSegment::getSequence() const { return _target->getSequence(); } Sequence* DefaultMappedSegment::getSequence() { return const_cast<Sequence*>(_target->getSequence()); } hal_index_t DefaultMappedSegment::getStartPosition() const { return _target->getStartPosition(); } hal_index_t DefaultMappedSegment::getEndPosition() const { return _target->getEndPosition(); } hal_size_t DefaultMappedSegment::getLength() const { return _target->getLength(); } void DefaultMappedSegment::getString(string& outString) const { _target->getString(outString); } void DefaultMappedSegment::setCoordinates(hal_index_t startPos, hal_size_t length) { throw hal_exception("DefaultMappedSegment::setCoordinates not imeplemented"); } hal_index_t DefaultMappedSegment::getArrayIndex() const { return _target->getArrayIndex(); } bool DefaultMappedSegment::leftOf(hal_index_t genomePos) const { return _target->leftOf(genomePos); } bool DefaultMappedSegment::rightOf(hal_index_t genomePos) const { return _target->rightOf(genomePos); } bool DefaultMappedSegment::overlaps(hal_index_t genomePos) const { return _target->overlaps(genomePos); } bool DefaultMappedSegment::isFirst() const { return _target->isFirst(); } bool DefaultMappedSegment::isLast() const { return _target->isLast(); } bool DefaultMappedSegment::isMissingData(double nThreshold) const { return _target->isMissingData(nThreshold); } bool DefaultMappedSegment::isTop() const { return _target->isTop(); } hal_size_t DefaultMappedSegment::getMappedSegments( vector<MappedSegmentConstPtr>& outSegments, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) const { return _target->getMappedSegments(outSegments, tgtGenome, genomesOnPath, doDupes); } ////////////////////////////////////////////////////////////////////////////// // SLICED SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// void DefaultMappedSegment::toReverse() const { _target->toReverse(); } hal_offset_t DefaultMappedSegment::getStartOffset() const { return _target->getStartOffset(); } hal_offset_t DefaultMappedSegment::getEndOffset() const { return _target->getEndOffset(); } void DefaultMappedSegment::slice(hal_offset_t startOffset , hal_offset_t endOffset ) const { throw hal_exception("DefaultMappedSegment::slice not implemented"); } bool DefaultMappedSegment::getReversed() const { return _target->getReversed(); }
/* * Copyright (C) 2013 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include <string> #include <sstream> #include <iostream> #include <limits> #include <algorithm> #include "hal.h" #include "defaultMappedSegment.h" #include "defaultTopSegmentIterator.h" #include "defaultBottomSegmentIterator.h" using namespace std; using namespace hal; DefaultMappedSegment::DefaultMappedSegment( SegmentIteratorConstPtr source, SegmentIteratorConstPtr target) : _source(source.downCast<DefaultSegmentIteratorConstPtr>()), _target(target.downCast<DefaultSegmentIteratorConstPtr>()) { assert(_source->getLength() == _target->getLength()); } DefaultMappedSegment::~DefaultMappedSegment() { } ////////////////////////////////////////////////////////////////////////////// // MAPPED SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// SlicedSegmentConstPtr DefaultMappedSegment::getSource() const { return _source; } ////////////////////////////////////////////////////////////////////////////// // INTERNAL FUNCTIONS ////////////////////////////////////////////////////////////////////////////// hal_size_t DefaultMappedSegment::map(const DefaultSegmentIterator* source, vector<MappedSegmentConstPtr>& results, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) { assert(source != NULL); SegmentIteratorConstPtr startSource; SegmentIteratorConstPtr startTarget; if (source->isTop()) { startSource = dynamic_cast<const DefaultTopSegmentIterator*>(source)->copy(); startTarget = dynamic_cast<const DefaultTopSegmentIterator*>(source)->copy(); } else { startSource = dynamic_cast<const DefaultBottomSegmentIterator*>(source)->copy(); startTarget = dynamic_cast<const DefaultBottomSegmentIterator*>(source)->copy(); } DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(startSource, startTarget)); vector<DefaultMappedSegmentConstPtr> input(1, newMappedSeg); vector<DefaultMappedSegmentConstPtr> output; mapRecursive(NULL, input, output, tgtGenome, genomesOnPath, doDupes); results.insert(results.end(), output.begin(), output.end()); return output.size(); } hal_size_t DefaultMappedSegment::mapRecursive( const Genome* prevGenome, vector<DefaultMappedSegmentConstPtr>& input, vector<DefaultMappedSegmentConstPtr>& results, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) { vector<DefaultMappedSegmentConstPtr>* inputPtr = &input; vector<DefaultMappedSegmentConstPtr>* outputPtr = &results; const Genome* srcGenome = NULL; const Genome* genome = NULL; const Genome* nextGenome = NULL; hal_size_t nextChildIndex = numeric_limits<hal_size_t>::max(); if (!inputPtr->empty()) { srcGenome = inputPtr->at(0)->getSource()->getGenome(); genome = inputPtr->at(0)->getGenome(); const Genome* parentGenome = genome->getParent(); if (parentGenome != NULL && parentGenome != prevGenome && ( parentGenome == tgtGenome || genomesOnPath->find(parentGenome) != genomesOnPath->end())) { nextGenome = parentGenome; } for (hal_size_t child = 0; nextGenome == NULL && child < genome->getNumChildren(); ++child) { // note that this code is potentially unfriendly to the // inmemory option where entire child genomes get loaded // when they may not be needed. but since the column iterator // does the same thing, we don't worry for now const Genome* childGenome = genome->getChild(child); if (childGenome != prevGenome && ( childGenome == tgtGenome || genomesOnPath->find(childGenome) != genomesOnPath->end())) { nextGenome = childGenome; nextChildIndex = child; } } } if (nextGenome != NULL) { outputPtr->clear(); if (nextGenome == genome->getParent()) { for (size_t i = 0; i < inputPtr->size(); ++i) { mapUp(inputPtr->at(i), *outputPtr); } } else { for (size_t i = 0; i < inputPtr->size(); ++i) { mapDown(inputPtr->at(i), nextChildIndex, *outputPtr); } if (doDupes == true) { size_t outputSize = outputPtr->size(); for (size_t i = 0; i <outputSize; ++i) { mapSelf(outputPtr->at(i), *outputPtr); } } } swap(inputPtr, outputPtr); assert(genome != NULL); mapRecursive(genome, *inputPtr, *outputPtr, tgtGenome, genomesOnPath, doDupes); } else { swap(inputPtr, outputPtr); } // could potentially save this copy but dont care for now if (outputPtr != &results) { results = *outputPtr; } return results.size(); } hal_size_t DefaultMappedSegment::mapUp( DefaultMappedSegmentConstPtr mappedSeg, vector<DefaultMappedSegmentConstPtr>& results) { const Genome* parent = mappedSeg->getGenome()->getParent(); assert(parent != NULL); hal_size_t added = 0; if (mappedSeg->isTop() == true) { BottomSegmentIteratorConstPtr bottom = parent->getBottomSegmentIterator(); TopSegmentIteratorConstPtr top = mappedSeg->targetAsTop(); if (top->hasParent() == true) { bottom->toParent(top); mappedSeg->_target = bottom.downCast<DefaultSegmentIteratorConstPtr>(); results.push_back(mappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); BottomSegmentIteratorConstPtr bottom = mappedSeg->targetAsBottom(); hal_index_t startOffset = (hal_index_t)bottom->getStartOffset(); hal_index_t endOffset = (hal_index_t)bottom->getEndOffset(); TopSegmentIteratorConstPtr top = mappedSeg->getGenome()->getTopSegmentIterator(); top->toParseUp(bottom); do { TopSegmentIteratorConstPtr topNew = top->copy(); // we map the new target back to see how the offsets have // changed. these changes are then applied to the source segment // as deltas BottomSegmentIteratorConstPtr bottomBack = bottom->copy(); bottomBack->toParseDown(topNew); hal_index_t startBack = (hal_index_t)bottomBack->getStartOffset(); hal_index_t endBack = (hal_index_t)bottomBack->getEndOffset(); assert(startBack >= startOffset); assert(endBack >= endOffset); SegmentIteratorConstPtr newSource = mappedSeg->sourceCopy(); hal_index_t startDelta = startBack - startOffset; hal_index_t endDelta = endBack - endOffset; assert(newSource->getLength() > startDelta + endDelta); newSource->slice(newSource->getStartOffset() + startDelta, newSource->getEndOffset() + endDelta); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(newSource, topNew)); assert(newMappedSeg->isTop() == true); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapUp(newMappedSeg, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (top->getEndPosition() != rightCutoff) { top->toRight(rightCutoff); } else { break; } } while (true); } return added; } hal_size_t DefaultMappedSegment::mapDown( DefaultMappedSegmentConstPtr mappedSeg, hal_size_t childIndex, vector<DefaultMappedSegmentConstPtr>& results) { const Genome* child = mappedSeg->getGenome()->getChild(childIndex); assert(child != NULL); hal_size_t added = 0; if (mappedSeg->isTop() == false) { TopSegmentIteratorConstPtr top = child->getTopSegmentIterator(); SegmentIteratorConstPtr target = mappedSeg->_target; BottomSegmentIteratorConstPtr bottom = target.downCast<BottomSegmentIteratorConstPtr>(); if (bottom->hasChild(childIndex) == true) { top->toChild(bottom, childIndex); mappedSeg->_target = top.downCast<DefaultSegmentIteratorConstPtr>(); results.push_back(mappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); TopSegmentIteratorConstPtr top = mappedSeg->targetAsTop(); hal_index_t startOffset = (hal_index_t)top->getStartOffset(); hal_index_t endOffset = (hal_index_t)top->getEndOffset(); BottomSegmentIteratorConstPtr bottom = mappedSeg->getGenome()->getBottomSegmentIterator(); bottom->toParseDown(top); cout << endl; cout << "PARSING DOWN RC=" << rightCutoff << endl; do { BottomSegmentIteratorConstPtr bottomNew = bottom->copy(); cout << bottomNew << endl; cout << "END " << bottomNew->getEndPosition() << endl; // we map the new target back to see how the offsets have // changed. these changes are then applied to the source segment // as deltas TopSegmentIteratorConstPtr topBack = top->copy(); topBack->toParseUp(bottomNew); hal_index_t startBack = (hal_index_t)topBack->getStartOffset(); hal_index_t endBack = (hal_index_t)topBack->getEndOffset(); assert(startBack >= startOffset); assert(endBack >= endOffset); SegmentIteratorConstPtr newSource = mappedSeg->sourceCopy(); hal_index_t startDelta = startBack - startOffset; hal_index_t endDelta = endBack - endOffset; assert((hal_index_t)newSource->getLength() > startDelta + endDelta); newSource->slice(newSource->getStartOffset() + startDelta, newSource->getEndOffset() + endDelta); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(newSource, bottomNew)); assert(newMappedSeg->isTop() == false); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapDown(newMappedSeg, childIndex, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (bottom->getEndPosition() != rightCutoff) { bottom->toRight(rightCutoff); } else { break; } } while (true); } return added; } hal_size_t DefaultMappedSegment::mapSelf( DefaultMappedSegmentConstPtr mappedSeg, vector<DefaultMappedSegmentConstPtr>& results) { hal_size_t added = 0; if (mappedSeg->isTop() == true) { SegmentIteratorConstPtr target = mappedSeg->_target; TopSegmentIteratorConstPtr top = target.downCast<TopSegmentIteratorConstPtr>(); TopSegmentIteratorConstPtr topCopy = top->copy(); while (topCopy->hasNextParalogy() == true) { topCopy->toNextParalogy(); if (topCopy->getArrayIndex() == top->getArrayIndex()) { break; } SegmentIteratorConstPtr source = mappedSeg->_source; TopSegmentIteratorConstPtr newTop = topCopy->copy(); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment( mappedSeg->_source, newTop.downCast<DefaultSegmentIteratorConstPtr>())); results.push_back(newMappedSeg); ++added; } } else { hal_index_t rightCutoff = mappedSeg->getEndPosition(); TopSegmentIteratorConstPtr top = mappedSeg->getGenome()->getTopSegmentIterator(); SegmentIteratorConstPtr target = mappedSeg->_target; BottomSegmentIteratorConstPtr bottom = target.downCast<BottomSegmentIteratorConstPtr>(); top->toParseUp(bottom); do { TopSegmentIteratorConstPtr topNew = top->copy(); BottomSegmentIteratorConstPtr bottomNew = bottom->copy(); bottomNew->toParseDown(top); DefaultMappedSegmentConstPtr newMappedSeg( new DefaultMappedSegment(bottomNew, topNew)); assert(newMappedSeg->isTop() == true); assert(newMappedSeg->getSource()->getGenome() == mappedSeg->getSource()->getGenome()); added += mapUp(newMappedSeg, results); // stupid that we have to make this check but odn't want to // make fundamental api change now if (top->getEndPosition() != rightCutoff) { top->toRight(rightCutoff); } else { break; } } while (true); } return added; } ////////////////////////////////////////////////////////////////////////////// // SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// void DefaultMappedSegment::setArrayIndex(Genome* genome, hal_index_t arrayIndex) { _target->setArrayIndex(genome, arrayIndex); } void DefaultMappedSegment::setArrayIndex(const Genome* genome, hal_index_t arrayIndex) const { _target->setArrayIndex(genome, arrayIndex); } const Genome* DefaultMappedSegment::getGenome() const { return _target->getGenome(); } Genome* DefaultMappedSegment::getGenome() { return const_cast<Genome*>(_target->getGenome()); } const Sequence* DefaultMappedSegment::getSequence() const { return _target->getSequence(); } Sequence* DefaultMappedSegment::getSequence() { return const_cast<Sequence*>(_target->getSequence()); } hal_index_t DefaultMappedSegment::getStartPosition() const { return _target->getStartPosition(); } hal_index_t DefaultMappedSegment::getEndPosition() const { return _target->getEndPosition(); } hal_size_t DefaultMappedSegment::getLength() const { return _target->getLength(); } void DefaultMappedSegment::getString(string& outString) const { _target->getString(outString); } void DefaultMappedSegment::setCoordinates(hal_index_t startPos, hal_size_t length) { throw hal_exception("DefaultMappedSegment::setCoordinates not imeplemented"); } hal_index_t DefaultMappedSegment::getArrayIndex() const { return _target->getArrayIndex(); } bool DefaultMappedSegment::leftOf(hal_index_t genomePos) const { return _target->leftOf(genomePos); } bool DefaultMappedSegment::rightOf(hal_index_t genomePos) const { return _target->rightOf(genomePos); } bool DefaultMappedSegment::overlaps(hal_index_t genomePos) const { return _target->overlaps(genomePos); } bool DefaultMappedSegment::isFirst() const { return _target->isFirst(); } bool DefaultMappedSegment::isLast() const { return _target->isLast(); } bool DefaultMappedSegment::isMissingData(double nThreshold) const { return _target->isMissingData(nThreshold); } bool DefaultMappedSegment::isTop() const { return _target->isTop(); } hal_size_t DefaultMappedSegment::getMappedSegments( vector<MappedSegmentConstPtr>& outSegments, const Genome* tgtGenome, const set<const Genome*>* genomesOnPath, bool doDupes) const { return _target->getMappedSegments(outSegments, tgtGenome, genomesOnPath, doDupes); } ////////////////////////////////////////////////////////////////////////////// // SLICED SEGMENT INTERFACE ////////////////////////////////////////////////////////////////////////////// void DefaultMappedSegment::toReverse() const { _target->toReverse(); } hal_offset_t DefaultMappedSegment::getStartOffset() const { return _target->getStartOffset(); } hal_offset_t DefaultMappedSegment::getEndOffset() const { return _target->getEndOffset(); } void DefaultMappedSegment::slice(hal_offset_t startOffset , hal_offset_t endOffset ) const { throw hal_exception("DefaultMappedSegment::slice not implemented"); } bool DefaultMappedSegment::getReversed() const { return _target->getReversed(); }
fix iteration end condition
fix iteration end condition
C++
mit
glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal
d8c4a46aed7155e5a5d219cebfe6b5b56c3c8917
source/annotatorlib/source/Commands/NewAnnotation.cpp
source/annotatorlib/source/Commands/NewAnnotation.cpp
#include <AnnotatorLib/Annotation.h> #include <AnnotatorLib/Commands/NewAnnotation.h> #include <AnnotatorLib/Object.h> #include <AnnotatorLib/Session.h> AnnotatorLib::Commands::NewAnnotation::NewAnnotation( const unsigned long newObjectId, const shared_ptr<Class> newObjectClass, AnnotatorLib::Session *session, shared_ptr<Frame> frame, float x, float y, float width, float height ) : createNewObject(true) { this->session = session; this->annotation_ = Annotation::make_shared(frame, std::make_shared<Object>(newObjectId, newObjectClass)); this->annotation_->setPosition(x, y, width, height); } AnnotatorLib::Commands::NewAnnotation::NewAnnotation( AnnotatorLib::Session *session, shared_ptr<Object> object, shared_ptr<Frame> frame, float x, float y, float width, float height) : createNewObject(false) { this->session = session; this->annotation_ = Annotation::make_shared(frame, object); this->annotation_->setPosition(x, y, width, height); } bool AnnotatorLib::Commands::NewAnnotation::execute() { bool success = session->addAnnotation(annotation_, true); // adds annotation and register to them if (createNewObject && success) createdNewObject = true; } bool AnnotatorLib::Commands::NewAnnotation::undo() { this->annotation_ = session->removeAnnotation(annotation_->getId(), true); // remove annotation from session and unregister // remove frame and object if empty if (!this->annotation_->getObject()->hasAnnotations()) session->removeObject(this->annotation_->getObject()->getId(), false); if (!this->annotation_->getObject()->hasAnnotations()) session->removeFrame(this->annotation_->getFrame()->getId(), false); return !this->annotation_; } shared_ptr<AnnotatorLib::Annotation> AnnotatorLib::Commands::NewAnnotation::getAnnotation() { return annotation_; }
#include <AnnotatorLib/Annotation.h> #include <AnnotatorLib/Commands/NewAnnotation.h> #include <AnnotatorLib/Object.h> #include <AnnotatorLib/Session.h> AnnotatorLib::Commands::NewAnnotation::NewAnnotation( const unsigned long newObjectId, const shared_ptr<Class> newObjectClass, AnnotatorLib::Session *session, shared_ptr<Frame> frame, float x, float y, float width, float height ) : createNewObject(true) { this->session = session; this->annotation_ = Annotation::make_shared(frame, std::make_shared<Object>(newObjectId, newObjectClass)); this->annotation_->setPosition(x, y, width, height); } AnnotatorLib::Commands::NewAnnotation::NewAnnotation( AnnotatorLib::Session *session, shared_ptr<Object> object, shared_ptr<Frame> frame, float x, float y, float width, float height) : createNewObject(false) { this->session = session; this->annotation_ = Annotation::make_shared(frame, object); this->annotation_->setPosition(x, y, width, height); } bool AnnotatorLib::Commands::NewAnnotation::execute() { bool success = session->addAnnotation(annotation_, true); // adds annotation and register to them if (createNewObject && success) createdNewObject = true; return success; } bool AnnotatorLib::Commands::NewAnnotation::undo() { this->annotation_ = session->removeAnnotation(annotation_->getId(), true); // remove annotation from session and unregister // remove frame and object if empty if (!this->annotation_->getObject()->hasAnnotations()) session->removeObject(this->annotation_->getObject()->getId(), false); if (!this->annotation_->getObject()->hasAnnotations()) session->removeFrame(this->annotation_->getFrame()->getId(), false); return !this->annotation_; } shared_ptr<AnnotatorLib::Annotation> AnnotatorLib::Commands::NewAnnotation::getAnnotation() { return annotation_; }
return if command weas successfull
return if command weas successfull
C++
apache-2.0
annotatorproject/annotatorlib,annotatorproject/annotatorlib,annotatorproject/annotatorlib,lasmue/annotatorlib,lasmue/annotatorlib
f20985ba9e00e34d42caf738c8cf2024342df875
src/bitcoind.cpp
src/bitcoind.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "config.h" #include "fs.h" #include "httprpc.h" #include "httpserver.h" #include "init.h" #include "noui.h" #include "rpc/server.h" #include "scheduler.h" #include "unlimited.h" #include "util.h" #include "utilstrencodings.h" #include "unlimited.h" //#include "versionbits.h" #include "forks_csv.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * //www.bitcoin.org/), * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https: * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void WaitForShutdown(boost::thread_group *threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { Interrupt(*threadGroup); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char *argv[]) { boost::thread_group threadGroup; CScheduler scheduler; auto &config = const_cast<Config &>(GetConfig()); bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() AllowedArgs::Bitcoind allowedArgs(&tweaks); try { ParseParameters(argc, argv, allowedArgs); } catch (const std::exception &e) { fprintf(stderr, "Error parsing program options: %s\n", e.what()); return false; } // Process help and version before taking care about datadir if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (mapArgs.count("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " bitcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + allowedArgs.helpMessage(); } fprintf(stdout, "%s", strUsage.c_str()); return true; } // bip135 begin // dump default deployment info and exit, if requested if (mapArgs.count("-dumpforks")) { std::string strVersion = "# " + strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion(); fprintf(stdout, "%s\n%s", strVersion.c_str(), FORKS_CSV_FILE_HEADER); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::MAIN).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::UNL).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::TESTNET).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::REGTEST).c_str()); return true; } // bip135 end try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs, allowedArgs); } catch (const std::exception &e) { fprintf(stderr, "Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception &e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:") && !boost::algorithm::istarts_with(argv[i], "bitcoincash:")) { fCommandLine = true; break; } } if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli " "utility instead.\n"); return false; } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Bitcoin server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); fRet = AppInit2(config, threadGroup, scheduler); } catch (const std::exception &e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } UnlimitedSetup(); if (!fRet) { Interrupt(threadGroup); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char *argv[]) { SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "config.h" #include "fs.h" #include "httprpc.h" #include "httpserver.h" #include "init.h" #include "noui.h" #include "rpc/server.h" #include "scheduler.h" #include "unlimited.h" #include "util.h" #include "utilstrencodings.h" #include "unlimited.h" //#include "versionbits.h" #include "forks_csv.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * //www.bitcoin.org/), * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https: * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void WaitForShutdown(boost::thread_group *threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { Interrupt(*threadGroup); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char *argv[]) { boost::thread_group threadGroup; CScheduler scheduler; auto &config = const_cast<Config &>(GetConfig()); bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() AllowedArgs::Bitcoind allowedArgs(&tweaks); try { ParseParameters(argc, argv, allowedArgs); } catch (const std::exception &e) { fprintf(stderr, "Error parsing program options: %s\n", e.what()); return false; } // Process help and version before taking care about datadir if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (mapArgs.count("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " bitcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + allowedArgs.helpMessage(); } fprintf(stdout, "%s", strUsage.c_str()); return true; } // bip135 begin // dump default deployment info and exit, if requested if (GetBoolArg("-dumpforks", false)) { std::string strVersion = "# " + strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion(); fprintf(stdout, "%s\n%s", strVersion.c_str(), FORKS_CSV_FILE_HEADER); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::MAIN).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::UNL).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::TESTNET).c_str()); fprintf(stdout, "%s", NetworkDeploymentInfoCSV(CBaseChainParams::REGTEST).c_str()); return true; } // bip135 end try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs, allowedArgs); } catch (const std::exception &e) { fprintf(stderr, "Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception &e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:") && !boost::algorithm::istarts_with(argv[i], "bitcoincash:")) { fCommandLine = true; break; } } if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli " "utility instead.\n"); return false; } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Bitcoin server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); fRet = AppInit2(config, threadGroup, scheduler); } catch (const std::exception &e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } UnlimitedSetup(); if (!fRet) { Interrupt(threadGroup); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char *argv[]) { SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); }
Use GetBoolArg to check dumpforks
[review] Use GetBoolArg to check dumpforks
C++
mit
BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited
afd99c9c81ec37a294b14612ff98a4af6daabe29
modules/cuda/src/precomp.hpp
modules/cuda/src/precomp.hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/cuda.hpp" #include "opencv2/cudaarithm.hpp" #include "opencv2/cudawarping.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/core/private.cuda.hpp" #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_CUDALEGACY # include "opencv2/cudalegacy/private.hpp" #endif #endif /* __OPENCV_PRECOMP_H__ */
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/cuda.hpp" #include "opencv2/cudaarithm.hpp" #include "opencv2/cudawarping.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/core/private.cuda.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_CUDALEGACY # include "opencv2/cudalegacy/private.hpp" #endif #endif /* __OPENCV_PRECOMP_H__ */
fix bug #3544:
fix bug #3544: add "opencv2/core/utility.hpp" header to precomp.hpp
C++
apache-2.0
opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv
5db5af997e59b4ab0d4a380ee41ed530302a50be
src/bufstream.cc
src/bufstream.cc
/* Copyright (c) 2014 Noel R. Cower 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 USEOR OTHER DEALINGS IN THE SOFTWARE. */ #include "bufstream.hh" #include <sstream> typedef std::basic_stringstream< #if __cplusplus >= 201103L char, std::char_traits<char>, sz_cxx_allocator_t<char> #else char, std::char_traits<char> #endif > sz_buffer_t; static size_t sz_bufstream_read(void *out, size_t length, sz_stream_t *stream); static size_t sz_bufstream_write(const void *in, size_t length, sz_stream_t *stream); static off_t sz_bufstream_seek(off_t off, int whence, sz_stream_t *stream); static int sz_bufstream_eof(sz_stream_t *stream); static void sz_bufstream_close(sz_stream_t *stream); struct SZ_HIDDEN sz_bufstream_t { sz_stream_t base; sz_allocator_t *alloc; sz_mode_t mode; uint8_t opaque[sizeof(sz_buffer_t)]; sz_buffer_t *buffer() { return (sz_buffer_t *)&opaque[0]; } void init() { new (opaque) sz_buffer_t( #if __cplusplus >= 201103L sz_bufstring_t(sz_cxx_allocator_t<char>(alloc)) #endif ); } void finalize() { buffer()->~sz_buffer_t(); } }; static sz_stream_t sz_bufstream_base = { sz_bufstream_read, sz_bufstream_write, sz_bufstream_seek, sz_bufstream_eof, sz_bufstream_close }; sz_stream_t * sz_buffer_stream(sz_mode_t mode, sz_allocator_t *alloc) { sz_bufstream_t *stream = (sz_bufstream_t *)sz_malloc(sizeof(sz_bufstream_t), alloc); stream->base = sz_bufstream_base; stream->init(); stream->mode = mode; return (sz_stream_t *)stream; } sz_bufstring_t sz_buffer_stream_data(sz_stream_t *stream) { return ((sz_bufstream_t *)stream)->buffer()->str(); } static size_t sz_bufstream_read(void *out, size_t length, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; if (bufstream->mode == SZ_READER) { bufstream->buffer()->read((char *)out, length); return bufstream->buffer()->gcount(); } return 0; } static size_t sz_bufstream_write(const void *in, size_t length, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; if (bufstream->mode == SZ_READER) { off_t offset = bufstream->buffer()->tellp(); bufstream->buffer()->write((const char *)in, length); return size_t(bufstream->buffer()->tellp() - offset); } return 0; } static off_t sz_bufstream_seek(off_t off, int whence, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; sz_buffer_t::seekdir dir = sz_buffer_t::beg; switch (whence) { case SEEK_CUR: dir = sz_buffer_t::cur; break; case SEEK_END: dir = sz_buffer_t::end; break; case SEEK_SET: default: break; } if (bufstream->mode == SZ_WRITER) { bufstream->buffer()->seekp(off, dir); return bufstream->buffer()->tellp(); } else { bufstream->buffer()->seekg(off, dir); return bufstream->buffer()->tellg(); } } static int sz_bufstream_eof(sz_stream_t *stream) { return ((sz_bufstream_t *)stream)->buffer()->eof(); } static void sz_bufstream_close(sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; bufstream->finalize(); sz_free(bufstream, bufstream->alloc); }
/* Copyright (c) 2014 Noel R. Cower 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 USEOR OTHER DEALINGS IN THE SOFTWARE. */ #include "bufstream.hh" #include <sstream> typedef std::basic_stringstream< #if __cplusplus >= 201103L char, std::char_traits<char>, sz_cxx_allocator_t<char> #else char, std::char_traits<char> #endif > sz_buffer_t; static size_t sz_bufstream_read(void *out, size_t length, sz_stream_t *stream); static size_t sz_bufstream_write(const void *in, size_t length, sz_stream_t *stream); static off_t sz_bufstream_seek(off_t off, int whence, sz_stream_t *stream); static int sz_bufstream_eof(sz_stream_t *stream); static void sz_bufstream_close(sz_stream_t *stream); struct SZ_HIDDEN sz_bufstream_t { sz_stream_t base; sz_allocator_t *alloc; sz_mode_t mode; uint8_t opaque[sizeof(sz_buffer_t)]; sz_buffer_t *buffer() { return (sz_buffer_t *)&opaque[0]; } void init() { new (opaque) sz_buffer_t( #if __cplusplus >= 201103L sz_bufstring_t(sz_cxx_allocator_t<char>(alloc)) #endif ); } void finalize() { buffer()->~sz_buffer_t(); } }; static sz_stream_t sz_bufstream_base = { sz_bufstream_read, sz_bufstream_write, sz_bufstream_seek, sz_bufstream_eof, sz_bufstream_close }; sz_stream_t * sz_buffer_stream(sz_mode_t mode, sz_allocator_t *alloc) { sz_bufstream_t *stream = (sz_bufstream_t *)sz_malloc(sizeof(sz_bufstream_t), alloc); stream->base = sz_bufstream_base; stream->init(); stream->mode = mode; return (sz_stream_t *)stream; } sz_bufstring_t sz_buffer_stream_data(sz_stream_t *stream) { return ((sz_bufstream_t *)stream)->buffer()->str(); } static size_t sz_bufstream_read(void *out, size_t length, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; if (bufstream->mode == SZ_READER) { bufstream->buffer()->read((char *)out, length); return bufstream->buffer()->gcount(); } return 0; } static size_t sz_bufstream_write(const void *in, size_t length, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; if (bufstream->mode == SZ_WRITER) { off_t offset = bufstream->buffer()->tellp(); bufstream->buffer()->write((const char *)in, length); return size_t(bufstream->buffer()->tellp() - offset); } return 0; } static off_t sz_bufstream_seek(off_t off, int whence, sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; sz_buffer_t::seekdir dir = sz_buffer_t::beg; switch (whence) { case SEEK_CUR: dir = sz_buffer_t::cur; break; case SEEK_END: dir = sz_buffer_t::end; break; case SEEK_SET: default: break; } if (bufstream->mode == SZ_WRITER) { bufstream->buffer()->seekp(off, dir); return bufstream->buffer()->tellp(); } else { bufstream->buffer()->seekg(off, dir); return bufstream->buffer()->tellg(); } } static int sz_bufstream_eof(sz_stream_t *stream) { return ((sz_bufstream_t *)stream)->buffer()->eof(); } static void sz_bufstream_close(sz_stream_t *stream) { sz_bufstream_t *bufstream = (sz_bufstream_t *)stream; bufstream->finalize(); sz_free(bufstream, bufstream->alloc); }
Fix incorrect mode check in sz_bufstream_write.
Fix incorrect mode check in sz_bufstream_write. Was causing a failure in a test.
C++
mit
nilium/libsnowball
95a3f0daf72b4fc5a1b87f781f84877856034a11
include/Pomdog/Basic/Platform.hpp
include/Pomdog/Basic/Platform.hpp
// // Copyright (C) 2013-2015 mogemimi. // Distributed under the MIT License. See LICENSE.md or // http://enginetrouble.net/pomdog/license for details. // #ifndef POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP #define POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP #if (_MSC_VER > 1000) #pragma once #endif namespace Pomdog { namespace Details { //---------------------------- // Choose compiler //---------------------------- #if defined(_MSC_VER) # define POMDOG_COMPILER_MSVC //# define POMDOG_COMPILER_VERSION _MSC_VER #elif defined(__clang__) # define POMDOG_COMPILER_CLANG //# define POMDOG_COMPILER_VERSION ((__clang_major__*100) + (__clang_minor__*10) + __clang_patchlevel__) #elif defined(__GNUC__) # define POMDOG_COMPILER_GNUC //# define POMDOG_COMPILER_VERSION ((__GNUC__*100) + (__GNUC_MINOR__*10) + __GNUC_PATCHLEVEL__) #elid defined(__BORLANDC__) && defined(__BCPLUSPLUS__) # define POMDOG_COMPILER_BORLAND //# define POMDOG_COMPILER_VERSION (__BCPLUSPLUS__) #else # error "Compiler undefined or not supported." #endif //---------------------------- // Choose platform //---------------------------- #if defined(linux) || defined(__linux) || defined(__linux__) # // Linux # define POMDOG_PLATFORM_LINUX #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) # // BSD # define POMDOG_PLATFORM_BSD #elif defined(_XBOX_ONE) && defined(_TITLE) # // Xbox One # define POMDOG_PLATFORM_XBOX_ONE #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) # // Windows # define POMDOG_PLATFORM_WIN32 #elif defined(ANDROID) || defined(__ANDROID__) # // Android OS # define POMDOG_PLATFORM_ANDROID #elif defined(__APPLE_CC__) && ((__IPHONE_OS_VERSION_MIN_REQUIRED >= 60000) || (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 60000)) # // Apple iOS 6 or later # define POMDOG_PLATFORM_APPLE_IOS #elif defined(__APPLE_CC__) # // Mac OSX # define POMDOG_PLATFORM_MACOSX #elif defined(__QNXNTO__) # // QNX Neutrino # define POMDOG_PLATFORM_QNXNTO #elif defined(__native_client__) # // Google Native Client(NaCl) # define POMDOG_PLATFORM_NACL #elif defined(__CYGWIN__) # // Cygwin # define POMDOG_PLATFORM_CYGWIN #elif defined(sun) || defined(__sun) # // Solaris # define POMDOG_PLATFORM_SOLARIS #elif defined(__hpux) # // Hewlett-Packard UNIX # define POMDOG_PLATFORM_HPUX #else # error "Sorry, this platform is not supported." #endif //---------------------------- // Hardware Architecture //---------------------------- #if defined(_M_IX86) /* msvc */ \ || defined(_X86_) \ || defined(__i386__) /* gcc */ \ || defined(__i386) /* gcc */ \ || defined(i386) # // x86 processors # define POMDOG_ARCHITECTURE_IX86 #elif \ defined(_M_X64) /* msvc */ \ || defined(_AMD64_) \ || defined(__x86_64__) /* 64-bit linux */ # // x64 processors # define POMDOG_ARCHITECTURE_AMD64 #elif \ defined(_M_IA64) /* msvc */ \ || defined(__ia64__) \ || defined(__ia64) \ || defined(__IA64__) \ || defined(_IA64) \ || defined(ia64) # // Itanium architecture, 64-bit processors # define POMDOG_ARCHITECTURE_IA64 #elif \ defined(__arm__) /* gcc */ \ || defined(__arm) /* gcc */ \ || defined(_ARM_) /* c compiler */ \ || defined(ARM) \ || defined(__ARM__) \ || defined(_M_ARM) /* windows mobile 5 */ # // ARM architecture # define POMDOG_ARCHITECTURE_ARM #elif \ defined(_M_PPC) /* msvc */ \ || defined(__powerpc__) /* gcc */ \ || defined(__powerpc) \ || defined(__POWERPC__) \ || defined(__PPC) \ || defined(_ARCH_PPC) # ///@note __powerpc64__ # // PowerPC platforms # define POMDOG_ARCHITECTURE_POWERPC #elif \ defined(_POWER) \ || defined(_ARCH_PWR) \ || defined(_ARCH_COM) # // Power architecture # define POMDOG_ARCHITECTURE_POWER #elif \ defined(_M_MRX000) /* msvc */ \ || defined(__mips__) \ || defined(__mips) \ || defined(__MIPS__) # // MIPS platforms # define POMDOG_ARCHITECTURE_MIPS #elif \ defined(_M_ALPHA) /* msvc */ \ || defined(__alpha__) \ || defined(__alpha) # // DEC Alpha platforms # define POMDOG_ARCHITECTURE_ALPHA #endif //---------------------------- // Byte order //---------------------------- #if defined(POMDOG_ARCHITECTURE_IX86) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_ARCHITECTURE_AMD64) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_ARCHITECTURE_IA64) # if defined(_hpux) || defined(hpux) # // HP-UX is big-endian. # define POMDOG_BYTEORDER_BIG_ENDIAN # else # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_ARM) # if defined(__ARMEB__) # // 'EB' is big-endian # define POMDOG_BYTEORDER_BIG_ENDIAN # else //__ARMEL__ # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_POWERPC) # define POMDOG_BYTEORDER_BIG_ENDIAN #elif defined(POMDOG_ARCHITECTURE_POWER) # define POMDOG_BYTEORDER_BIG_ENDIAN #elif defined(POMDOG_ARCHITECTURE_MIPS) # if defined(MIPSEB) || defined(_MIPSEB) || defined(__MIPSEB) # define POMDOG_BYTEORDER_BIG_ENDIAN # else// MIPSEL, _MIPSEL, __MIPSEL # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_ALPHA) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_COMPILER_GNUC) # if (((__GNUC__*100) + (__GNUC_MINOR__*10) + __GNUC_PATCHLEVEL__) >= 310) # // include header <endian.h> in the global namespace. # if defined (__LITTLE_ENDIAN__) || (__BYTE_ORDER == __LITTLE_ENDIAN) # define POMDOG_BYTEORDER_LITTLE_ENDIAN # elif defined (__BIG_ENDIAN__) || (__BYTE_ORDER == __BIG_ENDIAN) # define POMDOG_BYTEORDER_BIG_ENDIAN # endif # endif #else # error "Byte order undefined or not supported." #endif #if (defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && !defined(POMDOG_BYTEORDER_BIG_ENDIAN) && !(POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #elif (!defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && defined(POMDOG_BYTEORDER_BIG_ENDIAN) && !(POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #elif (!defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && !defined(POMDOG_BYTEORDER_BIG_ENDIAN) && (POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #else # error "Byte order undefined or not supported." #endif //---------------------------------- // C++11 support/not supported //---------------------------------- #ifndef __has_feature // Optional of course. # define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension # define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif #if defined(POMDOG_COMPILER_MSVC) \ && (_MSC_VER >= 1600) # // Support C++11 under MSVC #elif defined(POMDOG_COMPILER_CLANG) \ && __has_feature(cxx_lambdas) \ && __has_feature(cxx_nullptr) \ && __has_feature(cxx_static_assert) \ && __has_feature(cxx_strong_enums) \ && __has_feature(cxx_defaulted_functions) # // Support C++11 under Clang++ # // See also: # // http://clang.llvm.org/docs/LanguageExtensions.html#checking_upcoming_features #elif defined(POMDOG_COMPILER_GNUC) \ && defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus >= 201103L # // Support C++11 under GCC # // See also: # // http://gcc.gnu.org/projects/cxx0x.html #else # error "C++11/C++0x is not supported." #endif //---------------------------- // debug or release //---------------------------- #if defined(DEBUG) && defined(NDEBUG) # error "Both DEBUG and NDEBUG are defined." #endif }// namespace Details }// namespace Pomdog #endif // !defined(POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP)
// // Copyright (C) 2013-2015 mogemimi. // Distributed under the MIT License. See LICENSE.md or // http://enginetrouble.net/pomdog/license for details. // #ifndef POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP #define POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP #if (_MSC_VER > 1000) #pragma once #endif namespace Pomdog { namespace Details { //---------------------------- // Choose compiler //---------------------------- #if defined(_MSC_VER) # define POMDOG_COMPILER_MSVC //# define POMDOG_COMPILER_VERSION _MSC_VER #elif defined(__clang__) # define POMDOG_COMPILER_CLANG //# define POMDOG_COMPILER_VERSION ((__clang_major__*100) + (__clang_minor__*10) + __clang_patchlevel__) #elif defined(__GNUC__) # define POMDOG_COMPILER_GNUC //# define POMDOG_COMPILER_VERSION ((__GNUC__*100) + (__GNUC_MINOR__*10) + __GNUC_PATCHLEVEL__) #elid defined(__BORLANDC__) && defined(__BCPLUSPLUS__) # define POMDOG_COMPILER_BORLAND //# define POMDOG_COMPILER_VERSION (__BCPLUSPLUS__) #else # error "Compiler undefined or not supported." #endif //---------------------------- // Choose platform //---------------------------- #if defined(linux) || defined(__linux) || defined(__linux__) # // Linux # define POMDOG_PLATFORM_LINUX #elif defined(__PS4__) && defined(__FreeBSD__) # // PlayStation 4 # define POMDOG_PLATFORM_PlayStation4 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) # // BSD # define POMDOG_PLATFORM_BSD #elif defined(_XBOX_ONE) && defined(_TITLE) # // Xbox One # define POMDOG_PLATFORM_XBOX_ONE #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) # // Windows # define POMDOG_PLATFORM_WIN32 #elif defined(ANDROID) || defined(__ANDROID__) # // Android OS # define POMDOG_PLATFORM_ANDROID #elif (defined(__APPLE_CC__) && ((__IPHONE_OS_VERSION_MIN_REQUIRED >= 70000)) \ || (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 70000)) # // Apple iOS 7 or later # define POMDOG_PLATFORM_APPLE_IOS #elif defined(__APPLE_CC__) # // Mac OSX # define POMDOG_PLATFORM_MACOSX #elif defined(__QNXNTO__) # // QNX Neutrino # define POMDOG_PLATFORM_QNXNTO #elif defined(__native_client__) # // Google Native Client(NaCl) # define POMDOG_PLATFORM_NACL #elif defined(__CYGWIN__) # // Cygwin # define POMDOG_PLATFORM_CYGWIN #elif defined(sun) || defined(__sun) # // Solaris # define POMDOG_PLATFORM_SOLARIS #elif defined(__hpux) # // Hewlett-Packard UNIX # define POMDOG_PLATFORM_HPUX #else # error "Sorry, this platform is not supported." #endif //---------------------------- // Hardware Architecture //---------------------------- #if defined(_M_IX86) /* msvc */ \ || defined(_X86_) \ || defined(__i386__) /* gcc */ \ || defined(__i386) /* gcc */ \ || defined(i386) # // x86 processors # define POMDOG_ARCHITECTURE_IX86 #elif \ defined(_M_X64) /* msvc */ \ || defined(_AMD64_) \ || defined(__x86_64__) /* 64-bit linux */ # // x64 processors # define POMDOG_ARCHITECTURE_AMD64 #elif \ defined(_M_IA64) /* msvc */ \ || defined(__ia64__) \ || defined(__ia64) \ || defined(__IA64__) \ || defined(_IA64) \ || defined(ia64) # // Itanium architecture, 64-bit processors # define POMDOG_ARCHITECTURE_IA64 #elif \ defined(__arm__) /* gcc */ \ || defined(__arm) /* gcc */ \ || defined(_ARM_) /* c compiler */ \ || defined(ARM) \ || defined(__ARM__) \ || defined(_M_ARM) /* windows mobile 5 */ # // ARM architecture # define POMDOG_ARCHITECTURE_ARM #elif \ defined(_M_PPC) /* msvc */ \ || defined(__powerpc__) /* gcc */ \ || defined(__powerpc) \ || defined(__POWERPC__) \ || defined(__PPC) \ || defined(_ARCH_PPC) # ///@note __powerpc64__ # // PowerPC platforms # define POMDOG_ARCHITECTURE_POWERPC #elif \ defined(_POWER) \ || defined(_ARCH_PWR) \ || defined(_ARCH_COM) # // Power architecture # define POMDOG_ARCHITECTURE_POWER #elif \ defined(_M_MRX000) /* msvc */ \ || defined(__mips__) \ || defined(__mips) \ || defined(__MIPS__) # // MIPS platforms # define POMDOG_ARCHITECTURE_MIPS #elif \ defined(_M_ALPHA) /* msvc */ \ || defined(__alpha__) \ || defined(__alpha) # // DEC Alpha platforms # define POMDOG_ARCHITECTURE_ALPHA #endif //---------------------------- // Byte order //---------------------------- #if defined(POMDOG_ARCHITECTURE_IX86) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_ARCHITECTURE_AMD64) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_ARCHITECTURE_IA64) # if defined(_hpux) || defined(hpux) # // HP-UX is big-endian. # define POMDOG_BYTEORDER_BIG_ENDIAN # else # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_ARM) # if defined(__ARMEB__) # // 'EB' is big-endian # define POMDOG_BYTEORDER_BIG_ENDIAN # else //__ARMEL__ # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_POWERPC) # define POMDOG_BYTEORDER_BIG_ENDIAN #elif defined(POMDOG_ARCHITECTURE_POWER) # define POMDOG_BYTEORDER_BIG_ENDIAN #elif defined(POMDOG_ARCHITECTURE_MIPS) # if defined(MIPSEB) || defined(_MIPSEB) || defined(__MIPSEB) # define POMDOG_BYTEORDER_BIG_ENDIAN # else// MIPSEL, _MIPSEL, __MIPSEL # define POMDOG_BYTEORDER_LITTLE_ENDIAN # endif #elif defined(POMDOG_ARCHITECTURE_ALPHA) # define POMDOG_BYTEORDER_LITTLE_ENDIAN #elif defined(POMDOG_COMPILER_GNUC) # if (((__GNUC__*100) + (__GNUC_MINOR__*10) + __GNUC_PATCHLEVEL__) >= 310) # // include header <endian.h> in the global namespace. # if defined (__LITTLE_ENDIAN__) || (__BYTE_ORDER == __LITTLE_ENDIAN) # define POMDOG_BYTEORDER_LITTLE_ENDIAN # elif defined (__BIG_ENDIAN__) || (__BYTE_ORDER == __BIG_ENDIAN) # define POMDOG_BYTEORDER_BIG_ENDIAN # endif # endif #else # error "Byte order undefined or not supported." #endif #if (defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && !defined(POMDOG_BYTEORDER_BIG_ENDIAN) && !(POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #elif (!defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && defined(POMDOG_BYTEORDER_BIG_ENDIAN) && !(POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #elif (!defined(POMDOG_BYTEORDER_LITTLE_ENDIAN) && !defined(POMDOG_BYTEORDER_BIG_ENDIAN) && (POMDOG_BYTEORDER_MIDDLE_ENDIAN)) #else # error "Byte order undefined or not supported." #endif //---------------------------------- // C++11 support/not supported //---------------------------------- #ifndef __has_feature // Optional of course. # define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension # define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif #if defined(POMDOG_COMPILER_MSVC) \ && (_MSC_VER >= 1600) # // Support C++11 under MSVC #elif defined(POMDOG_COMPILER_CLANG) \ && __has_feature(cxx_lambdas) \ && __has_feature(cxx_nullptr) \ && __has_feature(cxx_static_assert) \ && __has_feature(cxx_strong_enums) \ && __has_feature(cxx_defaulted_functions) # // Support C++11 under Clang++ # // See also: # // http://clang.llvm.org/docs/LanguageExtensions.html#checking_upcoming_features #elif defined(POMDOG_COMPILER_GNUC) \ && defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus >= 201103L # // Support C++11 under GCC # // See also: # // http://gcc.gnu.org/projects/cxx0x.html #else # error "C++11/C++0x is not supported." #endif //---------------------------- // debug or release //---------------------------- #if defined(DEBUG) && defined(NDEBUG) # error "Both DEBUG and NDEBUG are defined." #endif }// namespace Details }// namespace Pomdog #endif // !defined(POMDOG_PLATFORM_C59B59BE_0311_4CB7_96D7_541924F8C06A_HPP)
Add PS4 platform
Add PS4 platform
C++
mit
mogemimi/pomdog,Mourtz/pomdog,mogemimi/pomdog,mogemimi/pomdog,bis83/pomdog,bis83/pomdog,Mourtz/pomdog
a8cd36d29ba6aef515ef0c05f63e8429b55e4428
src/thread_worker.cxx
src/thread_worker.cxx
/* * A thread that performs queued work. * * author: Max Kellermann <[email protected]> */ #include "thread_worker.hxx" #include "thread_queue.hxx" #include "thread_job.hxx" #include "ssl/ssl_init.hxx" static void * thread_worker_run(void *ctx) { /* reduce glibc's thread cancellation overhead */ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr); struct thread_worker &w = *(struct thread_worker *)ctx; ThreadQueue &q = *w.queue; ThreadJob *job; while ((job = thread_queue_wait(q)) != nullptr) { job->Run(); thread_queue_done(q, *job); } ssl_thread_deinit(); return nullptr; } bool thread_worker_create(struct thread_worker &w, ThreadQueue &q) { w.queue = &q; pthread_attr_t attr; pthread_attr_init(&attr); /* 64 kB stack ought to be enough */ pthread_attr_setstacksize(&attr, 65536); bool success = pthread_create(&w.thread, &attr, thread_worker_run, &w) == 0; pthread_attr_destroy(&attr); return success; }
/* * A thread that performs queued work. * * author: Max Kellermann <[email protected]> */ #include "thread_worker.hxx" #include "thread_queue.hxx" #include "thread_job.hxx" #include "ssl/ssl_init.hxx" #include "util/ScopeExit.hxx" static void * thread_worker_run(void *ctx) { /* reduce glibc's thread cancellation overhead */ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr); struct thread_worker &w = *(struct thread_worker *)ctx; ThreadQueue &q = *w.queue; ThreadJob *job; while ((job = thread_queue_wait(q)) != nullptr) { job->Run(); thread_queue_done(q, *job); } ssl_thread_deinit(); return nullptr; } bool thread_worker_create(struct thread_worker &w, ThreadQueue &q) { w.queue = &q; pthread_attr_t attr; pthread_attr_init(&attr); AtScopeExit(&attr) { pthread_attr_destroy(&attr); }; /* 64 kB stack ought to be enough */ pthread_attr_setstacksize(&attr, 65536); return pthread_create(&w.thread, &attr, thread_worker_run, &w) == 0; }
use AtScopeExit()
thread_worker: use AtScopeExit()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
1cdd2a9aecf560ce066bebfb2d5e839c441526d9
src/BabylonImGui/src/babylon_imgui/babylon_studio.cpp
src/BabylonImGui/src/babylon_imgui/babylon_studio.cpp
#include <babylon/GL/framebuffer_canvas.h> #include <babylon/babylon_imgui/babylon_logs_window.h> #include <babylon/babylon_imgui/babylon_studio.h> #include <babylon/core/filesystem.h> #include <babylon/core/system.h> #include <babylon/inspector/components/actiontabs/action_tabs_component.h> #include <babylon/interfaces/irenderable_scene_with_hud.h> #include <imgui.h> #include <imgui_internal.h> #include <imgui_runner_babylon/runner_babylon.h> #include <imgui_utils/icons_font_awesome_5.h> #include <babylon/babylon_imgui/babylon_studio_layout.h> #include <babylon/core/logging.h> #include <babylon/samples/samples_index.h> #ifdef _WIN32 #include <windows.h> #endif #include <iostream> namespace BABYLON { struct EmptyScene : public BABYLON::IRenderableScene { const char* getName() override { return "Empty Scene"; } void initializeScene(BABYLON::ICanvas*, BABYLON::Scene*) override { } }; class BabylonStudioApp { public: BabylonStudioApp() { std::string exePath = BABYLON::System::getExecutablePath(); std::string exeFolder = BABYLON::Filesystem::baseDir(exePath); std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp"; playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath); _playgroundCodeEditor.setFiles({playgroundPath}); _playgroundCodeEditor.setLightPalette(); } void RunApp(const std::shared_ptr<BABYLON::IRenderableScene>& initialScene, const BabylonStudioOptions& options) { _appContext._options = options; _appContext._options._appWindowParams.ShowMenuBar = true; auto showGuiLambda = [this]() -> bool { std::cout << "showGuiLambda 1 \n"; bool r = this->render(); std::cout << "showGuiLambda 2 \n"; for (auto f : _appContext._options._heartbeatCallbacks) f(); std::cout << "showGuiLambda 2 \n"; if (_appContext._options._playgroundCompilerCallback) { PlaygroundCompilerStatus playgroundCompilerStatus = _appContext._options._playgroundCompilerCallback(); if (playgroundCompilerStatus._renderableScene) setRenderableScene(playgroundCompilerStatus._renderableScene); _appContext._isCompiling = playgroundCompilerStatus._isCompiling; } std::cout << "showGuiLambda 3 \n"; return r; }; auto initSceneLambda = [=]() { std::cout << "initSceneLambda 1 \n"; this->initScene(); std::cout << "initSceneLambda 2 \n"; this->setRenderableScene(initialScene); std::cout << "initSceneLambda 3 \n"; }; _appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) { _studioLayout.PrepareLayout(mainDockId); }; ImGuiUtils::ImGuiRunner::InvokeRunnerBabylon( _appContext._options._appWindowParams, showGuiLambda, initSceneLambda ); } private: void registerRenderFunctions() { static bool registered = false; if (registered) return; // clang-format off _studioLayout.registerGuiRenderFunction( DockableWindowId::Inspector, [this]() { if (_appContext._inspector) _appContext._inspector->render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::Logs, []() { BABYLON::BabylonLogsWindow::instance().render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::Scene3d, [this]() { render3d(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::SamplesCodeViewer, [this]() { _samplesCodeEditor.render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::SampleBrowser, [this]() { _appContext._sampleListComponent.render(); }); #ifdef BABYLON_BUILD_PLAYGROUND _studioLayout.registerGuiRenderFunction( DockableWindowId::PlaygroundEditor, [this]() { renderPlayground(); }); #endif // clang-format on registered = true; } void initScene() { std::cout << "initScene 1 \n"; _appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) { this->setRenderableScene(scene); _studioLayout.FocusWindow(DockableWindowId::Scene3d); }; std::cout << "initScene 2 \n"; _appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) { _samplesCodeEditor.setFiles(files); _studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true); _studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer); }; std::cout << "initScene 3 \n"; _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) { _appContext._loopSamples.flagLoop = true; _appContext._loopSamples.samplesToLoop = samples; _appContext._loopSamples.currentIdx = 0; }; std::cout << "initScene 4 \n"; _appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f)); std::cout << "initScene 5 \n"; _appContext._sceneWidget->OnBeforeResize.push_back( [this]() { _appContext._inspector.release(); }); std::cout << "initScene 6 \n"; } void prepareSceneInspector() { auto currentScene = _appContext._sceneWidget->getScene(); if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) { _appContext._inspector = std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene()); _appContext._inspector->setScene(currentScene); } } // returns true if exit required bool renderMenu() { ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar; bool shallExit = false; if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Quit")) shallExit = true; if (ImGui::MenuItem("Save Screenshot")) saveScreenshot(); ImGui::EndMenu(); } _studioLayout.renderMenu(); renderStatus(); ImGui::EndMenuBar(); } return shallExit; } void renderStatus() { ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f }; if (_studioLayout.isVisible(DockableWindowId::Scene3d)) { ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f); std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName(); ImGui::TextColored(statusTextColor, "%s", sceneName.c_str()); } ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f); ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate); } // renders the GUI. Returns true when exit required bool render() { static bool wasInitialLayoutApplied = false; if (!wasInitialLayoutApplied) { this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser); wasInitialLayoutApplied = true; } prepareSceneInspector(); registerRenderFunctions(); bool shallExit = renderMenu(); _studioLayout.renderGui(); handleLoopSamples(); if (_appContext._options._flagScreenshotOneSampleAndExit) return saveScreenshotAfterFewFrames(); else return shallExit; } void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene) { if (_appContext._inspector) _appContext._inspector->setScene(nullptr); _appContext._sceneWidget->setRenderableScene(scene); if (_appContext._inspector) _appContext._inspector->setScene(_appContext._sceneWidget->getScene()); } void saveScreenshot(std::string filename = "") { if (filename.empty()) filename = std::string(_appContext._sceneWidget->getRenderableScene()->getName()) + ".jpg"; int imageWidth = 200; int jpgQuality = 75; this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg( filename.c_str(), jpgQuality, imageWidth); } // Saves a screenshot after few frames (returns true when done) [[nodiscard]] bool saveScreenshotAfterFewFrames() { _appContext._frameCounter++; if (_appContext._frameCounter < 30) return false; saveScreenshot(_appContext._options._sceneName + ".jpg"); return true; } bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size) { ImGui::SetNextWindowPos(position); ImGui::SetNextWindowSize(size); ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground; std::string id = label + "##ButtonInOverlayWindow"; ImGui::Begin(label.c_str(), nullptr, flags); bool clicked = ImGui::Button(label.c_str()); ImGui::End(); return clicked; } void renderHud(ImVec2 cursorScene3dTopLeft) { auto asSceneWithHud = dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene()); if (!asSceneWithHud) return; if (!asSceneWithHud->hudGui) return; static bool showHud = false; ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f); ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f); if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f))) showHud = !showHud; if (showHud) { ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once); ImGui::SetNextWindowBgAlpha(0.5f); ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("HUD", &showHud, flags); asSceneWithHud->hudGui(); ImGui::End(); } } void render3d() { ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size; sceneSize.y -= 35.f; sceneSize.x = (float)((int)((sceneSize.x) / 4) * 4); ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos(); _appContext._sceneWidget->render(sceneSize); renderHud(cursorPosBeforeScene3d); } void renderPlayground() { ImGui::Button(ICON_FA_QUESTION_CIRCLE); if (ImGui::IsItemHovered()) ImGui::SetTooltip( "Playground : you can edit the code below! As soon as you save it, the code will be " "compiled and the 3D scene " "will be updated"); ImGui::SameLine(); if (_appContext._isCompiling) { ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling"); _studioLayout.setVisible(DockableWindowId::Logs, true); } if (ImGui::Button(ICON_FA_PLAY " Run")) _playgroundCodeEditor.saveAll(); ImGui::SameLine(); _playgroundCodeEditor.render(); } private: void handleLoopSamples() { if (!_appContext._loopSamples.flagLoop) return; static int frame_counter = 0; const int max_frames = 60; if (frame_counter > max_frames) { std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx]; BABYLON_LOG_ERROR("LoopSample", sampleName) auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr); this->setRenderableScene(scene); if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2) _appContext._loopSamples.currentIdx++; else _appContext._loopSamples.flagLoop = false; frame_counter = 0; } else frame_counter++; } // // BabylonStudioContext // struct AppContext { std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget; std::unique_ptr<BABYLON::Inspector> _inspector; BABYLON::SamplesBrowser _sampleListComponent; int _frameCounter = 0; BabylonStudioOptions _options; bool _isCompiling = false; struct { bool flagLoop = false; size_t currentIdx = 0; std::vector<std::string> samplesToLoop; } _loopSamples; }; AppContext _appContext; BabylonStudioLayout _studioLayout; ImGuiUtils::CodeEditor _samplesCodeEditor = ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly ImGuiUtils::CodeEditor _playgroundCodeEditor; }; // end of class BabylonInspectorApp // public API void runBabylonStudio(const std::shared_ptr<BABYLON::IRenderableScene>& scene, BabylonStudioOptions options /* = SceneWithInspectorOptions() */ ) { BABYLON::BabylonStudioApp app; std::shared_ptr<BABYLON::IRenderableScene> sceneNotNull = scene ? scene : std::make_shared<EmptyScene>(); app.RunApp(sceneNotNull, options); } } // namespace BABYLON
#include <babylon/GL/framebuffer_canvas.h> #include <babylon/babylon_imgui/babylon_logs_window.h> #include <babylon/babylon_imgui/babylon_studio.h> #include <babylon/cameras/free_camera.h> #include <babylon/core/filesystem.h> #include <babylon/core/system.h> #include <babylon/inspector/components/actiontabs/action_tabs_component.h> #include <babylon/interfaces/irenderable_scene_with_hud.h> #include <imgui.h> #include <imgui_internal.h> #include <imgui_runner_babylon/runner_babylon.h> #include <imgui_utils/icons_font_awesome_5.h> #include <babylon/babylon_imgui/babylon_studio_layout.h> #include <babylon/core/logging.h> #ifdef _WIN32 #include <windows.h> #endif #include <iostream> namespace BABYLON { struct EmptyScene : public BABYLON::IRenderableScene { const char* getName() override { return "Empty Scene"; } void initializeScene(BABYLON::ICanvas*, BABYLON::Scene* scene) override { auto camera = BABYLON::FreeCamera::New("camera1", Vector3(0.f, 0.f, 0.f), scene); } }; class BabylonStudioApp { public: BabylonStudioApp() { std::string exePath = BABYLON::System::getExecutablePath(); std::string exeFolder = BABYLON::Filesystem::baseDir(exePath); std::string playgroundPath = exeFolder + "/../../../src/BabylonStudio/playground.cpp"; playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath); _playgroundCodeEditor.setFiles({playgroundPath}); _playgroundCodeEditor.setLightPalette(); } void RunApp(const std::shared_ptr<BABYLON::IRenderableScene>& initialScene, const BabylonStudioOptions& options) { _appContext._options = options; _appContext._options._appWindowParams.ShowMenuBar = true; auto showGuiLambda = [this]() -> bool { std::cout << "showGuiLambda 1 \n"; bool r = this->render(); std::cout << "showGuiLambda 2 \n"; for (auto f : _appContext._options._heartbeatCallbacks) f(); std::cout << "showGuiLambda 2 \n"; if (_appContext._options._playgroundCompilerCallback) { PlaygroundCompilerStatus playgroundCompilerStatus = _appContext._options._playgroundCompilerCallback(); if (playgroundCompilerStatus._renderableScene) setRenderableScene(playgroundCompilerStatus._renderableScene); _appContext._isCompiling = playgroundCompilerStatus._isCompiling; } std::cout << "showGuiLambda 3 \n"; return r; }; auto initSceneLambda = [=]() { std::cout << "initSceneLambda 1 \n"; this->initScene(); std::cout << "initSceneLambda 2 \n"; this->setRenderableScene(initialScene); std::cout << "initSceneLambda 3 \n"; }; _appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) { _studioLayout.PrepareLayout(mainDockId); }; ImGuiUtils::ImGuiRunner::InvokeRunnerBabylon( _appContext._options._appWindowParams, showGuiLambda, initSceneLambda ); } private: void registerRenderFunctions() { static bool registered = false; if (registered) return; // clang-format off _studioLayout.registerGuiRenderFunction( DockableWindowId::Inspector, [this]() { if (_appContext._inspector) _appContext._inspector->render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::Logs, []() { BABYLON::BabylonLogsWindow::instance().render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::Scene3d, [this]() { render3d(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::SamplesCodeViewer, [this]() { _samplesCodeEditor.render(); }); _studioLayout.registerGuiRenderFunction( DockableWindowId::SampleBrowser, [this]() { _appContext._sampleListComponent.render(); }); #ifdef BABYLON_BUILD_PLAYGROUND _studioLayout.registerGuiRenderFunction( DockableWindowId::PlaygroundEditor, [this]() { renderPlayground(); }); #endif // clang-format on registered = true; } void initScene() { std::cout << "initScene 1 \n"; _appContext._sampleListComponent.OnNewRenderableScene = [&](std::shared_ptr<IRenderableScene> scene) { this->setRenderableScene(scene); _studioLayout.FocusWindow(DockableWindowId::Scene3d); }; std::cout << "initScene 2 \n"; _appContext._sampleListComponent.OnEditFiles = [&](const std::vector<std::string>& files) { _samplesCodeEditor.setFiles(files); _studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true); _studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer); }; std::cout << "initScene 3 \n"; _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector<std::string>& samples) { _appContext._loopSamples.flagLoop = true; _appContext._loopSamples.samplesToLoop = samples; _appContext._loopSamples.currentIdx = 0; }; std::cout << "initScene 4 \n"; _appContext._sceneWidget = std::make_unique<BABYLON::ImGuiSceneWidget>(ImVec2(640.f, 480.f)); std::cout << "initScene 5 \n"; _appContext._sceneWidget->OnBeforeResize.push_back( [this]() { _appContext._inspector.release(); }); std::cout << "initScene 6 \n"; } void prepareSceneInspector() { auto currentScene = _appContext._sceneWidget->getScene(); if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) { _appContext._inspector = std::make_unique<BABYLON::Inspector>(nullptr, _appContext._sceneWidget->getScene()); _appContext._inspector->setScene(currentScene); } } // returns true if exit required bool renderMenu() { ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar; bool shallExit = false; if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Quit")) shallExit = true; if (ImGui::MenuItem("Save Screenshot")) saveScreenshot(); ImGui::EndMenu(); } _studioLayout.renderMenu(); renderStatus(); ImGui::EndMenuBar(); } return shallExit; } void renderStatus() { ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f }; if (_studioLayout.isVisible(DockableWindowId::Scene3d)) { ImGui::SameLine(ImGui::GetIO().DisplaySize.x / 2.f); std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName(); ImGui::TextColored(statusTextColor, "%s", sceneName.c_str()); } ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f); ImGui::TextColored(statusTextColor, "FPS: %.1f", ImGui::GetIO().Framerate); } // renders the GUI. Returns true when exit required bool render() { static bool wasInitialLayoutApplied = false; if (!wasInitialLayoutApplied) { this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser); wasInitialLayoutApplied = true; } prepareSceneInspector(); registerRenderFunctions(); bool shallExit = renderMenu(); _studioLayout.renderGui(); handleLoopSamples(); if (_appContext._options._flagScreenshotOneSampleAndExit) return saveScreenshotAfterFewFrames(); else return shallExit; } void setRenderableScene(std::shared_ptr<BABYLON::IRenderableScene> scene) { if (_appContext._inspector) _appContext._inspector->setScene(nullptr); _appContext._sceneWidget->setRenderableScene(scene); if (_appContext._inspector) _appContext._inspector->setScene(_appContext._sceneWidget->getScene()); } void saveScreenshot(std::string filename = "") { if (filename.empty()) filename = std::string(_appContext._sceneWidget->getRenderableScene()->getName()) + ".jpg"; int imageWidth = 200; int jpgQuality = 75; this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg( filename.c_str(), jpgQuality, imageWidth); } // Saves a screenshot after few frames (returns true when done) [[nodiscard]] bool saveScreenshotAfterFewFrames() { _appContext._frameCounter++; if (_appContext._frameCounter < 30) return false; saveScreenshot(_appContext._options._sceneName + ".jpg"); return true; } bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size) { ImGui::SetNextWindowPos(position); ImGui::SetNextWindowSize(size); ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground; std::string id = label + "##ButtonInOverlayWindow"; ImGui::Begin(label.c_str(), nullptr, flags); bool clicked = ImGui::Button(label.c_str()); ImGui::End(); return clicked; } void renderHud(ImVec2 cursorScene3dTopLeft) { auto asSceneWithHud = dynamic_cast<IRenderableSceneWithHud*>(_appContext._sceneWidget->getRenderableScene()); if (!asSceneWithHud) return; if (!asSceneWithHud->hudGui) return; static bool showHud = false; ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f); ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f); if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f))) showHud = !showHud; if (showHud) { ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once); ImGui::SetNextWindowBgAlpha(0.5f); ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("HUD", &showHud, flags); asSceneWithHud->hudGui(); ImGui::End(); } } void render3d() { ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size; sceneSize.y -= 35.f; sceneSize.x = (float)((int)((sceneSize.x) / 4) * 4); ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos(); _appContext._sceneWidget->render(sceneSize); renderHud(cursorPosBeforeScene3d); } void renderPlayground() { ImGui::Button(ICON_FA_QUESTION_CIRCLE); if (ImGui::IsItemHovered()) ImGui::SetTooltip( "Playground : you can edit the code below! As soon as you save it, the code will be " "compiled and the 3D scene " "will be updated"); ImGui::SameLine(); if (_appContext._isCompiling) { ImGui::TextColored(ImVec4(1., 0., 0., 1.), "Compiling"); _studioLayout.setVisible(DockableWindowId::Logs, true); } if (ImGui::Button(ICON_FA_PLAY " Run")) _playgroundCodeEditor.saveAll(); ImGui::SameLine(); _playgroundCodeEditor.render(); } private: void handleLoopSamples() { if (!_appContext._loopSamples.flagLoop) return; static int frame_counter = 0; const int max_frames = 60; if (frame_counter > max_frames) { std::string sampleName = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx]; BABYLON_LOG_ERROR("LoopSample", sampleName) auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr); this->setRenderableScene(scene); if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2) _appContext._loopSamples.currentIdx++; else _appContext._loopSamples.flagLoop = false; frame_counter = 0; } else frame_counter++; } // // BabylonStudioContext // struct AppContext { std::unique_ptr<BABYLON::ImGuiSceneWidget> _sceneWidget; std::unique_ptr<BABYLON::Inspector> _inspector; BABYLON::SamplesBrowser _sampleListComponent; int _frameCounter = 0; BabylonStudioOptions _options; bool _isCompiling = false; struct { bool flagLoop = false; size_t currentIdx = 0; std::vector<std::string> samplesToLoop; } _loopSamples; }; AppContext _appContext; BabylonStudioLayout _studioLayout; ImGuiUtils::CodeEditor _samplesCodeEditor = ImGuiUtils::CodeEditor(true); // true <-> showCheckboxReadOnly ImGuiUtils::CodeEditor _playgroundCodeEditor; }; // end of class BabylonInspectorApp // public API void runBabylonStudio(const std::shared_ptr<BABYLON::IRenderableScene>& scene, BabylonStudioOptions options /* = SceneWithInspectorOptions() */ ) { BABYLON::BabylonStudioApp app; std::shared_ptr<BABYLON::IRenderableScene> sceneNotNull = scene ? scene : std::make_shared<EmptyScene>(); app.RunApp(sceneNotNull, options); } } // namespace BABYLON
add camera to EmptyScene
babylon_studio: add camera to EmptyScene
C++
apache-2.0
samdauwe/BabylonCpp,samdauwe/BabylonCpp,samdauwe/BabylonCpp,samdauwe/BabylonCpp
3a98e89b4433b4edef2d338840e995fd3564560e
include/d2/detail/basic_mutex.hpp
include/d2/detail/basic_mutex.hpp
/** * This file defines several utilities used in the rest of the library. */ #ifndef D2_DETAIL_BASIC_MUTEX_HPP #define D2_DETAIL_BASIC_MUTEX_HPP #include <boost/assert.hpp> #include <boost/noncopyable.hpp> #include <boost/thread/detail/platform.hpp> #if defined(BOOST_THREAD_PLATFORM_PTHREAD) # include <cerrno> // for EINTR # include <pthread.h> #endif namespace d2 { namespace detail { /** * Basic mutex class not relying on anything that might be using this library, * which would create a circular dependency. */ class basic_mutex : public boost::noncopyable { #if defined(BOOST_THREAD_PLATFORM_PTHREAD) private: pthread_mutex_t mutex_; public: inline basic_mutex() { int res = pthread_mutex_init(&mutex_, NULL); (void)res; BOOST_ASSERT(!res); } inline void lock() { int res; do res = pthread_mutex_lock(&mutex_); while (res == EINTR); BOOST_ASSERT(!res); } inline void unlock() { int res; do res = pthread_mutex_unlock(&mutex_); while (res == EINTR); BOOST_ASSERT(!res); } inline ~basic_mutex() { int res; do res = pthread_mutex_destroy(&mutex_); while (res == EINTR); } #elif defined(BOOST_THREAD_PLATFORM_WIN32) #error "Win32 not supported right now." #endif }; } // end namespace detail } // end namespace d2 #endif // !D2_DETAIL_BASIC_MUTEX_HPP
/** * This file defines several utilities used in the rest of the library. * Note: This file contains parts from Boost that were cherry picked and * modified a bit in some cases. Because of this, this file is * distributed under the same license as the original files. * * (C) Copyright 2006-8 Anthony Williams * (C) Copyright 2011-2012 Vicente J. Botet Escriba * (C) Copyright 2012 Louis Dionne * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef D2_DETAIL_BASIC_MUTEX_HPP #define D2_DETAIL_BASIC_MUTEX_HPP #include <boost/assert.hpp> #include <boost/config.hpp> // for BOOST_STATIC_CONSTANT #include <boost/noncopyable.hpp> #include <cstddef> #include <boost/thread/detail/platform.hpp> #if defined(BOOST_THREAD_PLATFORM_PTHREAD) # include <cerrno> // for EINTR # include <pthread.h> #elif defined(BOOST_THREAD_PLATFORM_WIN32) # include <boost/detail/interlocked.hpp> # include <boost/thread/win32/interlocked_read.hpp> # include <boost/thread/win32/thread_primitives.hpp> #endif namespace d2 { namespace detail { /** * Basic mutex class not relying on anything that might be using this library, * which would create a circular dependency. */ class basic_mutex : public boost::noncopyable { #if defined(BOOST_THREAD_PLATFORM_PTHREAD) private: pthread_mutex_t mutex_; public: inline basic_mutex() { int res = pthread_mutex_init(&mutex_, NULL); (void)res; BOOST_ASSERT(!res); } inline void lock() { int res; do res = pthread_mutex_lock(&mutex_); while (res == EINTR); BOOST_ASSERT(!res); } inline void unlock() { int res; do res = pthread_mutex_unlock(&mutex_); while (res == EINTR); BOOST_ASSERT(!res); } inline ~basic_mutex() { int res; do res = pthread_mutex_destroy(&mutex_); while (res == EINTR); } #elif defined(BOOST_THREAD_PLATFORM_WIN32) private: BOOST_STATIC_CONSTANT(unsigned char, lock_flag_bit = 31); BOOST_STATIC_CONSTANT(unsigned char, event_set_flag_bit = 30); BOOST_STATIC_CONSTANT(long, lock_flag_value = 1 << lock_flag_bit); BOOST_STATIC_CONSTANT(long, event_set_flag_value = 1<<event_set_flag_bit); long active_count_; void* event_; void* get_event() { void* const current_event = boost::detail::interlocked_read_acquire(&event_); if(current_event == NULL) { void* const new_event = boost::detail::win32::create_anonymous_event( ::boost::detail::win32::auto_reset_event, ::boost::detail::win32::event_initially_reset); #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4311 4312) #endif void* const old_event = BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(&event_, new_event, 0); #ifdef BOOST_MSVC #pragma warning(pop) #endif if(old_event != NULL) { boost::detail::win32::CloseHandle(new_event); return old_event; } else { return new_event; } } return current_event; } inline void mark_waiting_and_try_lock(long& old_count) { while (true) { long const new_count = (old_count & lock_flag_value) ? (old_count + 1) : (old_count | lock_flag_value); long const current = BOOST_INTERLOCKED_COMPARE_EXCHANGE( &active_count_, new_count, old_count); if(current == old_count) break; old_count = current; } } inline void clear_waiting_and_try_lock(long& old_count) { old_count &= ~lock_flag_value; old_count |= event_set_flag_value; while (true) { long const new_count = ( (old_count & lock_flag_value) ? old_count : ((old_count - 1) | lock_flag_value) ) & ~event_set_flag_value; long const current = BOOST_INTERLOCKED_COMPARE_EXCHANGE( &active_count_, new_count, old_count); if(current == old_count) break; old_count = current; } } inline bool try_lock() BOOST_NOEXCEPT { return !boost::detail::win32::interlocked_bit_test_and_set( &active_count_, lock_flag_bit); } public: inline basic_mutex() : active_count_(0), event_(0) { } inline ~basic_mutex() { void* old_event = BOOST_INTERLOCKED_EXCHANGE_POINTER(&event_, NULL); if(old_event) boost::detail::win32::CloseHandle(old_event); } inline void lock() { if(try_lock()) return; long old_count = active_count_; mark_waiting_and_try_lock(old_count); if(old_count & lock_flag_value) { bool lock_acquired = false; void* const sem = get_event(); do { BOOST_VERIFY(boost::detail::win32::WaitForSingleObject( sem, ::boost::detail::win32::infinite) == 0); clear_waiting_and_try_lock(old_count); lock_acquired = !(old_count & lock_flag_value); } while(!lock_acquired); } } inline void unlock() { long const offset = lock_flag_value; long const old_count = BOOST_INTERLOCKED_EXCHANGE_ADD( &active_count_, lock_flag_value); if(!(old_count & event_set_flag_value) && old_count > offset && !boost::detail::win32::interlocked_bit_test_and_set( &active_count_, event_set_flag_bit)) { boost::detail::win32::SetEvent(get_event()); } } #endif // BOOST_THREAD_PLATFORM_{PTHREAD, WIN32} }; } // end namespace detail } // end namespace d2 #endif // !D2_DETAIL_BASIC_MUTEX_HPP
Add support for Win32 in the basic_mutex class.
Add support for Win32 in the basic_mutex class.
C++
mit
ldionne/d2
c2f5c85eccb68f215f10c12b6a6822935db9d51d
include/dll/standard_conv_rbm.hpp
include/dll/standard_conv_rbm.hpp
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::fast_conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); PARALLEL_SECTION { h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); } maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; tmp_result(batch) = h_s_padded(batch) >> w_padded(channel); tmp_result(batch).ifft2_many_inplace(); for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(1) += etl::real(tmp_result(batch)(k)); } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::fast_conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); PARALLEL_SECTION { h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); } maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; tmp_result(batch) = h_s_padded(batch) >> w_padded(channel); tmp_result(batch).ifft2_many_inplace(); for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(1) += etl::real(tmp_result(batch)(k)); } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV1; ++i) { for (size_t j = 0; j < parent_t::NV2; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif
Disable FFT full convolution for now
Disable FFT full convolution for now This is slower than AVX convolution on small kernels
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
144870319dd024d991ce25e8905734cb86e26aa7
include/primesieve/pod_vector.hpp
include/primesieve/pod_vector.hpp
/// /// @file pod_vector.hpp /// /// Copyright (C) 2022 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POD_VECTOR_HPP #define POD_VECTOR_HPP #include "macros.hpp" #include <algorithm> #include <cstddef> #include <memory> #include <stdint.h> #include <type_traits> #include <utility> namespace primesieve { /// pod_vector is a dynamically growing array. /// It has the same API (though not complete) as std::vector but its /// resize() method does not default initialize memory for built-in /// integer types. It does however default initialize classes and /// struct types if they have a constructor. It also prevents /// bounds checks which is important for primesieve's performance, e.g. /// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS /// which enables std::vector bounds checks. /// template <typename T, typename Allocator = std::allocator<T>> class pod_vector { public: // The default C++ std::allocator is stateless. We use this // allocator and do not support other statefull allocators, // which simplifies our implementation. // // "The default allocator is stateless, that is, all instances // of the given allocator are interchangeable, compare equal // and can deallocate memory allocated by any other instance // of the same allocator type." // https://en.cppreference.com/w/cpp/memory/allocator // // "The member type is_always_equal of std::allocator_traits // is intendedly used for determining whether an allocator // type is stateless." // https://en.cppreference.com/w/cpp/named_req/Allocator static_assert(std::allocator_traits<Allocator>::is_always_equal::value, "pod_vector<T> only supports stateless allocators!"); using value_type = T; pod_vector() noexcept = default; pod_vector(std::size_t size) { resize(size); } ~pod_vector() { destroy(array_, end_); Allocator().deallocate(array_, capacity()); } /// Free all memory, the pod_vector /// can be reused afterwards. void deallocate() noexcept { this->~pod_vector<T>(); array_ = nullptr; end_ = nullptr; capacity_ = nullptr; } /// Reset the pod_vector, but do not free its /// memory. Same as std::vector.clear(). void clear() noexcept { destroy(array_, end_); end_ = array_; } /// Copying is slow, we prevent it pod_vector(const pod_vector&) = delete; pod_vector& operator=(const pod_vector&) = delete; /// Move constructor pod_vector(pod_vector&& other) noexcept { swap(other); } /// Move assignment operator pod_vector& operator=(pod_vector&& other) noexcept { if (this != &other) swap(other); return *this; } /// Better assembly than: std::swap(vect1, vect2) void swap(pod_vector& other) noexcept { T* tmp_array = array_; T* tmp_end = end_; T* tmp_capacity = capacity_; array_ = other.array_; end_ = other.end_; capacity_ = other.capacity_; other.array_ = tmp_array; other.end_ = tmp_end; other.capacity_ = tmp_capacity; } bool empty() const noexcept { return array_ == end_; } T& operator[](std::size_t pos) noexcept { ASSERT(pos < size()); return array_[pos]; } const T& operator[](std::size_t pos) const noexcept { ASSERT(pos < size()); return array_[pos]; } T* data() noexcept { return array_; } const T* data() const noexcept { return array_; } std::size_t size() const noexcept { ASSERT(end_ >= array_); return (std::size_t)(end_ - array_); } std::size_t capacity() const noexcept { ASSERT(capacity_ >= array_); return (std::size_t)(capacity_ - array_); } T* begin() noexcept { return array_; } const T* begin() const noexcept { return array_; } T* end() noexcept { return end_; } const T* end() const noexcept { return end_; } T& front() noexcept { ASSERT(!empty()); return *array_; } const T& front() const noexcept { ASSERT(!empty()); return *array_; } T& back() noexcept { ASSERT(!empty()); return *(end_ - 1); } const T& back() const noexcept { ASSERT(!empty()); return *(end_ - 1); } ALWAYS_INLINE void push_back(const T& value) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Placement new new(end_) T(value); end_++; } ALWAYS_INLINE void push_back(T&& value) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Without std::move() the copy constructor will // be called instead of the move constructor. new(end_) T(std::move(value)); end_++; } template <class... Args> ALWAYS_INLINE void emplace_back(Args&&... args) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Placement new new(end_) T(std::forward<Args>(args)...); end_++; } template <class InputIt> void insert(T* const pos, InputIt first, InputIt last) { static_assert(std::is_trivially_copyable<T>::value, "pod_vector<T>::insert() supports only trivially copyable types!"); // We only support appending to the vector ASSERT(pos == end_); (void) pos; if (first < last) { std::size_t new_size = size() + (std::size_t) (last - first); reserve(new_size); std::uninitialized_copy(first, last, end_); end_ = array_ + new_size; } } void reserve(std::size_t n) { if (n > capacity()) reserve_unchecked(n); } void resize(std::size_t n) { if (n > size()) { if (n > capacity()) reserve_unchecked(n); // This default initializes memory of classes and structs // with constructors (and with in-class initialization of // non-static members). But it does not default initialize // memory for POD types like int, long. if (!std::is_trivial<T>::value) uninitialized_default_construct(end_, array_ + n); end_ = array_ + n; } else if (n < size()) { destroy(array_ + n, end_); end_ = array_ + n; } } private: T* array_ = nullptr; T* end_ = nullptr; T* capacity_ = nullptr; void reserve_unchecked(std::size_t n) { ASSERT(n > capacity()); std::size_t old_size = size(); std::size_t old_capacity = capacity(); // GCC & Clang's std::vector grow the capacity by at least // 2x for every call to resize() with n > capacity(). We // grow by at least 1.5x as we tend to accurately calculate // the amount of memory we need upfront. std::size_t new_capacity = (old_capacity * 3) / 2; new_capacity = std::max(new_capacity, n); ASSERT(new_capacity > old_size); T* old = array_; array_ = Allocator().allocate(new_capacity); end_ = array_ + old_size; capacity_ = array_ + new_capacity; // Both primesieve & primecount require that byte arrays are // aligned to at least a alignof(uint64_t) boundary. This is // needed because our code casts byte arrays into uint64_t arrays // in some places in order to improve performance. The default // allocator guarantees that each memory allocation is at least // aligned to the largest built-in type (usually 16 or 32). ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0); if (old) { static_assert(std::is_nothrow_move_constructible<T>::value, "pod_vector<T> only supports nothrow moveable types!"); uninitialized_move_n(old, old_size, array_); Allocator().deallocate(old, old_capacity); } } template <typename U> ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type uninitialized_move_n(U* __restrict first, std::size_t count, U* __restrict d_first) { // We can use memcpy to move trivially copyable types. // https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class // https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy std::uninitialized_copy_n(first, count, d_first); } /// Same as std::uninitialized_move_n() from C++17. /// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n /// /// Unlike std::uninitialized_move_n() our implementation uses /// __restrict pointers which improves the generated assembly /// (using GCC & Clang). We can do this because we only use this /// method for non-overlapping arrays. template <typename U> ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type uninitialized_move_n(U* __restrict first, std::size_t count, U* __restrict d_first) { for (std::size_t i = 0; i < count; i++) new (d_first++) T(std::move(*first++)); } /// Same as std::uninitialized_default_construct() from C++17. /// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last) { // Default initialize array using placement new. // Note that `new (first) T();` zero initializes built-in integer types, // whereas `new (first) T;` does not initialize built-in integer types. for (; first != last; first++) new (first) T; } /// Same as std::destroy() from C++17. /// https://en.cppreference.com/w/cpp/memory/destroy ALWAYS_INLINE void destroy(T* first, T* last) { if (!std::is_trivially_destructible<T>::value) { // Theoretically deallocating in reverse order is more // cache efficient. Clang's std::vector implementation // also deallocates in reverse order. while (first != last) (--last)->~T(); } } }; template <typename T, std::size_t N> class pod_array { public: using value_type = T; T array_[N]; T& operator[](std::size_t pos) noexcept { ASSERT(pos < size()); return array_[pos]; } const T& operator[](std::size_t pos) const noexcept { ASSERT(pos < size()); return array_[pos]; } void fill(const T& value) { std::fill_n(begin(), size(), value); } T* data() noexcept { return array_; } const T* data() const noexcept { return array_; } T* begin() noexcept { return array_; } const T* begin() const noexcept { return array_; } T* end() noexcept { return array_ + N; } const T* end() const noexcept { return array_ + N; } T& back() noexcept { ASSERT(N > 0); return array_[N - 1]; } const T& back() const noexcept { ASSERT(N > 0); return array_[N - 1]; } constexpr std::size_t size() const noexcept { return N; } }; } // namespace #endif
/// /// @file pod_vector.hpp /// /// Copyright (C) 2022 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POD_VECTOR_HPP #define POD_VECTOR_HPP #include "macros.hpp" #include <algorithm> #include <cstddef> #include <memory> #include <stdint.h> #include <type_traits> #include <utility> namespace primesieve { /// pod_vector is a dynamically growing array. /// It has the same API (though not complete) as std::vector but its /// resize() method does not default initialize memory for built-in /// integer types. It does however default initialize classes and /// struct types if they have a constructor. It also prevents /// bounds checks which is important for primesieve's performance, e.g. /// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS /// which enables std::vector bounds checks. /// template <typename T, typename Allocator = std::allocator<T>> class pod_vector { public: // The default C++ std::allocator is stateless. We use this // allocator and do not support other statefull allocators, // which simplifies our implementation. // // "The default allocator is stateless, that is, all instances // of the given allocator are interchangeable, compare equal // and can deallocate memory allocated by any other instance // of the same allocator type." // https://en.cppreference.com/w/cpp/memory/allocator // // "The member type is_always_equal of std::allocator_traits // is intendedly used for determining whether an allocator // type is stateless." // https://en.cppreference.com/w/cpp/named_req/Allocator static_assert(std::allocator_traits<Allocator>::is_always_equal::value, "pod_vector<T> only supports stateless allocators!"); using value_type = T; pod_vector() noexcept = default; pod_vector(std::size_t size) { resize(size); } ~pod_vector() { destroy(array_, end_); Allocator().deallocate(array_, capacity()); } /// Free all memory, the pod_vector /// can be reused afterwards. void deallocate() noexcept { this->~pod_vector<T>(); array_ = nullptr; end_ = nullptr; capacity_ = nullptr; } /// Reset the pod_vector, but do not free its /// memory. Same as std::vector.clear(). void clear() noexcept { destroy(array_, end_); end_ = array_; } /// Copying is slow, we prevent it pod_vector(const pod_vector&) = delete; pod_vector& operator=(const pod_vector&) = delete; /// Move constructor pod_vector(pod_vector&& other) noexcept { swap(other); } /// Move assignment operator pod_vector& operator=(pod_vector&& other) noexcept { if (this != &other) swap(other); return *this; } /// Better assembly than: std::swap(vect1, vect2) void swap(pod_vector& other) noexcept { T* tmp_array = array_; T* tmp_end = end_; T* tmp_capacity = capacity_; array_ = other.array_; end_ = other.end_; capacity_ = other.capacity_; other.array_ = tmp_array; other.end_ = tmp_end; other.capacity_ = tmp_capacity; } bool empty() const noexcept { return array_ == end_; } T& operator[](std::size_t pos) noexcept { ASSERT(pos < size()); return array_[pos]; } const T& operator[](std::size_t pos) const noexcept { ASSERT(pos < size()); return array_[pos]; } T* data() noexcept { return array_; } const T* data() const noexcept { return array_; } std::size_t size() const noexcept { ASSERT(end_ >= array_); return (std::size_t)(end_ - array_); } std::size_t capacity() const noexcept { ASSERT(capacity_ >= array_); return (std::size_t)(capacity_ - array_); } T* begin() noexcept { return array_; } const T* begin() const noexcept { return array_; } T* end() noexcept { return end_; } const T* end() const noexcept { return end_; } T& front() noexcept { ASSERT(!empty()); return *array_; } const T& front() const noexcept { ASSERT(!empty()); return *array_; } T& back() noexcept { ASSERT(!empty()); return *(end_ - 1); } const T& back() const noexcept { ASSERT(!empty()); return *(end_ - 1); } ALWAYS_INLINE void push_back(const T& value) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Placement new new(end_) T(value); end_++; } ALWAYS_INLINE void push_back(T&& value) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Without std::move() the copy constructor will // be called instead of the move constructor. new(end_) T(std::move(value)); end_++; } template <class... Args> ALWAYS_INLINE void emplace_back(Args&&... args) { if_unlikely(end_ == capacity_) reserve_unchecked(std::max((std::size_t) 1, capacity() * 2)); // Placement new new(end_) T(std::forward<Args>(args)...); end_++; } template <class InputIt> void insert(T* const pos, InputIt first, InputIt last) { static_assert(std::is_trivially_copyable<T>::value, "pod_vector<T>::insert() supports only trivially copyable types!"); // We only support appending to the vector ASSERT(pos == end_); (void) pos; if (first < last) { std::size_t new_size = size() + (std::size_t) (last - first); reserve(new_size); std::uninitialized_copy(first, last, end_); end_ = array_ + new_size; } } void reserve(std::size_t n) { if (n > capacity()) reserve_unchecked(n); } void resize(std::size_t n) { if (n > size()) { if (n > capacity()) reserve_unchecked(n); // This default initializes memory of classes and structs // with constructors (and with in-class initialization of // non-static members). But it does not default initialize // memory for POD types like int, long. if (!std::is_trivial<T>::value) uninitialized_default_construct(end_, array_ + n); end_ = array_ + n; } else if (n < size()) { destroy(array_ + n, end_); end_ = array_ + n; } } private: T* array_ = nullptr; T* end_ = nullptr; T* capacity_ = nullptr; /// Requires n > capacity() void reserve_unchecked(std::size_t n) { ASSERT(n > capacity()); ASSERT(size() <= capacity()); std::size_t old_size = size(); std::size_t old_capacity = capacity(); // GCC & Clang's std::vector grow the capacity by at least // 2x for every call to resize() with n > capacity(). We // grow by at least 1.5x as we tend to accurately calculate // the amount of memory we need upfront. std::size_t new_capacity = (old_capacity * 3) / 2; new_capacity = std::max(new_capacity, n); ASSERT(old_capacity < new_capacity); T* old = array_; array_ = Allocator().allocate(new_capacity); end_ = array_ + old_size; capacity_ = array_ + new_capacity; ASSERT(size() < capacity()); // Both primesieve & primecount require that byte arrays are // aligned to at least a alignof(uint64_t) boundary. This is // needed because our code casts byte arrays into uint64_t arrays // in some places in order to improve performance. The default // allocator guarantees that each memory allocation is at least // aligned to the largest built-in type (usually 16 or 32). ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0); if (old) { static_assert(std::is_nothrow_move_constructible<T>::value, "pod_vector<T> only supports nothrow moveable types!"); uninitialized_move_n(old, old_size, array_); Allocator().deallocate(old, old_capacity); } } template <typename U> ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type uninitialized_move_n(U* __restrict first, std::size_t count, U* __restrict d_first) { // We can use memcpy to move trivially copyable types. // https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class // https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy std::uninitialized_copy_n(first, count, d_first); } /// Same as std::uninitialized_move_n() from C++17. /// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n /// /// Unlike std::uninitialized_move_n() our implementation uses /// __restrict pointers which improves the generated assembly /// (using GCC & Clang). We can do this because we only use this /// method for non-overlapping arrays. template <typename U> ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type uninitialized_move_n(U* __restrict first, std::size_t count, U* __restrict d_first) { for (std::size_t i = 0; i < count; i++) new (d_first++) T(std::move(*first++)); } /// Same as std::uninitialized_default_construct() from C++17. /// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last) { // Default initialize array using placement new. // Note that `new (first) T();` zero initializes built-in integer types, // whereas `new (first) T;` does not initialize built-in integer types. for (; first != last; first++) new (first) T; } /// Same as std::destroy() from C++17. /// https://en.cppreference.com/w/cpp/memory/destroy ALWAYS_INLINE void destroy(T* first, T* last) { if (!std::is_trivially_destructible<T>::value) { // Theoretically deallocating in reverse order is more // cache efficient. Clang's std::vector implementation // also deallocates in reverse order. while (first != last) (--last)->~T(); } } }; template <typename T, std::size_t N> class pod_array { public: using value_type = T; T array_[N]; T& operator[](std::size_t pos) noexcept { ASSERT(pos < size()); return array_[pos]; } const T& operator[](std::size_t pos) const noexcept { ASSERT(pos < size()); return array_[pos]; } void fill(const T& value) { std::fill_n(begin(), size(), value); } T* data() noexcept { return array_; } const T* data() const noexcept { return array_; } T* begin() noexcept { return array_; } const T* begin() const noexcept { return array_; } T* end() noexcept { return array_ + N; } const T* end() const noexcept { return array_ + N; } T& back() noexcept { ASSERT(N > 0); return array_[N - 1]; } const T& back() const noexcept { ASSERT(N > 0); return array_[N - 1]; } constexpr std::size_t size() const noexcept { return N; } }; } // namespace #endif
Add more assertions
Add more assertions
C++
bsd-2-clause
kimwalisch/primesieve,kimwalisch/primesieve,kimwalisch/primesieve
9f1309638e451df4c4027eb6fd40d5461e7ed17e
include/bptree/internal/static_vector.hpp
include/bptree/internal/static_vector.hpp
/************************************************ * static_vector.hpp * bptree * * Copyright (c) 2017, Chi-En Wu * Distributed under MIT License ************************************************/ #ifndef BPTREE_INTERNAL_STATIC_VECTOR_HPP_ #define BPTREE_INTERNAL_STATIC_VECTOR_HPP_ #include <cassert> #include <cstddef> #include <memory> #include <stdexcept> #include <type_traits> namespace bptree { namespace internal { /************************************************ * Declaration: class static_vector<T, N> ************************************************/ template <typename T, std::size_t N> class static_vector { public: // Public Type(s) using value_type = T; using reference = value_type&; using const_reference = value_type const&; using pointer = value_type*; using const_pointer = value_type const*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; public: // Public Method(s) static_vector(); explicit static_vector(size_type count); static_vector(size_type count, value_type const& value); template <typename InputIt> static_vector(InputIt first, InputIt last); static_vector(std::initializer_list<value_type> il); static_vector(static_vector const& other); ~static_vector(); static_vector& operator=(std::initializer_list<value_type> il); static_vector& operator=(static_vector const& other); void assign(size_type count, value_type const& value); void assign(std::initializer_list<value_type> il); template <typename InputIt> void assign(InputIt first, InputIt last); void push_back(value_type const& value); void push_back(value_type&& value); template <typename... Args> void emplace_back(Args&&... args); void clear() noexcept; reference operator[](size_type pos); const_reference operator[](size_type pos) const; reference at(size_type pos); const_reference at(size_type pos) const; value_type* data() noexcept; value_type const* data() const noexcept; bool empty() const noexcept; bool full() const noexcept; size_type size() const noexcept; constexpr size_type max_size() const noexcept; constexpr size_type capacity() const noexcept; private: // Private Property(ies) size_type size_; std::aligned_storage_t<sizeof(T), alignof(T)> data_[N]; }; /************************************************ * Implementation: class static_vector<T, N> ************************************************/ template <typename T, std::size_t N> inline static_vector<T, N>::static_vector() : size_(0), data_() { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(size_type count) : size_(count), data_() { assert(count <= max_size()); auto first = data(); auto last = first + size_; auto current = first; try { for (; current != last; ++current) { ::new(current) value_type; } } catch (...) { for (; first != current; ++first) { first->~value_type(); } throw; } } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(size_type count, value_type const& value) : size_(count), data_() { assert(count <= max_size()); auto first = data(); auto last = first + size_; std::uninitialized_fill(first, last, value); } template <typename T, std::size_t N> template <typename InputIt> inline static_vector<T, N>::static_vector(InputIt first, InputIt last) : static_vector() { auto data_first = data(); auto data_last = std::uninitialized_copy(first, last, data_first); size_ = data_last - data_first; assert(size_ <= max_size()); } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(std::initializer_list<value_type> il) : static_vector(il.begin(), il.end()) { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(static_vector const& other) : static_vector(other.data(), other.data() + other.size()) { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::~static_vector() { clear(); } template <typename T, std::size_t N> inline static_vector<T, N>& static_vector<T, N>::operator=(std::initializer_list<value_type> il) { assign(il); return *this; } template <typename T, std::size_t N> inline static_vector<T, N>& static_vector<T, N>::operator=(static_vector const& other) { assign(other.data(), other.data() + other.size()); return *this; } template <typename T, std::size_t N> inline void static_vector<T, N>::assign(size_type count, value_type const& value) { assert(count <= max_size()); clear(); auto first = data(); auto last = first + count; size_ = count; std::uninitialized_fill(first, last, value); } template <typename T, std::size_t N> inline void static_vector<T, N>::assign(std::initializer_list<value_type> il) { assign(il.begin(), il.end()); } template <typename T, std::size_t N> template <typename InputIt> inline void static_vector<T, N>::assign(InputIt first, InputIt last) { clear(); auto ptr = std::uninitialized_copy(first, last, data()); size_ = ptr - data(); assert(size_ <= max_size()); } template <typename T, std::size_t N> inline void static_vector<T, N>::push_back(value_type const& value) { assert(size_ < max_size()); ::new(data() + size_) value_type(value); ++size_; } template <typename T, std::size_t N> inline void static_vector<T, N>::push_back(value_type&& value) { assert(size_ < max_size()); ::new(data() + size_) value_type(std::move(value)); ++size_; } template <typename T, std::size_t N> template <typename... Args> inline void static_vector<T, N>::emplace_back(Args&&... args) { assert(size_ < max_size()); ::new(data() + size_) value_type(std::forward<Args>(args)...); ++size_; } template <typename T, std::size_t N> inline void static_vector<T, N>::clear() noexcept { for (size_type pos = 0; pos < size(); ++pos) { at(pos).~value_type(); } size_ = 0; } template <typename T, std::size_t N> inline typename static_vector<T, N>::reference static_vector<T, N>::operator[](size_type pos) { assert(pos < size()); return *(data() + pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::const_reference static_vector<T, N>::operator[](size_type pos) const { assert(pos < size()); return *(data() + pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::reference static_vector<T, N>::at(size_type pos) { return const_cast<reference>( static_cast<static_vector const*>(this)->at(pos)); } template <typename T, std::size_t N> inline typename static_vector<T, N>::const_reference static_vector<T, N>::at(size_type pos) const { if (pos >= size()) { throw std::out_of_range("index out of bounds"); } return operator[](pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::value_type* static_vector<T, N>::data() noexcept { return reinterpret_cast<value_type*>(data_); } template <typename T, std::size_t N> inline typename static_vector<T, N>::value_type const* static_vector<T, N>::data() const noexcept { return reinterpret_cast<value_type const*>(data_); } template <typename T, std::size_t N> inline bool static_vector<T, N>::empty() const noexcept { return size() == 0; } template <typename T, std::size_t N> inline bool static_vector<T, N>::full() const noexcept { return size() >= max_size(); } template <typename T, std::size_t N> inline typename static_vector<T, N>::size_type static_vector<T, N>::size() const noexcept { return size_; } template <typename T, std::size_t N> inline constexpr typename static_vector<T, N>::size_type static_vector<T, N>::max_size() const noexcept { return N; } template <typename T, std::size_t N> inline constexpr typename static_vector<T, N>::size_type static_vector<T, N>::capacity() const noexcept { return max_size(); } } // namespace internal } // namespace bptree #endif // BPTREE_INTERNAL_STATIC_VECTOR_HPP_
/************************************************ * static_vector.hpp * bptree * * Copyright (c) 2017, Chi-En Wu * Distributed under MIT License ************************************************/ #ifndef BPTREE_INTERNAL_STATIC_VECTOR_HPP_ #define BPTREE_INTERNAL_STATIC_VECTOR_HPP_ #include <cassert> #include <cstddef> #include <memory> #include <stdexcept> #include <type_traits> namespace bptree { namespace internal { /************************************************ * Declaration: class static_vector<T, N> ************************************************/ template <typename T, std::size_t N> class static_vector { public: // Public Type(s) using value_type = T; using reference = value_type&; using const_reference = value_type const&; using pointer = value_type*; using const_pointer = value_type const*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; public: // Public Method(s) static_vector(); explicit static_vector(size_type count); static_vector(size_type count, value_type const& value); template <typename InputIt> static_vector(InputIt first, InputIt last); static_vector(std::initializer_list<value_type> il); static_vector(static_vector const& other); ~static_vector(); static_vector& operator=(std::initializer_list<value_type> il); static_vector& operator=(static_vector const& other); void assign(size_type count, value_type const& value); void assign(std::initializer_list<value_type> il); template <typename InputIt> void assign(InputIt first, InputIt last); void push_back(value_type const& value); void push_back(value_type&& value); template <typename... Args> void emplace_back(Args&&... args); void clear() noexcept; reference operator[](size_type pos); const_reference operator[](size_type pos) const; reference at(size_type pos); const_reference at(size_type pos) const; value_type* data() noexcept; value_type const* data() const noexcept; bool empty() const noexcept; bool full() const noexcept; size_type size() const noexcept; constexpr size_type max_size() const noexcept; constexpr size_type capacity() const noexcept; private: // Private Property(ies) size_type size_; std::aligned_storage_t<sizeof(T), alignof(T)> data_[N]; }; /************************************************ * Implementation: class static_vector<T, N> ************************************************/ template <typename T, std::size_t N> inline static_vector<T, N>::static_vector() : size_(0), data_() { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(size_type count) : size_(count), data_() { assert(count <= max_size()); auto first = data(); auto last = first + size_; auto current = first; try { for (; current != last; ++current) { ::new(current) value_type; } } catch (...) { for (; first != current; ++first) { first->~value_type(); } throw; } } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(size_type count, value_type const& value) : size_(count), data_() { assert(count <= max_size()); auto first = data(); auto last = first + size_; std::uninitialized_fill(first, last, value); } template <typename T, std::size_t N> template <typename InputIt> inline static_vector<T, N>::static_vector(InputIt first, InputIt last) : static_vector() { auto data_first = data(); auto data_last = std::uninitialized_copy(first, last, data_first); size_ = data_last - data_first; assert(size_ <= max_size()); } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(std::initializer_list<value_type> il) : static_vector(il.begin(), il.end()) { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::static_vector(static_vector const& other) : static_vector(other.data(), other.data() + other.size()) { // do nothing } template <typename T, std::size_t N> inline static_vector<T, N>::~static_vector() { clear(); } template <typename T, std::size_t N> inline static_vector<T, N>& static_vector<T, N>::operator=(std::initializer_list<value_type> il) { assign(il); return *this; } template <typename T, std::size_t N> inline static_vector<T, N>& static_vector<T, N>::operator=(static_vector const& other) { assign(other.data(), other.data() + other.size()); return *this; } template <typename T, std::size_t N> inline void static_vector<T, N>::assign(size_type count, value_type const& value) { assert(count <= max_size()); clear(); auto first = data(); auto last = first + count; size_ = count; std::uninitialized_fill(first, last, value); } template <typename T, std::size_t N> inline void static_vector<T, N>::assign(std::initializer_list<value_type> il) { assign(il.begin(), il.end()); } template <typename T, std::size_t N> template <typename InputIt> inline void static_vector<T, N>::assign(InputIt first, InputIt last) { clear(); auto ptr = std::uninitialized_copy(first, last, data()); size_ = ptr - data(); assert(size_ <= max_size()); } template <typename T, std::size_t N> inline void static_vector<T, N>::push_back(value_type const& value) { emplace_back(value); } template <typename T, std::size_t N> inline void static_vector<T, N>::push_back(value_type&& value) { emplace_back(std::move(value)); } template <typename T, std::size_t N> template <typename... Args> inline void static_vector<T, N>::emplace_back(Args&&... args) { assert(size_ < max_size()); ::new(data() + size_) value_type(std::forward<Args>(args)...); ++size_; } template <typename T, std::size_t N> inline void static_vector<T, N>::clear() noexcept { for (size_type pos = 0; pos < size(); ++pos) { at(pos).~value_type(); } size_ = 0; } template <typename T, std::size_t N> inline typename static_vector<T, N>::reference static_vector<T, N>::operator[](size_type pos) { assert(pos < size()); return *(data() + pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::const_reference static_vector<T, N>::operator[](size_type pos) const { assert(pos < size()); return *(data() + pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::reference static_vector<T, N>::at(size_type pos) { return const_cast<reference>( static_cast<static_vector const*>(this)->at(pos)); } template <typename T, std::size_t N> inline typename static_vector<T, N>::const_reference static_vector<T, N>::at(size_type pos) const { if (pos >= size()) { throw std::out_of_range("index out of bounds"); } return operator[](pos); } template <typename T, std::size_t N> inline typename static_vector<T, N>::value_type* static_vector<T, N>::data() noexcept { return reinterpret_cast<value_type*>(data_); } template <typename T, std::size_t N> inline typename static_vector<T, N>::value_type const* static_vector<T, N>::data() const noexcept { return reinterpret_cast<value_type const*>(data_); } template <typename T, std::size_t N> inline bool static_vector<T, N>::empty() const noexcept { return size() == 0; } template <typename T, std::size_t N> inline bool static_vector<T, N>::full() const noexcept { return size() >= max_size(); } template <typename T, std::size_t N> inline typename static_vector<T, N>::size_type static_vector<T, N>::size() const noexcept { return size_; } template <typename T, std::size_t N> inline constexpr typename static_vector<T, N>::size_type static_vector<T, N>::max_size() const noexcept { return N; } template <typename T, std::size_t N> inline constexpr typename static_vector<T, N>::size_type static_vector<T, N>::capacity() const noexcept { return max_size(); } } // namespace internal } // namespace bptree #endif // BPTREE_INTERNAL_STATIC_VECTOR_HPP_
Implement `static_vector<T, N>::push_back()` with `static_vector<T, N>::emplace_back()`
:hammer: Implement `static_vector<T, N>::push_back()` with `static_vector<T, N>::emplace_back()`
C++
mit
jason2506/bptree,jason2506/bptree
44918e352cfe03ce28a5562db5f9e0af1a895c2e
include/primesieve/WheelFactorization.hpp
include/primesieve/WheelFactorization.hpp
/// /// @file WheelFactorization.hpp /// @brief Classes and structs related to wheel factorization. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEELFACTORIZATION_HPP #define WHEELFACTORIZATION_HPP #include "config.hpp" #include "pmath.hpp" #include "primesieve_error.hpp" #include <stdint.h> #include <cstddef> #include <cassert> #include <string> #include <limits> namespace primesieve { /// The WheelInit data structure is used to calculate the first /// multiple >= start of each sieving prime. /// struct WheelInit { uint8_t nextMultipleFactor; uint8_t wheelIndex; }; extern const WheelInit wheel30Init[30]; extern const WheelInit wheel210Init[210]; /// The WheelElement data structure is used to skip multiples of /// small primes using wheel factorization. /// struct WheelElement { /// Bitmask used to unset the bit corresponding to the current /// multiple of a SievingPrime object. uint8_t unsetBit; /// Factor used to calculate the next multiple of a sieving prime /// that is not divisible by any of the wheel factors. uint8_t nextMultipleFactor; /// Overflow needed to correct the next multiple index /// (due to sievingPrime = prime / 30). uint8_t correct; /// Used to calculate the next wheel index: /// wheelIndex += next; int8_t next; }; extern const WheelElement wheel30[8*8]; extern const WheelElement wheel210[48*8]; /// Sieving primes are used to cross-off multiples (of itself). /// Each SievingPrime object contains a sieving prime and the position /// of its next multiple within the SieveOfEratosthenes array /// (i.e. multipleIndex) and a wheelIndex. /// class SievingPrime { public: enum { MAX_MULTIPLEINDEX = (1 << 23) - 1, MAX_WHEELINDEX = (1 << (32 - 23)) - 1 }; uint_t getSievingPrime() const { return sievingPrime_; } uint_t getMultipleIndex() const { return indexes_ & MAX_MULTIPLEINDEX; } uint_t getWheelIndex() const { return indexes_ >> 23; } void setMultipleIndex(uint_t multipleIndex) { assert(multipleIndex <= MAX_MULTIPLEINDEX); indexes_ = static_cast<uint32_t>(indexes_ | multipleIndex); } void setWheelIndex(uint_t wheelIndex) { assert(wheelIndex <= MAX_WHEELINDEX); indexes_ = static_cast<uint32_t>(wheelIndex << 23); } void set(uint_t multipleIndex, uint_t wheelIndex) { assert(multipleIndex <= MAX_MULTIPLEINDEX); assert(wheelIndex <= MAX_WHEELINDEX); indexes_ = static_cast<uint32_t>(multipleIndex | (wheelIndex << 23)); } void set(uint_t sievingPrime, uint_t multipleIndex, uint_t wheelIndex) { set(multipleIndex, wheelIndex); sievingPrime_ = static_cast<uint32_t>(sievingPrime); } private: /// multipleIndex = 23 least significant bits of indexes_. /// wheelIndex = 9 most significant bits of indexes_. uint32_t indexes_; uint32_t sievingPrime_; }; /// The Bucket data structure is used to store sieving primes. /// @see http://www.ieeta.pt/~tos/software/prime_sieve.html /// The Bucket class is designed as a singly linked list, once there /// is no more space in the current Bucket a new Bucket node is /// allocated. /// class Bucket { public: Bucket() { reset(); } SievingPrime* begin() { return &sievingPrimes_[0]; } SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; } SievingPrime* end() { return prime_; } Bucket* next() { return next_; } bool hasNext() const { return next_ != NULL; } bool empty() { return begin() == end(); } void reset() { prime_ = begin(); } void setNext(Bucket* next) { next_ = next; } /// Store a sieving prime in the bucket. /// @return false if the bucket is full else true. /// bool store(uint_t sievingPrime, uint_t multipleIndex, uint_t wheelIndex) { prime_->set(sievingPrime, multipleIndex, wheelIndex); return prime_++ != last(); } private: SievingPrime* prime_; Bucket* next_; SievingPrime sievingPrimes_[config::BUCKETSIZE]; }; /// The abstract WheelFactorization class is used skip multiples of /// small primes in the sieve of Eratosthenes. The EratSmall, /// EratMedium and EratBig classes are derived from /// WheelFactorization. /// template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL> class WheelFactorization { public: /// Add a new sieving prime to the sieving algorithm. /// Calculate the first multiple > segmentLow of prime and the /// position within the SieveOfEratosthenes array of that multiple /// and its wheel index. When done store the sieving prime. /// void addSievingPrime(uint_t prime, uint64_t segmentLow) { segmentLow += 6; // calculate the first multiple (of prime) > segmentLow uint64_t quotient = segmentLow / prime + 1; uint64_t multiple = prime * quotient; // prime not needed for sieving if (multiple > stop_ || multiple < segmentLow) return; // ensure multiple >= prime * prime if (quotient < prime) { multiple = isquare<uint64_t>(prime); quotient = prime; } // calculate the next multiple of prime that is not // divisible by any of the wheel's factors uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor; uint64_t nextMultiple = prime * nextMultipleFactor; if (nextMultiple > stop_ - multiple) return; nextMultiple += multiple - segmentLow; uint_t multipleIndex = static_cast<uint_t>(nextMultiple / NUMBERS_PER_BYTE); uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex; storeSievingPrime(prime, multipleIndex, wheelIndex); } protected: /// @param stop Upper bound for sieving. /// @param sieveSize Sieve size in bytes. /// WheelFactorization(uint64_t stop, uint_t sieveSize) : stop_(stop) { uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1; if (sieveSize > maxSieveSize) throw primesieve_error("WheelFactorization: sieveSize must be <= " + std::to_string(maxSieveSize)); } virtual ~WheelFactorization() { } virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0; static uint_t getMaxFactor() { return WHEEL[0].nextMultipleFactor; } /// Cross-off the current multiple (unset bit) of sievingPrime and /// calculate its next multiple i.e. multipleIndex. /// static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex) { sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit; *multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime; *multipleIndex += WHEEL[*wheelIndex].correct; *wheelIndex += WHEEL[*wheelIndex].next; } private: static const uint_t wheelOffsets_[30]; const uint64_t stop_; DISALLOW_COPY_AND_ASSIGN(WheelFactorization); }; template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL> const uint_t WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] = { 0, SIZE * 7, 0, 0, 0, 0, 0, SIZE * 0, 0, 0, 0, SIZE * 1, 0, SIZE * 2, 0, 0, 0, SIZE * 3, 0, SIZE * 4, 0, 0, 0, SIZE * 5, 0, 0, 0, 0, 0, SIZE * 6 }; /// 3rd wheel, skips multiples of 2, 3 and 5 typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t; /// 4th wheel, skips multiples of 2, 3, 5 and 7 typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t; } // namespace primesieve #endif
/// /// @file WheelFactorization.hpp /// @brief Classes and structs related to wheel factorization. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef WHEELFACTORIZATION_HPP #define WHEELFACTORIZATION_HPP #include "config.hpp" #include "pmath.hpp" #include "primesieve_error.hpp" #include <stdint.h> #include <cstddef> #include <cassert> #include <string> #include <limits> namespace primesieve { /// The WheelInit data structure is used to calculate the first /// multiple >= start of each sieving prime. /// struct WheelInit { uint8_t nextMultipleFactor; uint8_t wheelIndex; }; extern const WheelInit wheel30Init[30]; extern const WheelInit wheel210Init[210]; /// The WheelElement data structure is used to skip multiples of /// small primes using wheel factorization. /// struct WheelElement { /// Bitmask used to unset the bit corresponding to the current /// multiple of a SievingPrime object. uint8_t unsetBit; /// Factor used to calculate the next multiple of a sieving prime /// that is not divisible by any of the wheel factors. uint8_t nextMultipleFactor; /// Overflow needed to correct the next multiple index /// (due to sievingPrime = prime / 30). uint8_t correct; /// Used to calculate the next wheel index: /// wheelIndex += next; int8_t next; }; extern const WheelElement wheel30[8*8]; extern const WheelElement wheel210[48*8]; /// Sieving primes are used to cross-off multiples (of itself). /// Each SievingPrime object contains a sieving prime and the position /// of its next multiple within the SieveOfEratosthenes array /// (i.e. multipleIndex) and a wheelIndex. /// class SievingPrime { public: enum { MAX_MULTIPLEINDEX = (1 << 23) - 1, MAX_WHEELINDEX = (1 << (32 - 23)) - 1 }; uint_t getSievingPrime() const { return sievingPrime_; } uint_t getMultipleIndex() const { return indexes_ & MAX_MULTIPLEINDEX; } uint_t getWheelIndex() const { return indexes_ >> 23; } void setMultipleIndex(uint_t multipleIndex) { assert(multipleIndex <= MAX_MULTIPLEINDEX); indexes_ = (uint32_t)(indexes_ | multipleIndex); } void setWheelIndex(uint_t wheelIndex) { assert(wheelIndex <= MAX_WHEELINDEX); indexes_ = (uint32_t)(wheelIndex << 23); } void set(uint_t multipleIndex, uint_t wheelIndex) { assert(multipleIndex <= MAX_MULTIPLEINDEX); assert(wheelIndex <= MAX_WHEELINDEX); indexes_ = (uint32_t)(multipleIndex | (wheelIndex << 23)); } void set(uint_t sievingPrime, uint_t multipleIndex, uint_t wheelIndex) { set(multipleIndex, wheelIndex); sievingPrime_ = (uint32_t) sievingPrime; } private: /// multipleIndex = 23 least significant bits of indexes_. /// wheelIndex = 9 most significant bits of indexes_. uint32_t indexes_; uint32_t sievingPrime_; }; /// The Bucket data structure is used to store sieving primes. /// @see http://www.ieeta.pt/~tos/software/prime_sieve.html /// The Bucket class is designed as a singly linked list, once there /// is no more space in the current Bucket a new Bucket node is /// allocated. /// class Bucket { public: Bucket() { reset(); } SievingPrime* begin() { return &sievingPrimes_[0]; } SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; } SievingPrime* end() { return prime_; } Bucket* next() { return next_; } bool hasNext() const { return next_ != NULL; } bool empty() { return begin() == end(); } void reset() { prime_ = begin(); } void setNext(Bucket* next) { next_ = next; } /// Store a sieving prime in the bucket. /// @return false if the bucket is full else true. /// bool store(uint_t sievingPrime, uint_t multipleIndex, uint_t wheelIndex) { prime_->set(sievingPrime, multipleIndex, wheelIndex); return prime_++ != last(); } private: SievingPrime* prime_; Bucket* next_; SievingPrime sievingPrimes_[config::BUCKETSIZE]; }; /// The abstract WheelFactorization class is used skip multiples of /// small primes in the sieve of Eratosthenes. The EratSmall, /// EratMedium and EratBig classes are derived from /// WheelFactorization. /// template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL> class WheelFactorization { public: /// Add a new sieving prime to the sieving algorithm. /// Calculate the first multiple > segmentLow of prime and the /// position within the SieveOfEratosthenes array of that multiple /// and its wheel index. When done store the sieving prime. /// void addSievingPrime(uint_t prime, uint64_t segmentLow) { segmentLow += 6; // calculate the first multiple (of prime) > segmentLow uint64_t quotient = segmentLow / prime + 1; uint64_t multiple = prime * quotient; // prime not needed for sieving if (multiple > stop_ || multiple < segmentLow) return; // ensure multiple >= prime * prime if (quotient < prime) { multiple = isquare<uint64_t>(prime); quotient = prime; } // calculate the next multiple of prime that is not // divisible by any of the wheel's factors uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor; uint64_t nextMultiple = prime * nextMultipleFactor; if (nextMultiple > stop_ - multiple) return; nextMultiple += multiple - segmentLow; uint_t multipleIndex = (uint_t)(nextMultiple / NUMBERS_PER_BYTE); uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex; storeSievingPrime(prime, multipleIndex, wheelIndex); } protected: /// @param stop Upper bound for sieving. /// @param sieveSize Sieve size in bytes. /// WheelFactorization(uint64_t stop, uint_t sieveSize) : stop_(stop) { uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1; if (sieveSize > maxSieveSize) throw primesieve_error("WheelFactorization: sieveSize must be <= " + std::to_string(maxSieveSize)); } virtual ~WheelFactorization() { } virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0; static uint_t getMaxFactor() { return WHEEL[0].nextMultipleFactor; } /// Cross-off the current multiple (unset bit) of sievingPrime and /// calculate its next multiple i.e. multipleIndex. /// static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex) { sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit; *multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime; *multipleIndex += WHEEL[*wheelIndex].correct; *wheelIndex += WHEEL[*wheelIndex].next; } private: static const uint_t wheelOffsets_[30]; const uint64_t stop_; DISALLOW_COPY_AND_ASSIGN(WheelFactorization); }; template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL> const uint_t WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] = { 0, SIZE * 7, 0, 0, 0, 0, 0, SIZE * 0, 0, 0, 0, SIZE * 1, 0, SIZE * 2, 0, 0, 0, SIZE * 3, 0, SIZE * 4, 0, 0, 0, SIZE * 5, 0, 0, 0, 0, 0, SIZE * 6 }; /// 3rd wheel, skips multiples of 2, 3 and 5 typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t; /// 4th wheel, skips multiples of 2, 3, 5 and 7 typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t; } // namespace primesieve #endif
Use C-style casts
Use C-style casts
C++
bsd-2-clause
kimwalisch/primesieve,kimwalisch/primesieve,kimwalisch/primesieve
a0749511f6c0446930fcbcd3192801bbc78a6978
src/textformatter.cpp
src/textformatter.cpp
#include "textformatter.h" #include <algorithm> #include <assert.h> #include <cinttypes> #include <limits.h> #include "htmlrenderer.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" namespace newsboat { TextFormatter::TextFormatter() {} TextFormatter::~TextFormatter() {} void TextFormatter::add_line(LineType type, std::string line) { LOG(Level::DEBUG, "TextFormatter::add_line: `%s' (line type %u)", line, static_cast<unsigned int>(type)); auto clean_line = utils::wstr2str( utils::clean_nonprintable_characters(utils::str2wstr(line))); lines.push_back(std::make_pair(type, clean_line)); } void TextFormatter::add_lines( const std::vector<std::pair<LineType, std::string>>& lines) { for (const auto& line : lines) { add_line(line.first, utils::replace_all(line.second, "\t", " ")); } } std::vector<std::string> wrap_line(const std::string& line, const size_t width) { if (line.empty()) { return {""}; } std::vector<std::string> result; std::vector<std::string> words = utils::tokenize_spaced(line); std::string prefix; size_t prefix_width = 0; auto iswhitespace = [](const std::string& input) { return std::all_of(input.cbegin(), input.cend(), [](std::string::value_type c) { return std::isspace(c); }); }; if (iswhitespace(words[0])) { prefix = utils::substr_with_width_stfl(words[0], width); prefix_width = utils::strwidth_stfl(prefix); words.erase(words.cbegin()); } std::string curline = prefix; for (auto& word : words) { size_t word_width = utils::strwidth_stfl(word); size_t curline_width = utils::strwidth_stfl(curline); // for languages (e.g., CJK) don't use a space as a word // boundary while (word_width > (width - prefix_width)) { size_t space_left = width - curline_width; std::string part = utils::substr_with_width_stfl(word, space_left); curline.append(part); word.erase(0, part.length()); result.push_back(curline); curline = prefix; if (part.empty()) { // discard the current word word.clear(); } word_width = utils::strwidth_stfl(word); curline_width = utils::strwidth_stfl(curline); } if ((curline_width + word_width) > width) { result.push_back(curline); if (iswhitespace(word)) { curline = prefix; } else { curline = prefix + word; } } else { curline.append(word); } } if (curline != prefix) { result.push_back(curline); } return result; } std::vector<std::string> format_text_plain_helper( const std::vector<std::pair<LineType, std::string>>& lines, RegexManager* rxman, const std::string& location, // wrappable lines are wrapped at this width const size_t wrap_width, // if non-zero, softwrappable lines are wrapped at this width const size_t total_width) { LOG(Level::DEBUG, "TextFormatter::format_text_plain: rxman = %p, location = " "`%s', " "wrap_width = %" PRIu64 ", total_width = %" PRIu64 ", %" PRIu64 " lines", rxman, location, static_cast<uint64_t>(wrap_width), static_cast<uint64_t>(total_width), static_cast<uint64_t>(lines.size())); std::vector<std::string> format_cache; auto store_line = [&format_cache](std::string line) { format_cache.push_back(line); LOG(Level::DEBUG, "TextFormatter::format_text_plain: stored `%s'", line); }; for (const auto& line : lines) { auto type = line.first; auto text = line.second; LOG(Level::DEBUG, "TextFormatter::format_text_plain: got line `%s' type " "%u", text, static_cast<unsigned int>(type)); if (rxman && type != LineType::hr) { rxman->quote_and_highlight(text, location); } switch (type) { case LineType::wrappable: if (text == "") { store_line(" "); continue; } text = utils::consolidate_whitespace(text); for (const auto& line : wrap_line(text, wrap_width)) { store_line(line); } break; case LineType::softwrappable: if (text == "") { store_line(" "); continue; } if (total_width == 0) { store_line(text); } else { for (const auto& line : wrap_line(text, total_width)) { store_line(line); } } break; case LineType::nonwrappable: store_line(text); break; case LineType::hr: store_line(HtmlRenderer::render_hr(wrap_width)); break; } } return format_cache; } std::pair<std::string, std::size_t> TextFormatter::format_text_to_list( RegexManager* rxman, const std::string& location, const size_t wrap_width, const size_t total_width) { auto formatted = format_text_plain_helper( lines, rxman, location, wrap_width, total_width); auto format_cache = std::string("{list"); for (auto& line : formatted) { if (line != "") { utils::trim_end(line); format_cache.append(strprintf::fmt( "{listitem text:%s}", Stfl::quote(line))); } } format_cache.push_back('}'); auto line_count = formatted.size(); return {format_cache, line_count}; } std::string TextFormatter::format_text_plain(const size_t width, const size_t total_width) { std::string result; auto formatted = format_text_plain_helper( lines, nullptr, "", width, total_width); for (const auto& line : formatted) { result += line + "\n"; } return result; } } // namespace newsboat
#include "textformatter.h" #include <algorithm> #include <assert.h> #include <cinttypes> #include <limits.h> #include "htmlrenderer.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" namespace newsboat { TextFormatter::TextFormatter() {} TextFormatter::~TextFormatter() {} void TextFormatter::add_line(LineType type, std::string line) { LOG(Level::DEBUG, "TextFormatter::add_line: `%s' (line type %u)", line, static_cast<unsigned int>(type)); auto clean_line = utils::wstr2str( utils::clean_nonprintable_characters(utils::str2wstr(line))); lines.push_back(std::make_pair(type, clean_line)); } void TextFormatter::add_lines( const std::vector<std::pair<LineType, std::string>>& lines) { for (const auto& line : lines) { add_line(line.first, utils::replace_all(line.second, "\t", " ")); } } std::vector<std::string> wrap_line(const std::string& line, const size_t width, bool raw) { if (line.empty()) { return {""}; } std::vector<std::string> result; std::vector<std::string> words = utils::tokenize_spaced(line); std::string prefix; size_t prefix_width = 0; auto iswhitespace = [](const std::string& input) { return std::all_of(input.cbegin(), input.cend(), [](std::string::value_type c) { return std::isspace(c); }); }; auto strwidth = [raw](const std::string& str) { if (raw) { return utils::strwidth(str); } else { return utils::strwidth_stfl(str); } }; auto substr_with_width = [raw](const std::string& str, const size_t max_width) { if (raw) { return utils::substr_with_width(str, max_width); } else { return utils::substr_with_width_stfl(str, max_width); } }; if (iswhitespace(words[0])) { prefix = substr_with_width(words[0], width); prefix_width = strwidth(prefix); words.erase(words.cbegin()); } std::string curline = prefix; for (auto& word : words) { size_t word_width = strwidth(word); size_t curline_width = strwidth(curline); // for languages (e.g., CJK) don't use a space as a word // boundary while (word_width > (width - prefix_width)) { size_t space_left = width - curline_width; std::string part = substr_with_width(word, space_left); curline.append(part); word.erase(0, part.length()); result.push_back(curline); curline = prefix; if (part.empty()) { // discard the current word word.clear(); } word_width = strwidth(word); curline_width = strwidth(curline); } if ((curline_width + word_width) > width) { result.push_back(curline); if (iswhitespace(word)) { curline = prefix; } else { curline = prefix + word; } } else { curline.append(word); } } if (curline != prefix) { result.push_back(curline); } return result; } std::vector<std::string> format_text_plain_helper( const std::vector<std::pair<LineType, std::string>>& lines, RegexManager* rxman, const std::string& location, // wrappable lines are wrapped at this width const size_t wrap_width, // if non-zero, softwrappable lines are wrapped at this width const size_t total_width, bool raw = false) { LOG(Level::DEBUG, "TextFormatter::format_text_plain: rxman = %p, location = " "`%s', " "wrap_width = %" PRIu64 ", total_width = %" PRIu64 ", %" PRIu64 " lines", rxman, location, static_cast<uint64_t>(wrap_width), static_cast<uint64_t>(total_width), static_cast<uint64_t>(lines.size())); std::vector<std::string> format_cache; auto store_line = [&format_cache](std::string line) { format_cache.push_back(line); LOG(Level::DEBUG, "TextFormatter::format_text_plain: stored `%s'", line); }; for (const auto& line : lines) { auto type = line.first; auto text = line.second; LOG(Level::DEBUG, "TextFormatter::format_text_plain: got line `%s' type " "%u", text, static_cast<unsigned int>(type)); if (rxman && type != LineType::hr) { rxman->quote_and_highlight(text, location); } switch (type) { case LineType::wrappable: if (text == "") { store_line(" "); continue; } text = utils::consolidate_whitespace(text); for (const auto& line : wrap_line(text, wrap_width, raw)) { store_line(line); } break; case LineType::softwrappable: if (text == "") { store_line(" "); continue; } if (total_width == 0) { store_line(text); } else { for (const auto& line : wrap_line(text, total_width, raw)) { store_line(line); } } break; case LineType::nonwrappable: store_line(text); break; case LineType::hr: store_line(HtmlRenderer::render_hr(wrap_width)); break; } } return format_cache; } std::pair<std::string, std::size_t> TextFormatter::format_text_to_list( RegexManager* rxman, const std::string& location, const size_t wrap_width, const size_t total_width) { auto formatted = format_text_plain_helper( lines, rxman, location, wrap_width, total_width); auto format_cache = std::string("{list"); for (auto& line : formatted) { if (line != "") { utils::trim_end(line); format_cache.append(strprintf::fmt( "{listitem text:%s}", Stfl::quote(line))); } } format_cache.push_back('}'); auto line_count = formatted.size(); return {format_cache, line_count}; } std::string TextFormatter::format_text_plain(const size_t width, const size_t total_width) { std::string result; auto formatted = format_text_plain_helper( lines, nullptr, "", width, total_width, true); for (const auto& line : formatted) { result += line + "\n"; } return result; } } // namespace newsboat
Use non-stfl variant of string-handling functions
Use non-stfl variant of string-handling functions
C++
mit
der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat
7e2ee08ad1e6a6a2d90e5ab8562e8842f3701cd2
source/WebcamImageTransform.cpp
source/WebcamImageTransform.cpp
#include "main.hpp" #include "WebcamImageTransform.hpp" void WebcamImageTransform::create(const graphics::ScreenRectBuffer *rectangle, uint32_t input_width, uint32_t input_height, uint32_t output_width, uint32_t output_height) { this->rectangle = rectangle; this->input_width = input_width; this->input_height = input_height; this->output_width = output_width; this->output_height = output_height; const auto overscan = ((float)input_width / input_height) / ((float)output_width / output_height); // column-major!!! transform = glm::mat3(-.95f, 0.f, 0.f, 0.f, -.95f * overscan, 0.f, 1.f, 1.f, 1.f); inverseTransform = glm::inverse(transform); static const char *vertexShaderSource = R"glsl( #version 330 core layout(location=0) in vec2 position; uniform mat3 transform; out vec2 texcoord; void main() { vec2 pixelTexcoord = position * .5 + .5; texcoord = vec2(transform * vec3(pixelTexcoord, 1.)); gl_Position = vec4(position, 0., 1.); } )glsl"; static const char *fragmentShaderSource = R"glsl( #version 330 core uniform sampler2D source; in vec2 texcoord; out vec4 frag_color; const float PI = 3.14159265; vec3 rgb2hsv(vec3 rgb) { float cmin = min(rgb.r, min(rgb.g, rgb.b)); float cmax = max(rgb.r, max(rgb.g, rgb.b)); float d = cmax - cmin; float eps = 0.00001; if (d < eps || cmax < eps) { return vec3(0, 0, cmax); } float _h; if (cmax == rgb.r) { _h = (rgb.g - rgb.b) / d; if (_h < 0.) { _h += 6.; } } else if (cmax == rgb.g) { _h = ((rgb.b - rgb.r) / d) + 2.; } else { _h = ((rgb.r - rgb.g) / d) + 4.; } return vec3(_h * 60. * (PI / 180.), d / cmax, cmax); } vec3 hsv2rgb(vec3 hsv) { // rapidtables.com/convert/color/hsv-to-rgb.htm float _h = hsv.x * 180. / PI; float _c = hsv.y * hsv.z; float _x = _c * (1. - abs(mod(_h / 60., 2.) - 1.)); float _m = hsv.z - _c; vec3 _r; if (/* 0. <= _h && */ _h < 60.) { _r.r = _c; _r.g = _x; _r.b = 0.; } else if (_h < 120.) { _r.r = _x; _r.g = _c; _r.b = 0.; } else if (_h < 180.) { _r.r = 0.; _r.g = _c; _r.b = _x; } else if (_h < 240.) { _r.r = 0.; _r.g = _x; _r.b = _c; } else if (_h < 300.) { _r.r = _x; _r.g = 0.; _r.b = _c; } else /* if (_h < 360.) */ { _r.r = _c; _r.g = 0.; _r.b = _x; } return _r + vec3(_m); } void main() { vec3 rgb = texture(source, texcoord).bgr; rgb = 1.1 * rgb; // increase overall brightness vec3 hsv = rgb2hsv(rgb); hsv.y = hsv.y * 2.; // increase saturation rgb = hsv2rgb(hsv); frag_color = vec4(rgb, 0.); } )glsl"; pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None); pipeline_transform_location = pipeline.getUniformLocation("transform"); pipeline_source_location = pipeline.getUniformLocation("source"); } void WebcamImageTransform::destroy() { pipeline.destroy(); } void WebcamImageTransform::draw(graphics::Texture &input, graphics::Framebuffer &output) { assert(input.getWidth() == input_width); assert(input.getHeight() == input_height); assert(output.getWidth() == output_width); assert(output.getHeight() == output_height); output.bind(); glViewport(0, 0, output.getWidth(), output.getHeight()); pipeline.bind(); glUniformMatrix3fv(pipeline_transform_location, 1, GL_FALSE, &transform[0][0]); input.bind(0u); glUniform1i(pipeline_source_location, 0u); rectangle->draw(); }
#include "main.hpp" #include "WebcamImageTransform.hpp" void WebcamImageTransform::create(const graphics::ScreenRectBuffer *rectangle, uint32_t input_width, uint32_t input_height, uint32_t output_width, uint32_t output_height) { this->rectangle = rectangle; this->input_width = input_width; this->input_height = input_height; this->output_width = output_width; this->output_height = output_height; const auto overscan = ((float)input_width / input_height) / ((float)output_width / output_height); // column-major!!! transform = glm::mat3(-.95f, 0.f, 0.f, 0.f, -.95f * overscan, 0.f, 1.f, 1.f, 1.f); inverseTransform = glm::inverse(transform); static const char *vertexShaderSource = R"glsl( #version 330 core layout(location=0) in vec2 position; uniform mat3 transform; out vec2 texcoord; void main() { vec2 pixelTexcoord = position * .5 + .5; texcoord = vec2(transform * vec3(pixelTexcoord, 1.)); gl_Position = vec4(position, 0., 1.); } )glsl"; static const char *fragmentShaderSource = R"glsl( #version 330 core uniform sampler2D source; in vec2 texcoord; out vec4 frag_color; const float PI = 3.14159265; vec3 rgb2hsv(vec3 rgb) { float cmin = min(rgb.r, min(rgb.g, rgb.b)); float cmax = max(rgb.r, max(rgb.g, rgb.b)); float d = cmax - cmin; float eps = 0.00001; if (d < eps || cmax < eps) { return vec3(0, 0, cmax); } float _h; if (cmax == rgb.r) { _h = (rgb.g - rgb.b) / d; if (_h < 0.) { _h += 6.; } } else if (cmax == rgb.g) { _h = ((rgb.b - rgb.r) / d) + 2.; } else { _h = ((rgb.r - rgb.g) / d) + 4.; } return vec3(_h * 60. * (PI / 180.), d / cmax, cmax); } vec3 hsv2rgb(vec3 hsv) { // rapidtables.com/convert/color/hsv-to-rgb.htm float _h = hsv.x * 180. / PI; float _c = hsv.y * hsv.z; float _x = _c * (1. - abs(mod(_h / 60., 2.) - 1.)); float _m = hsv.z - _c; vec3 _r; if (/* 0. <= _h && */ _h < 60.) { _r.r = _c; _r.g = _x; _r.b = 0.; } else if (_h < 120.) { _r.r = _x; _r.g = _c; _r.b = 0.; } else if (_h < 180.) { _r.r = 0.; _r.g = _c; _r.b = _x; } else if (_h < 240.) { _r.r = 0.; _r.g = _x; _r.b = _c; } else if (_h < 300.) { _r.r = _x; _r.g = 0.; _r.b = _c; } else /* if (_h < 360.) */ { _r.r = _c; _r.g = 0.; _r.b = _x; } return _r + vec3(_m); } void main() { vec3 rgb = texture(source, texcoord).bgr; rgb = 1.8 * rgb - vec3(.1); // increase overall brightness vec3 hsv = rgb2hsv(rgb); hsv.y = hsv.y * 2.; // increase saturation rgb = hsv2rgb(hsv); frag_color = vec4(rgb, 0.); } )glsl"; pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None); pipeline_transform_location = pipeline.getUniformLocation("transform"); pipeline_source_location = pipeline.getUniformLocation("source"); } void WebcamImageTransform::destroy() { pipeline.destroy(); } void WebcamImageTransform::draw(graphics::Texture &input, graphics::Framebuffer &output) { assert(input.getWidth() == input_width); assert(input.getHeight() == input_height); assert(output.getWidth() == output_width); assert(output.getHeight() == output_height); output.bind(); glViewport(0, 0, output.getWidth(), output.getHeight()); pipeline.bind(); glUniformMatrix3fv(pipeline_transform_location, 1, GL_FALSE, &transform[0][0]); input.bind(0u); glUniform1i(pipeline_source_location, 0u); rectangle->draw(); }
Tweak Webcam saturation and brightness
Tweak Webcam saturation and brightness
C++
mit
luckyxxl/hfg-webcam-particles
f90f252170074dce3a083c848e7d7f433b6ef242
modules/common/filters/digital_filter_coefficients.cc
modules/common/filters/digital_filter_coefficients.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. 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 "modules/common/filters/digital_filter_coefficients.h" #include <cmath> #include <vector> namespace apollo { namespace common { void LpfCoefficients(const double ts, const double cutoff_freq, std::vector<double> *denominators, std::vector<double> *numerators) { denominators->clear(); numerators->clear(); denominators->reserve(3); numerators->reserve(3); double wa = 2.0 * M_PI * cutoff_freq; // Analog frequency in rad/s double alpha = wa * ts / 2.0; // tan(Wd/2), Wd is discrete frequency double alpha_sqr = alpha * alpha; double tmp_term = std::sqrt(2.0) * alpha + alpha_sqr; double gain = alpha_sqr / (1.0 + tmp_term); denominators->push_back(1.0); denominators->push_back(2.0 * (alpha_sqr - 1.0) / (1.0 + tmp_term)); denominators->push_back((1.0 - std::sqrt(2.0) * alpha + alpha_sqr) / (1.0 + tmp_term)); numerators->push_back(gain); numerators->push_back(2.0 * gain); numerators->push_back(gain); return; } void LpFistOrderCoefficients(const double ts, const double settling_time, const double dead_time, std::vector<double> *denominators, std::vector<double> *numerators) { // sanity check if (ts <= 0.0 || settling_time < 0.0 || dead_time < 0.0) { AERROR << "time cannot be negative"; return; } const size_t k_d = static_cast<int>(dead_time / ts); double a_term; denominators->clear(); numerators->clear(); denominators->reserve(2); numerators->reserve(k_d); // size depends on dead-time if (settling_time == 0.0) { a_term = 0.0; } else { a_term = exp(-1 * ts/settling_time); } denominators->push_back(1.0); denominators->push_back(-1.0 * a_term); for (size_t i = 0; i < k_d-1; ++i) { numerators->push_back(0.0); } numerators->push_back(1 - a_term); return; } } // namespace common } // namespace apollo
/****************************************************************************** * Copyright 2017 The Apollo Authors. 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 "modules/common/filters/digital_filter_coefficients.h" #include <cmath> #include <vector> namespace apollo { namespace common { void LpfCoefficients(const double ts, const double cutoff_freq, std::vector<double> *denominators, std::vector<double> *numerators) { denominators->clear(); numerators->clear(); denominators->reserve(3); numerators->reserve(3); double wa = 2.0 * M_PI * cutoff_freq; // Analog frequency in rad/s double alpha = wa * ts / 2.0; // tan(Wd/2), Wd is discrete frequency double alpha_sqr = alpha * alpha; double tmp_term = std::sqrt(2.0) * alpha + alpha_sqr; double gain = alpha_sqr / (1.0 + tmp_term); denominators->push_back(1.0); denominators->push_back(2.0 * (alpha_sqr - 1.0) / (1.0 + tmp_term)); denominators->push_back((1.0 - std::sqrt(2.0) * alpha + alpha_sqr) / (1.0 + tmp_term)); numerators->push_back(gain); numerators->push_back(2.0 * gain); numerators->push_back(gain); return; } void LpFistOrderCoefficients(const double ts, const double settling_time, const double dead_time, std::vector<double> *denominators, std::vector<double> *numerators) { // sanity check if (ts <= 0.0 || settling_time < 0.0 || dead_time < 0.0) { AERROR << "time cannot be negative"; return; } const size_t k_d = static_cast<int>(dead_time / ts); double a_term; denominators->clear(); numerators->clear(); denominators->reserve(2); numerators->reserve(k_d); // size depends on dead-time if (settling_time == 0.0) { a_term = 0.0; } else { a_term = exp(-1 * ts/settling_time); } denominators->push_back(1.0); denominators->push_back(-1.0 * a_term); for (size_t i = 0; i < k_d-1; ++i) { numerators->push_back(0.0); } numerators->push_back(1 - a_term); } } // namespace common } // namespace apollo
Update digital_filter_coefficients.cc
Update digital_filter_coefficients.cc
C++
apache-2.0
ApolloAuto/apollo,jinghaomiao/apollo,ycool/apollo,jinghaomiao/apollo,ApolloAuto/apollo,xiaoxq/apollo,jinghaomiao/apollo,xiaoxq/apollo,xiaoxq/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,xiaoxq/apollo,ApolloAuto/apollo,ycool/apollo,jinghaomiao/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,xiaoxq/apollo,ycool/apollo
73506792636b3d5c2b4a6226d81967bc73dd73d2
src/api/c/vector_field.cpp
src/api/c/vector_field.cpp
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/graphics.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <graphics_common.hpp> #include <err_common.hpp> #include <backend.hpp> #include <vector_field.hpp> #include <transpose.hpp> #include <handle.hpp> using af::dim4; using namespace detail; #if defined(WITH_GRAPHICS) using namespace graphics; template<typename T> forge::Chart* setup_vector_field(const forge::Window* const window, const af_array points, const af_array directions, const af_cell* const props, const bool transpose_ = false) { Array<T> pIn = getArray<T>(points); Array<T> dIn = getArray<T>(directions); // do transpose if required if(transpose_) { pIn = transpose<T>(pIn, false); dIn = transpose<T>(dIn, false); } ForgeManager& fgMngr = ForgeManager::getInstance(); // Get the chart for the current grid position (if any) forge::Chart* chart = NULL; if(pIn.dims()[0] == 2) { if (props->col>-1 && props->row>-1) chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_2D); else chart = fgMngr.getChart(window, 0, 0, FG_CHART_2D); } else { if (props->col>-1 && props->row>-1) chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_3D); else chart = fgMngr.getChart(window, 0, 0, FG_CHART_3D); } forge::VectorField* vectorfield = fgMngr.getVectorField(chart, pIn.elements(), getGLType<T>()); vectorfield->setColor(1.0, 0.0, 0.0, 1.0); chart->setAxesTitles("X Axis", "Y Axis", "Z Axis"); copy_vector_field<T>(pIn, dIn, vectorfield); return chart; } af_err vectorFieldWrapper(const af_window wind, const af_array points, const af_array directions, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo pInfo = getInfo(points); af::dim4 pDims = pInfo.dims(); af_dtype pType = pInfo.getType(); ArrayInfo dInfo = getInfo(directions); af::dim4 dDims = dInfo.dims(); af_dtype dType = dInfo.getType(); DIM_ASSERT(0, pDims == dDims); DIM_ASSERT(0, pDims.ndims() == 2); DIM_ASSERT(0, pDims[1] == 2 || pDims[2] == 3); // Columns:P 2 means 2D and 3 means 3D TYPE_ASSERT(pType == dType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; switch(pType) { case f32: chart = setup_vector_field<float >(window, points, directions, props, true); break; case s32: chart = setup_vector_field<int >(window, points, directions, props, true); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props, true); break; case s16: chart = setup_vector_field<short >(window, points, directions, props, true); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props, true); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props, true); break; default: TYPE_ERROR(1, pType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); } CATCHALL; return AF_SUCCESS; } af_err vectorFieldWrapper(const af_window wind, const af_array xPoints, const af_array yPoints, const af_array zPoints, const af_array xDirs, const af_array yDirs, const af_array zDirs, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo xpInfo = getInfo(xPoints); ArrayInfo ypInfo = getInfo(yPoints); ArrayInfo zpInfo = getInfo(zPoints); af::dim4 xpDims = xpInfo.dims(); af::dim4 ypDims = ypInfo.dims(); af::dim4 zpDims = zpInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); af_dtype zpType = zpInfo.getType(); ArrayInfo xdInfo = getInfo(xDirs); ArrayInfo ydInfo = getInfo(yDirs); ArrayInfo zdInfo = getInfo(zDirs); af::dim4 xdDims = xdInfo.dims(); af::dim4 ydDims = ydInfo.dims(); af::dim4 zdDims = zdInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); af_dtype zdType = zdInfo.getType(); // Assert all arrays are equal dimensions DIM_ASSERT(1, xpDims == xdDims); DIM_ASSERT(2, ypDims == ydDims); DIM_ASSERT(3, zpDims == zdDims); DIM_ASSERT(1, xpDims == ypDims); DIM_ASSERT(1, xpDims == zpDims); // Verify vector DIM_ASSERT(1, xpDims.ndims() == 1); // Assert all arrays are equal types DIM_ASSERT(1, xpType == xdType); DIM_ASSERT(2, ypType == ydType); DIM_ASSERT(3, zpType == zdType); DIM_ASSERT(1, xpType == ypType); DIM_ASSERT(1, xpType == zpType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; // Join for set up vector af_array points = 0, directions = 0; af_array pIn[] = {xPoints, yPoints, zPoints}; af_array dIn[] = {xDirs, yDirs, zDirs}; AF_CHECK(af_join_many(&points, 0, 3, pIn)); AF_CHECK(af_join_many(&directions, 0, 3, dIn)); switch(xpType) { case f32: chart = setup_vector_field<float >(window, points, directions, props); break; case s32: chart = setup_vector_field<int >(window, points, directions, props); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props); break; case s16: chart = setup_vector_field<short >(window, points, directions, props); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props); break; default: TYPE_ERROR(1, xpType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); AF_CHECK(af_release_array(points)); AF_CHECK(af_release_array(directions)); } CATCHALL; return AF_SUCCESS; } af_err vectorFieldWrapper(const af_window wind, const af_array xPoints, const af_array yPoints, const af_array xDirs, const af_array yDirs, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo xpInfo = getInfo(xPoints); ArrayInfo ypInfo = getInfo(yPoints); af::dim4 xpDims = xpInfo.dims(); af::dim4 ypDims = ypInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); ArrayInfo xdInfo = getInfo(xDirs); ArrayInfo ydInfo = getInfo(yDirs); af::dim4 xdDims = xdInfo.dims(); af::dim4 ydDims = ydInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); // Assert all arrays are equal dimensions DIM_ASSERT(1, xpDims == xdDims); DIM_ASSERT(2, ypDims == ydDims); DIM_ASSERT(1, xpDims == ypDims); // Verify vector DIM_ASSERT(1, xpDims.ndims() == 1); // Assert all arrays are equal types DIM_ASSERT(1, xpType == xdType); DIM_ASSERT(2, ypType == ydType); DIM_ASSERT(1, xpType == ypType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; // Join for set up vector af_array points = 0, directions = 0; AF_CHECK(af_join(&points, 0, xPoints, yPoints)); AF_CHECK(af_join(&directions, 0, xDirs, yDirs)); switch(xpType) { case f32: chart = setup_vector_field<float >(window, points, directions, props); break; case s32: chart = setup_vector_field<int >(window, points, directions, props); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props); break; case s16: chart = setup_vector_field<short >(window, points, directions, props); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props); break; default: TYPE_ERROR(1, xpType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); AF_CHECK(af_release_array(points)); AF_CHECK(af_release_array(directions)); } CATCHALL; return AF_SUCCESS; } #endif // WITH_GRAPHICS // ADD THIS TO UNIFIED af_err af_draw_vector_field_nd(const af_window wind, const af_array points, const af_array directions, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, points, directions, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif } af_err af_draw_vector_field_3d( const af_window wind, const af_array xPoints, const af_array yPoints, const af_array zPoints, const af_array xDirs, const af_array yDirs, const af_array zDirs, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, xPoints, yPoints, zPoints, xDirs, yDirs, zDirs, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif } af_err af_draw_vector_field_2d( const af_window wind, const af_array xPoints, const af_array yPoints, const af_array xDirs, const af_array yDirs, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, xPoints, yPoints, xDirs, yDirs, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif }
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/graphics.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <graphics_common.hpp> #include <err_common.hpp> #include <backend.hpp> #include <vector_field.hpp> #include <transpose.hpp> #include <handle.hpp> using af::dim4; using namespace detail; #if defined(WITH_GRAPHICS) using namespace graphics; template<typename T> forge::Chart* setup_vector_field(const forge::Window* const window, const af_array points, const af_array directions, const af_cell* const props, const bool transpose_ = true) { Array<T> pIn = getArray<T>(points); Array<T> dIn = getArray<T>(directions); // do transpose if required if(transpose_) { pIn = transpose<T>(pIn, false); dIn = transpose<T>(dIn, false); } ForgeManager& fgMngr = ForgeManager::getInstance(); // Get the chart for the current grid position (if any) forge::Chart* chart = NULL; if(pIn.dims()[0] == 2) { if (props->col>-1 && props->row>-1) chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_2D); else chart = fgMngr.getChart(window, 0, 0, FG_CHART_2D); } else { if (props->col>-1 && props->row>-1) chart = fgMngr.getChart(window, props->row, props->col, FG_CHART_3D); else chart = fgMngr.getChart(window, 0, 0, FG_CHART_3D); } forge::VectorField* vectorfield = fgMngr.getVectorField(chart, pIn.dims()[1], getGLType<T>()); vectorfield->setColor(1.0, 0.0, 0.0, 1.0); chart->setAxesTitles("X Axis", "Y Axis", "Z Axis"); copy_vector_field<T>(pIn, dIn, vectorfield); return chart; } af_err vectorFieldWrapper(const af_window wind, const af_array points, const af_array directions, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo pInfo = getInfo(points); af::dim4 pDims = pInfo.dims(); af_dtype pType = pInfo.getType(); ArrayInfo dInfo = getInfo(directions); af::dim4 dDims = dInfo.dims(); af_dtype dType = dInfo.getType(); DIM_ASSERT(0, pDims == dDims); DIM_ASSERT(0, pDims.ndims() == 2); DIM_ASSERT(0, pDims[1] == 2 || pDims[1] == 3); // Columns:P 2 means 2D and 3 means 3D TYPE_ASSERT(pType == dType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; switch(pType) { case f32: chart = setup_vector_field<float >(window, points, directions, props); break; case s32: chart = setup_vector_field<int >(window, points, directions, props); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props); break; case s16: chart = setup_vector_field<short >(window, points, directions, props); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props); break; default: TYPE_ERROR(1, pType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); } CATCHALL; return AF_SUCCESS; } af_err vectorFieldWrapper(const af_window wind, const af_array xPoints, const af_array yPoints, const af_array zPoints, const af_array xDirs, const af_array yDirs, const af_array zDirs, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo xpInfo = getInfo(xPoints); ArrayInfo ypInfo = getInfo(yPoints); ArrayInfo zpInfo = getInfo(zPoints); af::dim4 xpDims = xpInfo.dims(); af::dim4 ypDims = ypInfo.dims(); af::dim4 zpDims = zpInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); af_dtype zpType = zpInfo.getType(); ArrayInfo xdInfo = getInfo(xDirs); ArrayInfo ydInfo = getInfo(yDirs); ArrayInfo zdInfo = getInfo(zDirs); af::dim4 xdDims = xdInfo.dims(); af::dim4 ydDims = ydInfo.dims(); af::dim4 zdDims = zdInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); af_dtype zdType = zdInfo.getType(); // Assert all arrays are equal dimensions DIM_ASSERT(1, xpDims == xdDims); DIM_ASSERT(2, ypDims == ydDims); DIM_ASSERT(3, zpDims == zdDims); DIM_ASSERT(1, xpDims == ypDims); DIM_ASSERT(1, xpDims == zpDims); // Verify vector DIM_ASSERT(1, xpDims.ndims() == 1); // Assert all arrays are equal types DIM_ASSERT(1, xpType == xdType); DIM_ASSERT(2, ypType == ydType); DIM_ASSERT(3, zpType == zdType); DIM_ASSERT(1, xpType == ypType); DIM_ASSERT(1, xpType == zpType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; // Join for set up vector af_array points = 0, directions = 0; af_array pIn[] = {xPoints, yPoints, zPoints}; af_array dIn[] = {xDirs, yDirs, zDirs}; AF_CHECK(af_join_many(&points, 1, 3, pIn)); AF_CHECK(af_join_many(&directions, 1, 3, dIn)); switch(xpType) { case f32: chart = setup_vector_field<float >(window, points, directions, props); break; case s32: chart = setup_vector_field<int >(window, points, directions, props); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props); break; case s16: chart = setup_vector_field<short >(window, points, directions, props); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props); break; default: TYPE_ERROR(1, xpType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); AF_CHECK(af_release_array(points)); AF_CHECK(af_release_array(directions)); } CATCHALL; return AF_SUCCESS; } af_err vectorFieldWrapper(const af_window wind, const af_array xPoints, const af_array yPoints, const af_array xDirs, const af_array yDirs, const af_cell* const props) { if(wind==0) { AF_RETURN_ERROR("Not a valid window", AF_SUCCESS); } try { ArrayInfo xpInfo = getInfo(xPoints); ArrayInfo ypInfo = getInfo(yPoints); af::dim4 xpDims = xpInfo.dims(); af::dim4 ypDims = ypInfo.dims(); af_dtype xpType = xpInfo.getType(); af_dtype ypType = ypInfo.getType(); ArrayInfo xdInfo = getInfo(xDirs); ArrayInfo ydInfo = getInfo(yDirs); af::dim4 xdDims = xdInfo.dims(); af::dim4 ydDims = ydInfo.dims(); af_dtype xdType = xdInfo.getType(); af_dtype ydType = ydInfo.getType(); // Assert all arrays are equal dimensions DIM_ASSERT(1, xpDims == xdDims); DIM_ASSERT(2, ypDims == ydDims); DIM_ASSERT(1, xpDims == ypDims); // Verify vector DIM_ASSERT(1, xpDims.ndims() == 1); // Assert all arrays are equal types DIM_ASSERT(1, xpType == xdType); DIM_ASSERT(2, ypType == ydType); DIM_ASSERT(1, xpType == ypType); forge::Window* window = reinterpret_cast<forge::Window*>(wind); makeContextCurrent(window); forge::Chart* chart = NULL; // Join for set up vector af_array points = 0, directions = 0; AF_CHECK(af_join(&points, 1, xPoints, yPoints)); AF_CHECK(af_join(&directions, 1, xDirs, yDirs)); switch(xpType) { case f32: chart = setup_vector_field<float >(window, points, directions, props); break; case s32: chart = setup_vector_field<int >(window, points, directions, props); break; case u32: chart = setup_vector_field<uint >(window, points, directions, props); break; case s16: chart = setup_vector_field<short >(window, points, directions, props); break; case u16: chart = setup_vector_field<ushort >(window, points, directions, props); break; case u8 : chart = setup_vector_field<uchar >(window, points, directions, props); break; default: TYPE_ERROR(1, xpType); } // Window's draw function requires either image or chart if (props->col > -1 && props->row > -1) window->draw(props->col, props->row, *chart, props->title); else window->draw(*chart); AF_CHECK(af_release_array(points)); AF_CHECK(af_release_array(directions)); } CATCHALL; return AF_SUCCESS; } #endif // WITH_GRAPHICS // ADD THIS TO UNIFIED af_err af_draw_vector_field_nd(const af_window wind, const af_array points, const af_array directions, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, points, directions, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif } af_err af_draw_vector_field_3d( const af_window wind, const af_array xPoints, const af_array yPoints, const af_array zPoints, const af_array xDirs, const af_array yDirs, const af_array zDirs, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, xPoints, yPoints, zPoints, xDirs, yDirs, zDirs, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif } af_err af_draw_vector_field_2d( const af_window wind, const af_array xPoints, const af_array yPoints, const af_array xDirs, const af_array yDirs, const af_cell* const props) { #if defined(WITH_GRAPHICS) return vectorFieldWrapper(wind, xPoints, yPoints, xDirs, yDirs, props); #else AF_RETURN_ERROR("ArrayFire compiled without graphics support", AF_ERR_NO_GFX); #endif }
Fix element count in vector field
Fix element count in vector field
C++
bsd-3-clause
arrayfire/arrayfire,umar456/arrayfire,shehzan10/arrayfire,arrayfire/arrayfire,munnybearz/arrayfire,umar456/arrayfire,9prady9/arrayfire,victorv/arrayfire,shehzan10/arrayfire,shehzan10/arrayfire,umar456/arrayfire,umar456/arrayfire,marbre/arrayfire,marbre/arrayfire,marbre/arrayfire,9prady9/arrayfire,victorv/arrayfire,victorv/arrayfire,munnybearz/arrayfire,marbre/arrayfire,9prady9/arrayfire,arrayfire/arrayfire,munnybearz/arrayfire,victorv/arrayfire,shehzan10/arrayfire,arrayfire/arrayfire,9prady9/arrayfire
9ac12dba8f723394ea0c80068962506572e882f9
src/api/wayfire/plugin.hpp
src/api/wayfire/plugin.hpp
#ifndef PLUGIN_H #define PLUGIN_H #include <functional> #include <memory> #include "wayfire/util.hpp" #include "wayfire/bindings.hpp" extern "C" { #include <wlr/types/wlr_input_device.h> } class wayfire_config; namespace wf { class output_t; /** * Plugins can set their capabilities to indicate what kind of plugin they are. * At any point, only one plugin with a given capability can be active on its * output (although multiple plugins with the same capability can be loaded). */ enum plugin_capabilities_t { /** The plugin provides view decorations */ CAPABILITY_VIEW_DECORATOR = 1 << 0, /** The plugin grabs input. * Required in order to use plugin_grab_interface_t::grab() */ CAPABILITY_GRAB_INPUT = 1 << 1, /** The plugin uses custom renderer */ CAPABILITY_CUSTOM_RENDERER = 1 << 2, /** The plugin manages the whole desktop, for ex. switches workspaces. */ CAPABILITY_MANAGE_DESKTOP = 1 << 3, /* Compound capabilities */ /** The plugin manages the whole compositor state */ CAPABILITY_MANAGE_COMPOSITOR = CAPABILITY_GRAB_INPUT | CAPABILITY_MANAGE_DESKTOP | CAPABILITY_CUSTOM_RENDERER, }; /** * The plugin grab interface is what the plugins use to announce themselves to * the core and other plugins as active, and to request to grab input. */ struct plugin_grab_interface_t { private: bool grabbed = false; public: /** The name of the plugin. Not important */ std::string name; /** The plugin capabilities. A bitmask of the values specified above */ uint32_t capabilities; /** The output the grab interface is on */ wf::output_t * const output; plugin_grab_interface_t(wf::output_t *_output); /** * Grab the input on the output. Requires CAPABILITY_GRAB_INPUT. * On successful grab, core will reset keyboard/pointer/touch focus. * * @return True if input was successfully grabbed. */ bool grab(); /** @return If the grab interface is grabbed */ bool is_grabbed(); /** Ungrab input, if it is grabbed. */ void ungrab(); /** * When grabbed, core will redirect all input events to the grabbing plugin. * The grabbing plugin can subscribe to different input events by setting * the callbacks below. */ struct { struct { std::function<void(wlr_event_pointer_axis*)> axis; std::function<void(uint32_t, uint32_t)> button; // button, state std::function<void(int32_t, int32_t)> motion; // x, y std::function<void(wlr_event_pointer_motion*)> relative_motion; } pointer; struct { std::function<void(uint32_t,uint32_t)> key; // button, state std::function<void(uint32_t,uint32_t)> mod; // modifier, state } keyboard; struct { std::function<void(int32_t, int32_t, int32_t)> down; // id, x, y std::function<void(int32_t)> up; // id std::function<void(int32_t, int32_t, int32_t)> motion; // id, x, y } touch; /** * Each plugin might be deactivated forcefully, for example when the * desktop is locked. Plugins MUST honor this signal and exit their * grabs/renderers immediately. * * Note that cancel() is emitted even when the plugin is just activated * without grabbing input. */ std::function<void()> cancel; } callbacks; }; using plugin_grab_interface_uptr = std::unique_ptr<plugin_grab_interface_t>; class plugin_interface_t { public: /** * The output this plugin is running on. Initialized by core. * Each output has its own set of plugin instances. This way, a plugin * rarely if ever needs to care about multi-monitor setups. */ wf::output_t *output; /** * The grab interface of the plugin, initialized by core. */ std::unique_ptr<plugin_grab_interface_t> grab_interface; /** * The init method is the entry of the plugin. In the init() method, the * plugin should register all bindings it provides, connect to signals, etc. */ virtual void init() = 0; /** * The fini method is called when a plugin is unloaded. It should clean up * all global state it has set (for ex. signal callbacks, bindings, ...), * because the plugin will be freed after this. */ virtual void fini(); /** * A plugin can request that it is never unloaded, even if it is removed * from the config's plugin list. * * Note that unloading a plugin is sometimes unavoidable, for ex. when the * output the plugin is running on is destroyed. So non-unloadable plugins * should still provide proper fini() methods. */ virtual bool is_unloadable() { return true; } virtual ~plugin_interface_t(); /** Handle to the plugin's .so file, used by the plugin loader */ void *handle = NULL; }; } /** * Each plugin must provide a function which instantiates the plugin's class * and returns the instance. * * This function must have the name newInstance() and should be declared with * extern "C" so that the loader can find it. */ using wayfire_plugin_load_func = wf::plugin_interface_t* (*)(); /** The version of Wayfire's API/ABI */ constexpr uint32_t WAYFIRE_API_ABI_VERSION = 2020'04'03; /** * Each plugin must also provide a function which returns the Wayfire API/ABI * that it was compiled with. * * This function must have the name getWayfireVersion() and should be declared * with extern "C" so that the loader can find it. */ using wayfire_plugin_version_func = uint32_t (*)(); /** A macro to declare the necessary functions, given the plugin class name */ #define DECLARE_WAYFIRE_PLUGIN(PluginClass) \ extern "C" \ {\ wf::plugin_interface_t* newInstance() { return new PluginClass; } \ uint32_t getWayfireVersion() { return WAYFIRE_API_ABI_VERSION; } \ } #endif
#ifndef PLUGIN_H #define PLUGIN_H #include <functional> #include <memory> #include "wayfire/util.hpp" #include "wayfire/bindings.hpp" extern "C" { #include <wlr/types/wlr_input_device.h> } class wayfire_config; namespace wf { class output_t; /** * Plugins can set their capabilities to indicate what kind of plugin they are. * At any point, only one plugin with a given capability can be active on its * output (although multiple plugins with the same capability can be loaded). */ enum plugin_capabilities_t { /** The plugin provides view decorations */ CAPABILITY_VIEW_DECORATOR = 1 << 0, /** The plugin grabs input. * Required in order to use plugin_grab_interface_t::grab() */ CAPABILITY_GRAB_INPUT = 1 << 1, /** The plugin uses custom renderer */ CAPABILITY_CUSTOM_RENDERER = 1 << 2, /** The plugin manages the whole desktop, for ex. switches workspaces. */ CAPABILITY_MANAGE_DESKTOP = 1 << 3, /* Compound capabilities */ /** The plugin manages the whole compositor state */ CAPABILITY_MANAGE_COMPOSITOR = CAPABILITY_GRAB_INPUT | CAPABILITY_MANAGE_DESKTOP | CAPABILITY_CUSTOM_RENDERER, }; /** * The plugin grab interface is what the plugins use to announce themselves to * the core and other plugins as active, and to request to grab input. */ struct plugin_grab_interface_t { private: bool grabbed = false; public: /** The name of the plugin. Not important */ std::string name; /** The plugin capabilities. A bitmask of the values specified above */ uint32_t capabilities; /** The output the grab interface is on */ wf::output_t * const output; plugin_grab_interface_t(wf::output_t *_output); /** * Grab the input on the output. Requires CAPABILITY_GRAB_INPUT. * On successful grab, core will reset keyboard/pointer/touch focus. * * @return True if input was successfully grabbed. */ bool grab(); /** @return If the grab interface is grabbed */ bool is_grabbed(); /** Ungrab input, if it is grabbed. */ void ungrab(); /** * When grabbed, core will redirect all input events to the grabbing plugin. * The grabbing plugin can subscribe to different input events by setting * the callbacks below. */ struct { struct { std::function<void(wlr_event_pointer_axis*)> axis; std::function<void(uint32_t, uint32_t)> button; // button, state std::function<void(int32_t, int32_t)> motion; // x, y std::function<void(wlr_event_pointer_motion*)> relative_motion; } pointer; struct { std::function<void(uint32_t,uint32_t)> key; // button, state std::function<void(uint32_t,uint32_t)> mod; // modifier, state } keyboard; struct { std::function<void(int32_t, int32_t, int32_t)> down; // id, x, y std::function<void(int32_t)> up; // id std::function<void(int32_t, int32_t, int32_t)> motion; // id, x, y } touch; /** * Each plugin might be deactivated forcefully, for example when the * desktop is locked. Plugins MUST honor this signal and exit their * grabs/renderers immediately. * * Note that cancel() is emitted even when the plugin is just activated * without grabbing input. */ std::function<void()> cancel; } callbacks; }; using plugin_grab_interface_uptr = std::unique_ptr<plugin_grab_interface_t>; class plugin_interface_t { public: /** * The output this plugin is running on. Initialized by core. * Each output has its own set of plugin instances. This way, a plugin * rarely if ever needs to care about multi-monitor setups. */ wf::output_t *output; /** * The grab interface of the plugin, initialized by core. */ std::unique_ptr<plugin_grab_interface_t> grab_interface; /** * The init method is the entry of the plugin. In the init() method, the * plugin should register all bindings it provides, connect to signals, etc. */ virtual void init() = 0; /** * The fini method is called when a plugin is unloaded. It should clean up * all global state it has set (for ex. signal callbacks, bindings, ...), * because the plugin will be freed after this. */ virtual void fini(); /** * A plugin can request that it is never unloaded, even if it is removed * from the config's plugin list. * * Note that unloading a plugin is sometimes unavoidable, for ex. when the * output the plugin is running on is destroyed. So non-unloadable plugins * should still provide proper fini() methods. */ virtual bool is_unloadable() { return true; } virtual ~plugin_interface_t(); /** Handle to the plugin's .so file, used by the plugin loader */ void *handle = NULL; }; } /** * Each plugin must provide a function which instantiates the plugin's class * and returns the instance. * * This function must have the name newInstance() and should be declared with * extern "C" so that the loader can find it. */ using wayfire_plugin_load_func = wf::plugin_interface_t* (*)(); /** The version of Wayfire's API/ABI */ constexpr uint32_t WAYFIRE_API_ABI_VERSION = 2020'04'04; /** * Each plugin must also provide a function which returns the Wayfire API/ABI * that it was compiled with. * * This function must have the name getWayfireVersion() and should be declared * with extern "C" so that the loader can find it. */ using wayfire_plugin_version_func = uint32_t (*)(); /** A macro to declare the necessary functions, given the plugin class name */ #define DECLARE_WAYFIRE_PLUGIN(PluginClass) \ extern "C" \ {\ wf::plugin_interface_t* newInstance() { return new PluginClass; } \ uint32_t getWayfireVersion() { return WAYFIRE_API_ABI_VERSION; } \ } #endif
update ABI version
api: update ABI version
C++
mit
ammen99/wayfire,ammen99/wayfire
9b845c6e367d95c442940578bfc18559d86ec52c
net/disk_cache/file_posix.cc
net/disk_cache/file_posix.cc
// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/file.h" #include <fcntl.h> #include "base/logging.h" #include "base/threading/worker_pool.h" #include "net/disk_cache/disk_cache.h" #include "net/disk_cache/in_flight_io.h" namespace { // This class represents a single asynchronous IO operation while it is being // bounced between threads. class FileBackgroundIO : public disk_cache::BackgroundIO { public: // Other than the actual parameters for the IO operation (including the // |callback| that must be notified at the end), we need the controller that // is keeping track of all operations. When done, we notify the controller // (we do NOT invoke the callback), in the worker thead that completed the // operation. FileBackgroundIO(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback, disk_cache::InFlightIO* controller) : disk_cache::BackgroundIO(controller), callback_(callback), file_(file), buf_(buf), buf_len_(buf_len), offset_(offset) { } disk_cache::FileIOCallback* callback() { return callback_; } disk_cache::File* file() { return file_; } // Read and Write are the operations that can be performed asynchronously. // The actual parameters for the operation are setup in the constructor of // the object. Both methods should be called from a worker thread, by posting // a task to the WorkerPool (they are RunnableMethods). When finished, // controller->OnIOComplete() is called. void Read(); void Write(); private: ~FileBackgroundIO() {} disk_cache::FileIOCallback* callback_; disk_cache::File* file_; const void* buf_; size_t buf_len_; size_t offset_; DISALLOW_COPY_AND_ASSIGN(FileBackgroundIO); }; // The specialized controller that keeps track of current operations. class FileInFlightIO : public disk_cache::InFlightIO { public: FileInFlightIO() {} ~FileInFlightIO() {} // These methods start an asynchronous operation. The arguments have the same // semantics of the File asynchronous operations, with the exception that the // operation never finishes synchronously. void PostRead(disk_cache::File* file, void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback); void PostWrite(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback); protected: // Invokes the users' completion callback at the end of the IO operation. // |cancel| is true if the actual task posted to the thread is still // queued (because we are inside WaitForPendingIO), and false if said task is // the one performing the call. virtual void OnOperationComplete(disk_cache::BackgroundIO* operation, bool cancel); private: DISALLOW_COPY_AND_ASSIGN(FileInFlightIO); }; // --------------------------------------------------------------------------- // Runs on a worker thread. void FileBackgroundIO::Read() { if (file_->Read(const_cast<void*>(buf_), buf_len_, offset_)) { result_ = static_cast<int>(buf_len_); } else { result_ = -1; } controller_->OnIOComplete(this); } // Runs on a worker thread. void FileBackgroundIO::Write() { bool rv = file_->Write(buf_, buf_len_, offset_); result_ = rv ? static_cast<int>(buf_len_) : -1; controller_->OnIOComplete(this); } // --------------------------------------------------------------------------- void FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback *callback) { scoped_refptr<FileBackgroundIO> operation( new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); file->AddRef(); // Balanced on OnOperationComplete() base::WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(operation.get(), &FileBackgroundIO::Read), true); OnOperationPosted(operation); } void FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback) { scoped_refptr<FileBackgroundIO> operation( new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); file->AddRef(); // Balanced on OnOperationComplete() base::WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(operation.get(), &FileBackgroundIO::Write), true); OnOperationPosted(operation); } // Runs on the IO thread. void FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation, bool cancel) { FileBackgroundIO* op = static_cast<FileBackgroundIO*>(operation); disk_cache::FileIOCallback* callback = op->callback(); int bytes = operation->result(); // Release the references acquired in PostRead / PostWrite. op->file()->Release(); callback->OnFileIOComplete(bytes); } // A static object tha will broker all async operations. FileInFlightIO* s_file_operations = NULL; // Returns the current FileInFlightIO. FileInFlightIO* GetFileInFlightIO() { if (!s_file_operations) { s_file_operations = new FileInFlightIO; } return s_file_operations; } // Deletes the current FileInFlightIO. void DeleteFileInFlightIO() { DCHECK(s_file_operations); delete s_file_operations; s_file_operations = NULL; } } // namespace namespace disk_cache { File::File(base::PlatformFile file) : init_(true), mixed_(true), platform_file_(file), sync_platform_file_(base::kInvalidPlatformFileValue) { } bool File::Init(const FilePath& name) { if (init_) return false; int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE; platform_file_ = base::CreatePlatformFile(name, flags, NULL, NULL); if (platform_file_ < 0) { platform_file_ = 0; return false; } init_ = true; return true; } base::PlatformFile File::platform_file() const { return platform_file_; } bool File::IsValid() const { if (!init_) return false; return (base::kInvalidPlatformFileValue != platform_file_); } bool File::Read(void* buffer, size_t buffer_len, size_t offset) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > LONG_MAX) return false; int ret = pread(platform_file_, buffer, buffer_len, offset); return (static_cast<size_t>(ret) == buffer_len); } bool File::Write(const void* buffer, size_t buffer_len, size_t offset) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; int ret = pwrite(platform_file_, buffer, buffer_len, offset); return (static_cast<size_t>(ret) == buffer_len); } // We have to increase the ref counter of the file before performing the IO to // prevent the completion to happen with an invalid handle (if the file is // closed while the IO is in flight). bool File::Read(void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (!callback) { if (completed) *completed = true; return Read(buffer, buffer_len, offset); } if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; GetFileInFlightIO()->PostRead(this, buffer, buffer_len, offset, callback); *completed = false; return true; } bool File::Write(const void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (!callback) { if (completed) *completed = true; return Write(buffer, buffer_len, offset); } return AsyncWrite(buffer, buffer_len, offset, callback, completed); } bool File::SetLength(size_t length) { DCHECK(init_); if (length > ULONG_MAX) return false; return 0 == ftruncate(platform_file_, length); } size_t File::GetLength() { DCHECK(init_); size_t ret = lseek(platform_file_, 0, SEEK_END); return ret; } // Static. void File::WaitForPendingIO(int* num_pending_io) { // We may be running unit tests so we should allow be able to reset the // message loop. GetFileInFlightIO()->WaitForPendingIO(); DeleteFileInFlightIO(); } File::~File() { if (IsValid()) close(platform_file_); } bool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; GetFileInFlightIO()->PostWrite(this, buffer, buffer_len, offset, callback); if (completed) *completed = false; return true; } } // namespace disk_cache
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/file.h" #include <fcntl.h> #include "base/logging.h" #include "base/threading/worker_pool.h" #include "net/disk_cache/disk_cache.h" #include "net/disk_cache/in_flight_io.h" namespace { // This class represents a single asynchronous IO operation while it is being // bounced between threads. class FileBackgroundIO : public disk_cache::BackgroundIO { public: // Other than the actual parameters for the IO operation (including the // |callback| that must be notified at the end), we need the controller that // is keeping track of all operations. When done, we notify the controller // (we do NOT invoke the callback), in the worker thead that completed the // operation. FileBackgroundIO(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback, disk_cache::InFlightIO* controller) : disk_cache::BackgroundIO(controller), callback_(callback), file_(file), buf_(buf), buf_len_(buf_len), offset_(offset) { } disk_cache::FileIOCallback* callback() { return callback_; } disk_cache::File* file() { return file_; } // Read and Write are the operations that can be performed asynchronously. // The actual parameters for the operation are setup in the constructor of // the object. Both methods should be called from a worker thread, by posting // a task to the WorkerPool (they are RunnableMethods). When finished, // controller->OnIOComplete() is called. void Read(); void Write(); private: ~FileBackgroundIO() {} disk_cache::FileIOCallback* callback_; disk_cache::File* file_; const void* buf_; size_t buf_len_; size_t offset_; DISALLOW_COPY_AND_ASSIGN(FileBackgroundIO); }; // The specialized controller that keeps track of current operations. class FileInFlightIO : public disk_cache::InFlightIO { public: FileInFlightIO() {} ~FileInFlightIO() {} // These methods start an asynchronous operation. The arguments have the same // semantics of the File asynchronous operations, with the exception that the // operation never finishes synchronously. void PostRead(disk_cache::File* file, void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback); void PostWrite(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback); protected: // Invokes the users' completion callback at the end of the IO operation. // |cancel| is true if the actual task posted to the thread is still // queued (because we are inside WaitForPendingIO), and false if said task is // the one performing the call. virtual void OnOperationComplete(disk_cache::BackgroundIO* operation, bool cancel); private: DISALLOW_COPY_AND_ASSIGN(FileInFlightIO); }; // --------------------------------------------------------------------------- // Runs on a worker thread. void FileBackgroundIO::Read() { if (file_->Read(const_cast<void*>(buf_), buf_len_, offset_)) { result_ = static_cast<int>(buf_len_); } else { result_ = -1; } controller_->OnIOComplete(this); } // Runs on a worker thread. void FileBackgroundIO::Write() { bool rv = file_->Write(buf_, buf_len_, offset_); result_ = rv ? static_cast<int>(buf_len_) : -1; controller_->OnIOComplete(this); } // --------------------------------------------------------------------------- void FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback *callback) { scoped_refptr<FileBackgroundIO> operation( new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); file->AddRef(); // Balanced on OnOperationComplete() base::WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(operation.get(), &FileBackgroundIO::Read), true); OnOperationPosted(operation); } void FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback) { scoped_refptr<FileBackgroundIO> operation( new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); file->AddRef(); // Balanced on OnOperationComplete() base::WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(operation.get(), &FileBackgroundIO::Write), true); OnOperationPosted(operation); } // Runs on the IO thread. void FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation, bool cancel) { FileBackgroundIO* op = static_cast<FileBackgroundIO*>(operation); disk_cache::FileIOCallback* callback = op->callback(); int bytes = operation->result(); // Release the references acquired in PostRead / PostWrite. op->file()->Release(); callback->OnFileIOComplete(bytes); } // A static object tha will broker all async operations. FileInFlightIO* s_file_operations = NULL; // Returns the current FileInFlightIO. FileInFlightIO* GetFileInFlightIO() { if (!s_file_operations) { s_file_operations = new FileInFlightIO; } return s_file_operations; } // Deletes the current FileInFlightIO. void DeleteFileInFlightIO() { DCHECK(s_file_operations); delete s_file_operations; s_file_operations = NULL; } } // namespace namespace disk_cache { File::File(base::PlatformFile file) : init_(true), mixed_(true), platform_file_(file), sync_platform_file_(base::kInvalidPlatformFileValue) { } bool File::Init(const FilePath& name) { if (init_) return false; int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE; platform_file_ = base::CreatePlatformFile(name, flags, NULL, NULL); if (platform_file_ < 0) { platform_file_ = 0; return false; } init_ = true; return true; } base::PlatformFile File::platform_file() const { return platform_file_; } bool File::IsValid() const { if (!init_) return false; return (base::kInvalidPlatformFileValue != platform_file_); } bool File::Read(void* buffer, size_t buffer_len, size_t offset) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > LONG_MAX) return false; int ret = pread(platform_file_, buffer, buffer_len, offset); return (static_cast<size_t>(ret) == buffer_len); } bool File::Write(const void* buffer, size_t buffer_len, size_t offset) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; int ret = pwrite(platform_file_, buffer, buffer_len, offset); return (static_cast<size_t>(ret) == buffer_len); } // We have to increase the ref counter of the file before performing the IO to // prevent the completion to happen with an invalid handle (if the file is // closed while the IO is in flight). bool File::Read(void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (!callback) { if (completed) *completed = true; return Read(buffer, buffer_len, offset); } if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; GetFileInFlightIO()->PostRead(this, buffer, buffer_len, offset, callback); *completed = false; return true; } bool File::Write(const void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (!callback) { if (completed) *completed = true; return Write(buffer, buffer_len, offset); } return AsyncWrite(buffer, buffer_len, offset, callback, completed); } bool File::SetLength(size_t length) { DCHECK(init_); if (length > ULONG_MAX) return false; return 0 == ftruncate(platform_file_, length); } size_t File::GetLength() { DCHECK(init_); off_t ret = lseek(platform_file_, 0, SEEK_END); if (ret < 0) return 0; return ret; } // Static. void File::WaitForPendingIO(int* num_pending_io) { // We may be running unit tests so we should allow be able to reset the // message loop. GetFileInFlightIO()->WaitForPendingIO(); DeleteFileInFlightIO(); } File::~File() { if (IsValid()) close(platform_file_); } bool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset, FileIOCallback* callback, bool* completed) { DCHECK(init_); if (buffer_len > ULONG_MAX || offset > ULONG_MAX) return false; GetFileInFlightIO()->PostWrite(this, buffer, buffer_len, offset, callback); if (completed) *completed = false; return true; } } // namespace disk_cache
Check for negative lseek return valies in disk_cache::File::GetLength.
Coverity: Check for negative lseek return valies in disk_cache::File::GetLength. BUG=none TEST=none CID=11651 Review URL: http://codereview.chromium.org/7218019 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@89925 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,dednal/chromium.src,patrickm/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,ltilve/chromium,robclark/chromium,Pluto-tv/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,keishi/chromium,keishi/chromium,keishi/chromium,anirudhSK/chromium,ondra-novak/chromium.src,ltilve/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,rogerwang/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,rogerwang/chromium,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,rogerwang/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,Just-D/chromium-1,jaruba/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,dednal/chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,patrickm/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,keishi/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,robclark/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,littlstar/chromium.src,anirudhSK/chromium,rogerwang/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,ltilve/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,ltilve/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,anirudhSK/chromium,Just-D/chromium-1,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,Chilledheart/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,dednal/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,robclark/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,patrickm/chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,rogerwang/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,keishi/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,dednal/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dednal/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,patrickm/chromium.src,robclark/chromium,patrickm/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dednal/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,keishi/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,ondra-novak/chromium.src,keishi/chromium,rogerwang/chromium,patrickm/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,ondra-novak/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,M4sse/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,rogerwang/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk
85642a5132a478273a7217abbd0e71d3522d9081
src/values/symbol.cpp
src/values/symbol.cpp
#include "../values.hpp" #include <unordered_map> namespace rev { value_t::p Symbol_Printable_str(value_t::p self) { auto sym = as<sym_t>(self); if (sym->has_ns()) { return imu::nu<string_t>(sym->ns() + "/" + sym->name()); } return imu::nu<string_t>(sym->name()); } value_t::p Symbol_WithMeta_withmeta(value_t::p self, value_t::p m) { // FIXME: symbols are interned by default, so this would set the meta // of all symbols with this name. create a copy instead self->set_meta(m); return self; } value_t::p Keyword_Printable_str(value_t::p self) { auto kw = as<keyw_t>(self); if (kw->has_ns()) { return imu::nu<string_t>(":" + kw->ns() + "/" + kw->name()); } return imu::nu<string_t>(":" + kw->name()); } value_t::p Keyword_IFn_invoke2(value_t::p self, value_t::p m) { void* args[] = {(void*) m, (void*) self}; return protocol_t::dispatch(protocol_t::lookup, 0, args, 2); } value_t::p Keyword_IFn_invoke3(value_t::p self, value_t::p m, value_t::p d) { void* args[] = {(void*) m, (void*) self, (void*) d}; return protocol_t::dispatch(protocol_t::lookup, 0, args, 3); } struct type_t::impl_t Symbol_printable[] = { {0, (intptr_t) Symbol_Printable_str, 0, 0, 0, 0, 0, 0} }; struct type_t::impl_t Symbol_withmeta[] = { {0, 0, (intptr_t) Symbol_WithMeta_withmeta, 0, 0, 0, 0, 0} }; // struct type_t::impl_t Symbol_equiv[] = { // {0, 0, (intptr_t) Symbol_Equiv_equiv, 0, 0, 0, 0, 0} // }; struct type_t::ext_t Symbol_methods[] = { {protocol_t::str, Symbol_printable}, {protocol_t::withmeta, Symbol_withmeta} // {protocol_t::equiv, Symbol_equiv} }; struct type_t::impl_t Keyword_printable[] = { {0, (intptr_t) Keyword_Printable_str, 0, 0, 0, 0, 0, 0} }; struct type_t::impl_t Keyword_ifn[] = { {0, 0, (intptr_t) Keyword_IFn_invoke2, (intptr_t) Keyword_IFn_invoke3, 0, 0, 0, 0} }; // struct type_t::impl_t Keyword_equiv[] = { // {0, 0, (intptr_t) Keyword_Equiv_equiv, 0, 0, 0, 0, 0} // }; struct type_t::ext_t Keyword_methods[] = { {protocol_t::str, Keyword_printable}, {protocol_t::ifn, Keyword_ifn} //{protocol_t::equiv, Keyword_equiv} }; static const uint64_t sym_size = sizeof(Symbol_methods) / sizeof(Symbol_methods[0]); static const uint64_t kw_size = sizeof(Keyword_methods) / sizeof(Keyword_methods[0]); template<> type_t value_base_t<sym_t>::prototype("Symbol.0", Symbol_methods, sym_size); template<> type_t value_base_t<keyw_t>::prototype("Keyword.0", Keyword_methods, kw_size); template<> sym_base_t<sym_t>::p sym_base_t<sym_t>::intern(const std::string& fqn) { static std::unordered_map<std::string, sym_t::p> cache; auto& sym = cache[fqn]; return sym ? sym : (sym = imu::nu<sym_t>(fqn)); } template<> sym_base_t<sym_t>::p sym_base_t<sym_t>::intern( const std::string& ns, const std::string& name) { return intern(ns + "/" + name); } template<> sym_base_t<keyw_t>::p sym_base_t<keyw_t>::intern(const std::string& fqn) { static std::unordered_map<std::string, keyw_t::p> cache; auto& k = cache[fqn]; return k ? k : (k = imu::nu<keyw_t>(fqn)); } sym_t::p sym_t::true_ = sym_t::intern("true"); sym_t::p sym_t::false_ = sym_t::intern("false"); }
#include "../values.hpp" #include <unordered_map> namespace rev { value_t::p Symbol_Printable_str(value_t::p self) { auto sym = as<sym_t>(self); if (sym->has_ns()) { return imu::nu<string_t>(sym->ns() + "/" + sym->name()); } return imu::nu<string_t>(sym->name()); } value_t::p Symbol_WithMeta_withmeta(value_t::p self, value_t::p m) { // FIXME: symbols are interned by default, so this would set the meta // of all symbols with this name. create a copy instead self->set_meta(m); return self; } value_t::p Keyword_Printable_str(value_t::p self) { auto kw = as<keyw_t>(self); if (kw->has_ns()) { return imu::nu<string_t>(":" + kw->ns() + "/" + kw->name()); } return imu::nu<string_t>(":" + kw->name()); } value_t::p Keyword_IFn_invoke2(value_t::p self, value_t::p m) { if (m) { void* args[] = {(void*) m, (void*) self}; return protocol_t::dispatch(protocol_t::lookup, 0, args, 2); } return nullptr; } value_t::p Keyword_IFn_invoke3(value_t::p self, value_t::p m, value_t::p d) { if (m) { void* args[] = {(void*) m, (void*) self, (void*) d}; return protocol_t::dispatch(protocol_t::lookup, 0, args, 3); } return d; } struct type_t::impl_t Symbol_printable[] = { {0, (intptr_t) Symbol_Printable_str, 0, 0, 0, 0, 0, 0} }; struct type_t::impl_t Symbol_withmeta[] = { {0, 0, (intptr_t) Symbol_WithMeta_withmeta, 0, 0, 0, 0, 0} }; // struct type_t::impl_t Symbol_equiv[] = { // {0, 0, (intptr_t) Symbol_Equiv_equiv, 0, 0, 0, 0, 0} // }; struct type_t::ext_t Symbol_methods[] = { {protocol_t::str, Symbol_printable}, {protocol_t::withmeta, Symbol_withmeta} // {protocol_t::equiv, Symbol_equiv} }; struct type_t::impl_t Keyword_printable[] = { {0, (intptr_t) Keyword_Printable_str, 0, 0, 0, 0, 0, 0} }; struct type_t::impl_t Keyword_ifn[] = { {0, 0, (intptr_t) Keyword_IFn_invoke2, (intptr_t) Keyword_IFn_invoke3, 0, 0, 0, 0} }; // struct type_t::impl_t Keyword_equiv[] = { // {0, 0, (intptr_t) Keyword_Equiv_equiv, 0, 0, 0, 0, 0} // }; struct type_t::ext_t Keyword_methods[] = { {protocol_t::str, Keyword_printable}, {protocol_t::ifn, Keyword_ifn} //{protocol_t::equiv, Keyword_equiv} }; static const uint64_t sym_size = sizeof(Symbol_methods) / sizeof(Symbol_methods[0]); static const uint64_t kw_size = sizeof(Keyword_methods) / sizeof(Keyword_methods[0]); template<> type_t value_base_t<sym_t>::prototype("Symbol.0", Symbol_methods, sym_size); template<> type_t value_base_t<keyw_t>::prototype("Keyword.0", Keyword_methods, kw_size); template<> sym_base_t<sym_t>::p sym_base_t<sym_t>::intern(const std::string& fqn) { static std::unordered_map<std::string, sym_t::p> cache; auto& sym = cache[fqn]; return sym ? sym : (sym = imu::nu<sym_t>(fqn)); } template<> sym_base_t<sym_t>::p sym_base_t<sym_t>::intern( const std::string& ns, const std::string& name) { return intern(ns + "/" + name); } template<> sym_base_t<keyw_t>::p sym_base_t<keyw_t>::intern(const std::string& fqn) { static std::unordered_map<std::string, keyw_t::p> cache; auto& k = cache[fqn]; return k ? k : (k = imu::nu<keyw_t>(fqn)); } sym_t::p sym_t::true_ = sym_t::intern("true"); sym_t::p sym_t::false_ = sym_t::intern("false"); }
Handle nil maps in keyword dispatch
Handle nil maps in keyword dispatch
C++
mit
torque-project/rev
1ee08f736d5db4b8ef05fc91518dd155748ca42a
defaults/src/vespa/defaults.cpp
defaults/src/vespa/defaults.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "defaults.h" #include <stdlib.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <string> #include <vector> #include <unistd.h> #include <atomic> #include <pwd.h> namespace { #define HOST_BUF_SZ 1024 const char *defaultHome = "/opt/vespa"; const char *defaultUser = "vespa"; const char *defaultHost = "localhost"; int defaultWebServicePort = 8080; int defaultPortBase = 19000; int defaultPortConfigServerRpc = 0; int defaultPortConfigServerHttp = 0; int defaultPortConfigProxyRpc = 0; const char *defaultConfigServers = "localhost"; std::atomic<bool> initialized(false); long getNumFromEnv(const char *envName) { const char *env = getenv(envName); if (env != nullptr && *env != '\0') { char *endptr = nullptr; long num = strtol(env, &endptr, 10); if (endptr != nullptr && *endptr == '\0') { return num; } fprintf(stderr, "warning\tbad %s '%s' (ignored)\n", envName, env); } return -1; } void findDefaults() { if (initialized) return; const char *env = getenv("VESPA_HOME"); if (env != NULL && *env != '\0') { DIR *dp = NULL; if (*env == '/' || *env == '.') { dp = opendir(env); } if (dp != NULL) { defaultHome = env; // fprintf(stderr, "debug\tVESPA_HOME is '%s'\n", defaultHome); closedir(dp); } else { fprintf(stderr, "warning\tbad VESPA_HOME '%s' (ignored)\n", env); } } env = getenv("VESPA_USER"); if (env != NULL && *env != '\0') { if (getpwnam(env) == 0) { fprintf(stderr, "warning\tbad VESPA_USER '%s' (ignored)\n", env); } else { defaultUser = env; } } env = getenv("VESPA_HOSTNAME"); if (env != NULL && *env != '\0') { defaultHost = env; } long p = getNumFromEnv("VESPA_WEB_SERVICE_PORT"); if (p > 0) { // fprintf(stderr, "debug\tdefault web service port is '%ld'\n", p); defaultWebServicePort = p; } p = getNumFromEnv("VESPA_PORT_BASE"); if (p > 0) { // fprintf(stderr, "debug\tdefault port base is '%ld'\n", p); defaultPortBase = p; } defaultPortConfigServerRpc = defaultPortBase + 70; defaultPortConfigProxyRpc = defaultPortBase + 90; p = getNumFromEnv("port_configserver_rpc"); if (p > 0) { defaultPortConfigServerRpc = p; } defaultPortConfigServerHttp = defaultPortConfigServerRpc + 1; p = getNumFromEnv("port_configproxy_rpc"); if (p > 0) { defaultPortConfigProxyRpc = p; } env = getenv("VESPA_CONFIGSERVERS"); if (env == NULL || *env == '\0') { env = getenv("services__addr_configserver"); } if (env == NULL || *env == '\0') { env = getenv("vespa_base__addr_configserver"); } if (env == NULL || *env == '\0') { env = getenv("addr_configserver"); } if (env != NULL && *env != '\0') { // fprintf(stderr, "debug\tdefault configserver(s) is '%s'\n", env); defaultConfigServers = env; } initialized = true; } } namespace vespa { std::string myPath(const char *argv0) { if (argv0[0] == '/') return argv0; const char *pathEnv = getenv("PATH"); if (pathEnv != 0) { std::string path = pathEnv; size_t pos = 0; size_t colon; do { colon = path.find(':', pos); std::string pre = path.substr(pos, colon-pos); pos = colon+1; if (pre[0] == '/') { pre.append("/"); pre.append(argv0); if (access(pre.c_str(), X_OK) == 0) { return pre; } } } while (colon != std::string::npos); } return argv0; } void Defaults::bootstrap(const char *argv0) { if (getenv("VESPA_HOME") == 0) { std::string path = myPath(argv0); size_t slash = path.rfind('/'); if (slash != std::string::npos) { path.resize(slash); slash = path.rfind('/', slash-1); if (slash != std::string::npos) { const char *dirname = path.c_str() + slash; if (strncmp(dirname, "/bin", 4) == 0 || strncmp(dirname, "/sbin", 5) == 0) { path.resize(slash); } } std::string setting = "VESPA_HOME"; setting.append("="); setting.append(path); putenv(&setting[0]); } } initialized = false; } const char * Defaults::vespaHome() { findDefaults(); return defaultHome; } std::string Defaults::underVespaHome(const char *path) { if (path[0] == '/') { return path; } if (path[0] == '.' && path[1] == '/') { return path; } findDefaults(); std::string ret = defaultHome; ret += '/'; ret += path; return ret; } const char * Defaults::vespaUser() { findDefaults(); return defaultUser; } const char * Defaults::vespaHostname() { findDefaults(); return defaultHost; } int Defaults::vespaWebServicePort() { findDefaults(); return defaultWebServicePort; } int Defaults::vespaPortBase() { findDefaults(); return defaultPortBase; } std::vector<std::string> Defaults::vespaConfigServerHosts() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { ret.push_back("localhost"); } else { while (token != 0) { char *colon = strchr(token, ':'); if (colon != 0 && colon != token) { *colon = '\0'; } ret.push_back(token); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } int Defaults::vespaConfigServerRpcPort() { findDefaults(); return defaultPortConfigServerRpc; } std::vector<std::string> Defaults::vespaConfigServerRpcAddrs() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { std::string one = "tcp/localhost:"; one += std::to_string(defaultPortConfigServerRpc); ret.push_back(one); } else { while (token != 0) { std::string one = "tcp/"; one += token; if (strchr(token, ':') == 0) { one += ":"; one += std::to_string(defaultPortConfigServerRpc); } ret.push_back(one); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } std::vector<std::string> Defaults::vespaConfigServerRestUrls() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { std::string one = "http://localhost:"; one += std::to_string(defaultPortConfigServerHttp); ret.push_back(one); } else { while (token != 0) { std::string one = "http://"; char *colon = strchr(token, ':'); if (colon != 0 && colon != token) { *colon = '\0'; } one += token; one += ":"; one += std::to_string(defaultPortConfigServerHttp); one += "/"; ret.push_back(one); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } std::string Defaults::vespaConfigProxyRpcAddr() { findDefaults(); std::string ret = "tcp/localhost:"; ret += std::to_string(defaultPortConfigProxyRpc); return ret; } std::vector<std::string> Defaults::vespaConfigSourcesRpcAddrs() { findDefaults(); std::vector<std::string> ret; ret.push_back(vespaConfigProxyRpcAddr()); for (std::string v : vespaConfigServerRpcAddrs()) { ret.push_back(v); } return ret; } } // namespace vespa
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "defaults.h" #include <stdlib.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <string> #include <vector> #include <unistd.h> #include <atomic> #include <pwd.h> namespace { #define HOST_BUF_SZ 1024 const char *defaultHome = 0; const char *defaultUser = 0; const char *defaultHost = 0; int defaultWebServicePort = 0; int defaultPortBase = 0; int defaultPortConfigServerRpc = 0; int defaultPortConfigServerHttp = 0; int defaultPortConfigProxyRpc = 0; const char *defaultConfigServers = 0; std::atomic<bool> initialized(false); long getNumFromEnv(const char *envName) { const char *env = getenv(envName); if (env != nullptr && *env != '\0') { char *endptr = nullptr; long num = strtol(env, &endptr, 10); if (endptr != nullptr && *endptr == '\0') { return num; } fprintf(stderr, "warning\tbad %s '%s' (ignored)\n", envName, env); } return -1; } const char *findVespaHome(const char *defHome) { const char *env = getenv("VESPA_HOME"); if (env != NULL && *env != '\0') { DIR *dp = NULL; if (*env == '/' || *env == '.') { dp = opendir(env); } if (dp != NULL) { // fprintf(stderr, "debug\tVESPA_HOME is '%s'\n", env); closedir(dp); return env; } else { fprintf(stderr, "warning\tbad VESPA_HOME '%s' (ignored)\n", env); } } return defHome; } const char *findVespaUser(const char *defUser) { const char *env = getenv("VESPA_USER"); if (env != NULL && *env != '\0') { if (getpwnam(env) == 0) { fprintf(stderr, "warning\tbad VESPA_USER '%s' (ignored)\n", env); } else { return env; } } return defUser; } const char *findHostname(const char *defHost) { const char *env = getenv("VESPA_HOSTNAME"); if (env != NULL && *env != '\0') { return env; } return defHost; } int findWebServicePort(int defPort) { long p = getNumFromEnv("VESPA_WEB_SERVICE_PORT"); if (p > 0) { // fprintf(stderr, "debug\tdefault web service port is '%ld'\n", p); return p; } return defPort; } int findVespaPortBase(int defPort) { long p = getNumFromEnv("VESPA_PORT_BASE"); if (p > 0) { // fprintf(stderr, "debug\tdefault port base is '%ld'\n", p); return p; } return defPort; } int findConfigServerPort(int defPort) { long p = getNumFromEnv("port_configserver_rpc"); if (p > 0) { return p; } return defPort; } int findConfigProxyPort(int defPort) { long p = getNumFromEnv("port_configproxy_rpc"); if (p > 0) { return p; } return defPort; } const char *findConfigServers(const char *defServers) { const char *env = getenv("VESPA_CONFIGSERVERS"); if (env == NULL || *env == '\0') { env = getenv("services__addr_configserver"); } if (env == NULL || *env == '\0') { env = getenv("vespa_base__addr_configserver"); } if (env == NULL || *env == '\0') { env = getenv("addr_configserver"); } if (env != NULL && *env != '\0') { // fprintf(stderr, "debug\tdefault configserver(s) is '%s'\n", env); return env; } return defServers; } void findDefaults() { if (initialized) return; defaultHome = findVespaHome("/opt/vespa"); defaultUser = findVespaUser("vespa"); defaultHost = findHostname("localhost"); defaultWebServicePort = findWebServicePort(8080); defaultPortBase = findVespaPortBase(19000); defaultPortConfigServerRpc = findConfigServerPort(defaultPortBase + 70); defaultPortConfigServerHttp = defaultPortConfigServerRpc + 1; defaultPortConfigProxyRpc = findConfigProxyPort(defaultPortBase + 90); defaultConfigServers = findConfigServers("localhost"); initialized = true; } std::string myPath(const char *argv0) { if (argv0[0] == '/') return argv0; const char *pathEnv = getenv("PATH"); if (pathEnv != 0) { std::string path = pathEnv; size_t pos = 0; size_t colon; do { colon = path.find(':', pos); std::string pre = path.substr(pos, colon-pos); pos = colon+1; if (pre[0] == '/') { pre.append("/"); pre.append(argv0); if (access(pre.c_str(), X_OK) == 0) { return pre; } } } while (colon != std::string::npos); } return argv0; } } namespace vespa { void Defaults::bootstrap(const char *argv0) { if (getenv("VESPA_HOME") == 0) { std::string path = myPath(argv0); size_t slash = path.rfind('/'); if (slash != std::string::npos) { path.resize(slash); slash = path.rfind('/', slash-1); if (slash != std::string::npos) { const char *dirname = path.c_str() + slash; if (strncmp(dirname, "/bin", 4) == 0 || strncmp(dirname, "/sbin", 5) == 0) { path.resize(slash); } } std::string setting = "VESPA_HOME"; setting.append("="); setting.append(path); putenv(&setting[0]); } } initialized = false; } const char * Defaults::vespaHome() { findDefaults(); return defaultHome; } std::string Defaults::underVespaHome(const char *path) { if (path[0] == '/') { return path; } if (path[0] == '.' && path[1] == '/') { return path; } findDefaults(); std::string ret = defaultHome; ret += '/'; ret += path; return ret; } const char * Defaults::vespaUser() { findDefaults(); return defaultUser; } const char * Defaults::vespaHostname() { findDefaults(); return defaultHost; } int Defaults::vespaWebServicePort() { findDefaults(); return defaultWebServicePort; } int Defaults::vespaPortBase() { findDefaults(); return defaultPortBase; } std::vector<std::string> Defaults::vespaConfigServerHosts() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { ret.push_back("localhost"); } else { while (token != 0) { char *colon = strchr(token, ':'); if (colon != 0 && colon != token) { *colon = '\0'; } ret.push_back(token); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } int Defaults::vespaConfigServerRpcPort() { findDefaults(); return defaultPortConfigServerRpc; } std::vector<std::string> Defaults::vespaConfigServerRpcAddrs() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { std::string one = "tcp/localhost:"; one += std::to_string(defaultPortConfigServerRpc); ret.push_back(one); } else { while (token != 0) { std::string one = "tcp/"; one += token; if (strchr(token, ':') == 0) { one += ":"; one += std::to_string(defaultPortConfigServerRpc); } ret.push_back(one); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } std::vector<std::string> Defaults::vespaConfigServerRestUrls() { findDefaults(); std::vector<std::string> ret; char *toParse = strdup(defaultConfigServers); char *savePtr = 0; char *token = strtok_r(toParse, " ,", &savePtr); if (token == 0) { std::string one = "http://localhost:"; one += std::to_string(defaultPortConfigServerHttp); ret.push_back(one); } else { while (token != 0) { std::string one = "http://"; char *colon = strchr(token, ':'); if (colon != 0 && colon != token) { *colon = '\0'; } one += token; one += ":"; one += std::to_string(defaultPortConfigServerHttp); one += "/"; ret.push_back(one); token = strtok_r(0, " ,", &savePtr); } } free(toParse); return ret; } std::string Defaults::vespaConfigProxyRpcAddr() { findDefaults(); std::string ret = "tcp/localhost:"; ret += std::to_string(defaultPortConfigProxyRpc); return ret; } std::vector<std::string> Defaults::vespaConfigSourcesRpcAddrs() { findDefaults(); std::vector<std::string> ret; ret.push_back(vespaConfigProxyRpcAddr()); for (std::string v : vespaConfigServerRpcAddrs()) { ret.push_back(v); } return ret; } } // namespace vespa
refactor to look more like java version
refactor to look more like java version
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
5d9bf905e42d14a09133c79298a9cb3ab7b2cf3d
Library/Sources/Stroika/Foundation/Execution/Platform/Windows/Exception.cpp
Library/Sources/Stroika/Foundation/Execution/Platform/Windows/Exception.cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../../../StroikaPreComp.h" #if qPlatform_Windows #include <Windows.h> #include <shellapi.h> #include <winerror.h> #include <wininet.h> // for error codes #else #error "WINDOWS REQUIRED FOR THIS MODULE" #endif #include "../../../Characters/CString/Utilities.h" #include "../../../Characters/Format.h" #include "../../../Configuration/Common.h" #include "../../../Containers/Common.h" #include "../../../Debug/Trace.h" #include "../../../Execution/TimeOutException.h" #if qPlatform_Windows #include "HRESULTErrorException.h" #endif #include "../../../IO/FileAccessException.h" #include "../../../IO/FileBusyException.h" #include "../../../Time/Realtime.h" #include "Exception.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Execution::Platform; using namespace Stroika::Foundation::Execution::Platform::Windows; // for InternetGetConnectedState #if _MSC_VER #pragma comment(lib, "Wininet.lib") #endif namespace { inline SDKString Win32Error2String_ (DWORD win32Err) { switch (win32Err) { case ERROR_NOT_ENOUGH_MEMORY: return SDKSTR ("Not enough memory to complete that operation (ERROR_NOT_ENOUGH_MEMORY)"); case ERROR_OUTOFMEMORY: return SDKSTR ("Not enough memory to complete that operation (ERROR_OUTOFMEMORY)"); case WSAEADDRNOTAVAIL: return SDKSTR ("Socket address not available (WSAEADDRNOTAVAIL)"); } if (INTERNET_ERROR_BASE <= win32Err and win32Err < INTERNET_ERROR_BASE + INTERNET_ERROR_LAST) { switch (win32Err) { case ERROR_INTERNET_INVALID_URL: return SDKSTR ("ERROR_INTERNET_INVALID_URL"); case ERROR_INTERNET_CANNOT_CONNECT: return SDKSTR ("Failed to connect to internet URL (ERROR_INTERNET_CANNOT_CONNECT)"); case ERROR_INTERNET_NAME_NOT_RESOLVED: return SDKSTR ("ERROR_INTERNET_NAME_NOT_RESOLVED"); case ERROR_INTERNET_INCORRECT_HANDLE_STATE: return SDKSTR ("ERROR_INTERNET_INCORRECT_HANDLE_STATE"); case ERROR_INTERNET_TIMEOUT: return SDKSTR ("Operation timed out (ERROR_INTERNET_TIMEOUT)"); case ERROR_INTERNET_CONNECTION_ABORTED: return SDKSTR ("ERROR_INTERNET_CONNECTION_ABORTED"); case ERROR_INTERNET_CONNECTION_RESET: return SDKSTR ("ERROR_INTERNET_CONNECTION_RESET"); case ERROR_HTTP_INVALID_SERVER_RESPONSE: return SDKSTR ("Invalid Server Response (ERROR_HTTP_INVALID_SERVER_RESPONSE)"); case ERROR_INTERNET_PROTOCOL_NOT_FOUND: { DWORD r = 0; if (::InternetGetConnectedState (&r, 0) and (r & INTERNET_CONNECTION_OFFLINE) == 0) { return SDKSTR ("ERROR_INTERNET_PROTOCOL_NOT_FOUND"); } else { return SDKSTR ("ERROR_INTERNET_PROTOCOL_NOT_FOUND (offline mode)"); } } default: { TCHAR buf[1024]; (void)::_stprintf_s (buf, SDKSTR ("INTERNET error code: %d"), win32Err); return buf; } } } TCHAR* lpMsgBuf = nullptr; if (not::FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, win32Err, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language reinterpret_cast<TCHAR*> (&lpMsgBuf), 0, nullptr)) { return CString::Format (SDKSTR ("Win32 error# %d"), static_cast<DWORD> (win32Err)); } SDKString result = lpMsgBuf; ::LocalFree (lpMsgBuf); return CString::Trim (result); } } /* ******************************************************************************** *********************** Platform::Windows::Exception *************************** ******************************************************************************** */ DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_MSC_WARNING_START (4996); Execution::Platform::Windows::Exception::Exception (DWORD error) : Execution::SystemErrorException<> (error_code (error, system_category ()), SDKString2Wide (Win32Error2String_ (error))) , fError (error) { } void Execution::Platform::Windows::Exception::Throw (DWORD error) { switch (error) { case ERROR_SUCCESS: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace DbgTrace ("Platform::Windows::Exception::Throw (ERROR_SUCCESS) - throwing Platform::Windows::Exception (ERROR_NOT_SUPPORTED) from %s", Execution::Private_::GetBT_s ().c_str ()); #else DbgTrace ("Platform::Windows::Exception::Throw (ERROR_SUCCESS) - throwing Platform::Windows::Exception (ERROR_NOT_SUPPORTED)"); #endif #endif // unsure WHAT to throw here - SOMETHING failed - but GetLastError () must have given // a bad reason code? throw Platform::Windows::Exception (ERROR_NOT_SUPPORTED); } #if 1 default: { Execution::ThrowSystemErrNo (error); #if 0 #if qStroika_Foundation_Exection_Throw_TraceThrowpoint #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing Platform::Windows::Exception from %s", error, Execution::Private_::GetBT_s ().c_str ()); #else DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing Platform::Windows::Exception", error); #endif #endif throw Execution::SystemErrorException (error, system_category ()); #endif } #else case ERROR_NOT_ENOUGH_MEMORY: case ERROR_OUTOFMEMORY: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing bad_alloc", error); #endif Execution::Throw (bad_alloc ()); } case ERROR_SHARING_VIOLATION: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing FileBusyException", error); #endif Execution::Throw (IO::FileBusyException ()); } case ERROR_ACCESS_DENIED: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing FileAccessException", error); #endif Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } case ERROR_FILE_NOT_FOUND: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing FileAccessException", error); #endif Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } case ERROR_PATH_NOT_FOUND: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing FileAccessException", error); #endif Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } case WAIT_TIMEOUT: case ERROR_INTERNET_TIMEOUT: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing TimeOutException", error); #endif Execution::Throw (Execution::TimeOutException ()); } default: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing Platform::Windows::Exception from %s", error, Execution::Private_::GetBT_s ().c_str ()); #else DbgTrace ("Platform::Windows::Exception::Throw (0x%x) - throwing Platform::Windows::Exception", error); #endif #endif throw Platform::Windows::Exception (error); } #endif } } SDKString Execution::Platform::Windows::Exception::LookupMessage (DWORD dw) { return Win32Error2String_ (dw); } DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_MSC_WARNING_END (4996); /* ******************************************************************************** ***************************** ThrowIfShellExecError **************************** ******************************************************************************** */ void Execution::Platform::Windows::ThrowIfShellExecError (HINSTANCE r) { DISABLE_COMPILER_MSC_WARNING_START (4302) DISABLE_COMPILER_MSC_WARNING_START (4311) int errCode = reinterpret_cast<int> (r); DISABLE_COMPILER_MSC_WARNING_END (4311) DISABLE_COMPILER_MSC_WARNING_END (4302) if (errCode <= 32) { DbgTrace ("ThrowIfShellExecError (0x%x) - throwing exception", errCode); switch (errCode) { case 0: Execution::ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); // The operating system is out of memory or resources. case ERROR_FILE_NOT_FOUND: Execution::ThrowSystemErrNo (ERROR_FILE_NOT_FOUND); // The specified file was not found. case ERROR_PATH_NOT_FOUND: Execution::ThrowSystemErrNo (ERROR_PATH_NOT_FOUND); // The specified path was not found. case ERROR_BAD_FORMAT: Execution::ThrowSystemErrNo (ERROR_BAD_FORMAT); // The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image). case SE_ERR_ACCESSDENIED: Execution::Throw (SystemErrorException{E_ACCESSDENIED, HRESULT_error_category ()}); // The operating system denied access to the specified file. case SE_ERR_ASSOCINCOMPLETE: Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); // The file name association is incomplete or invalid. case SE_ERR_DDEBUSY: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed. case SE_ERR_DDEFAIL: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The DDE transaction failed. case SE_ERR_DDETIMEOUT: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The DDE transaction could not be completed because the request timed out. case SE_ERR_DLLNOTFOUND: Execution::ThrowSystemErrNo (ERROR_DLL_NOT_FOUND); // The specified dynamic-link library (DLL) was not found. //case SE_ERR_FNF: throw (Platform::Windows::Exception (ERROR_FILE_NOT_FOUND)); // The specified file was not found. case SE_ERR_NOASSOC: Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); // There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable. case SE_ERR_OOM: Execution::ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); // There was not enough memory to complete the operation. //case SE_ERR_PNF: throw (Platform::Windows::Exception (ERROR_PATH_NOT_FOUND)); // The specified path was not found. case SE_ERR_SHARE: Execution::ThrowSystemErrNo (ERROR_INVALID_SHARENAME); // default: { // Not sure what error to report here... Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); } } } } /* ******************************************************************************** *********** Execution::RegisterDefaultHandler_invalid_parameter **************** ******************************************************************************** */ namespace { /* * Because of Microsoft's new secure-runtime-lib - we must provide a handler to catch errors (shouldn't occur - but in case. * We treat these largely like ASSERTION errors, but then translate them into a THROW of an exception - since that is * probably more often the right thing todo. */ void invalid_parameter_handler_ ([[maybe_unused]] const wchar_t* expression, [[maybe_unused]] const wchar_t* function, [[maybe_unused]] const wchar_t* file, [[maybe_unused]] unsigned int line, [[maybe_unused]] uintptr_t pReserved) { TraceContextBumper trcCtx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"invalid_parameter_handler", L"Func='%s', expr='%s', file='%s', line=%d.", function, expression, file, line)}; Assert (false); Execution::ThrowSystemErrNo (ERROR_INVALID_PARAMETER); } } void Execution::Platform::Windows::RegisterDefaultHandler_invalid_parameter () { (void)_set_invalid_parameter_handler (invalid_parameter_handler_); }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../../../StroikaPreComp.h" #if qPlatform_Windows #include <Windows.h> #include <shellapi.h> #include <winerror.h> #include <wininet.h> // for error codes #else #error "WINDOWS REQUIRED FOR THIS MODULE" #endif #include "../../../Characters/CString/Utilities.h" #include "../../../Characters/Format.h" #include "../../../Configuration/Common.h" #include "../../../Containers/Common.h" #include "../../../Debug/Trace.h" #include "../../../Execution/TimeOutException.h" #if qPlatform_Windows #include "HRESULTErrorException.h" #endif #include "../../../IO/FileAccessException.h" #include "../../../IO/FileBusyException.h" #include "../../../Time/Realtime.h" #include "Exception.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Execution::Platform; using namespace Stroika::Foundation::Execution::Platform::Windows; // for InternetGetConnectedState #if _MSC_VER #pragma comment(lib, "Wininet.lib") #endif namespace { inline SDKString Win32Error2String_ (DWORD win32Err) { switch (win32Err) { case ERROR_NOT_ENOUGH_MEMORY: return SDKSTR ("Not enough memory to complete that operation (ERROR_NOT_ENOUGH_MEMORY)"); case ERROR_OUTOFMEMORY: return SDKSTR ("Not enough memory to complete that operation (ERROR_OUTOFMEMORY)"); case WSAEADDRNOTAVAIL: return SDKSTR ("Socket address not available (WSAEADDRNOTAVAIL)"); } if (INTERNET_ERROR_BASE <= win32Err and win32Err < INTERNET_ERROR_BASE + INTERNET_ERROR_LAST) { switch (win32Err) { case ERROR_INTERNET_INVALID_URL: return SDKSTR ("ERROR_INTERNET_INVALID_URL"); case ERROR_INTERNET_CANNOT_CONNECT: return SDKSTR ("Failed to connect to internet URL (ERROR_INTERNET_CANNOT_CONNECT)"); case ERROR_INTERNET_NAME_NOT_RESOLVED: return SDKSTR ("ERROR_INTERNET_NAME_NOT_RESOLVED"); case ERROR_INTERNET_INCORRECT_HANDLE_STATE: return SDKSTR ("ERROR_INTERNET_INCORRECT_HANDLE_STATE"); case ERROR_INTERNET_TIMEOUT: return SDKSTR ("Operation timed out (ERROR_INTERNET_TIMEOUT)"); case ERROR_INTERNET_CONNECTION_ABORTED: return SDKSTR ("ERROR_INTERNET_CONNECTION_ABORTED"); case ERROR_INTERNET_CONNECTION_RESET: return SDKSTR ("ERROR_INTERNET_CONNECTION_RESET"); case ERROR_HTTP_INVALID_SERVER_RESPONSE: return SDKSTR ("Invalid Server Response (ERROR_HTTP_INVALID_SERVER_RESPONSE)"); case ERROR_INTERNET_PROTOCOL_NOT_FOUND: { DWORD r = 0; if (::InternetGetConnectedState (&r, 0) and (r & INTERNET_CONNECTION_OFFLINE) == 0) { return SDKSTR ("ERROR_INTERNET_PROTOCOL_NOT_FOUND"); } else { return SDKSTR ("ERROR_INTERNET_PROTOCOL_NOT_FOUND (offline mode)"); } } default: { TCHAR buf[1024]; (void)::_stprintf_s (buf, SDKSTR ("INTERNET error code: %d"), win32Err); return buf; } } } TCHAR* lpMsgBuf = nullptr; if (not::FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, win32Err, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language reinterpret_cast<TCHAR*> (&lpMsgBuf), 0, nullptr)) { return CString::Format (SDKSTR ("Win32 error# %d"), static_cast<DWORD> (win32Err)); } SDKString result = lpMsgBuf; ::LocalFree (lpMsgBuf); return CString::Trim (result); } } /* ******************************************************************************** *********************** Platform::Windows::Exception *************************** ******************************************************************************** */ DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_MSC_WARNING_START (4996); Execution::Platform::Windows::Exception::Exception (DWORD error) : Execution::SystemErrorException<> (error_code (error, system_category ()), SDKString2Wide (Win32Error2String_ (error))) , fError (error) { } void Execution::Platform::Windows::Exception::Throw (DWORD error) { switch (error) { case ERROR_SUCCESS: { #if qStroika_Foundation_Exection_Throw_TraceThrowpoint #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace DbgTrace ("Platform::Windows::Exception::Throw (ERROR_SUCCESS) - throwing Platform::Windows::Exception (ERROR_NOT_SUPPORTED) from %s", Execution::Private_::GetBT_s ().c_str ()); #else DbgTrace ("Platform::Windows::Exception::Throw (ERROR_SUCCESS) - throwing Platform::Windows::Exception (ERROR_NOT_SUPPORTED)"); #endif #endif // unsure WHAT to throw here - SOMETHING failed - but GetLastError () must have given // a bad reason code? throw Platform::Windows::Exception (ERROR_NOT_SUPPORTED); } default: { Execution::ThrowSystemErrNo (error); } } } SDKString Execution::Platform::Windows::Exception::LookupMessage (DWORD dw) { return Win32Error2String_ (dw); } DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") DISABLE_COMPILER_MSC_WARNING_END (4996); /* ******************************************************************************** ***************************** ThrowIfShellExecError **************************** ******************************************************************************** */ void Execution::Platform::Windows::ThrowIfShellExecError (HINSTANCE r) { DISABLE_COMPILER_MSC_WARNING_START (4302) DISABLE_COMPILER_MSC_WARNING_START (4311) int errCode = reinterpret_cast<int> (r); DISABLE_COMPILER_MSC_WARNING_END (4311) DISABLE_COMPILER_MSC_WARNING_END (4302) if (errCode <= 32) { DbgTrace ("ThrowIfShellExecError (0x%x) - throwing exception", errCode); switch (errCode) { case 0: Execution::ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); // The operating system is out of memory or resources. case ERROR_FILE_NOT_FOUND: Execution::ThrowSystemErrNo (ERROR_FILE_NOT_FOUND); // The specified file was not found. case ERROR_PATH_NOT_FOUND: Execution::ThrowSystemErrNo (ERROR_PATH_NOT_FOUND); // The specified path was not found. case ERROR_BAD_FORMAT: Execution::ThrowSystemErrNo (ERROR_BAD_FORMAT); // The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image). case SE_ERR_ACCESSDENIED: Execution::Throw (SystemErrorException{E_ACCESSDENIED, HRESULT_error_category ()}); // The operating system denied access to the specified file. case SE_ERR_ASSOCINCOMPLETE: Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); // The file name association is incomplete or invalid. case SE_ERR_DDEBUSY: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed. case SE_ERR_DDEFAIL: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The DDE transaction failed. case SE_ERR_DDETIMEOUT: Execution::ThrowSystemErrNo (ERROR_DDE_FAIL); // The DDE transaction could not be completed because the request timed out. case SE_ERR_DLLNOTFOUND: Execution::ThrowSystemErrNo (ERROR_DLL_NOT_FOUND); // The specified dynamic-link library (DLL) was not found. //case SE_ERR_FNF: throw (Platform::Windows::Exception (ERROR_FILE_NOT_FOUND)); // The specified file was not found. case SE_ERR_NOASSOC: Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); // There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable. case SE_ERR_OOM: Execution::ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); // There was not enough memory to complete the operation. //case SE_ERR_PNF: throw (Platform::Windows::Exception (ERROR_PATH_NOT_FOUND)); // The specified path was not found. case SE_ERR_SHARE: Execution::ThrowSystemErrNo (ERROR_INVALID_SHARENAME); // default: { // Not sure what error to report here... Execution::ThrowSystemErrNo (ERROR_NO_ASSOCIATION); } } } } /* ******************************************************************************** *********** Execution::RegisterDefaultHandler_invalid_parameter **************** ******************************************************************************** */ namespace { /* * Because of Microsoft's new secure-runtime-lib - we must provide a handler to catch errors (shouldn't occur - but in case. * We treat these largely like ASSERTION errors, but then translate them into a THROW of an exception - since that is * probably more often the right thing todo. */ void invalid_parameter_handler_ ([[maybe_unused]] const wchar_t* expression, [[maybe_unused]] const wchar_t* function, [[maybe_unused]] const wchar_t* file, [[maybe_unused]] unsigned int line, [[maybe_unused]] uintptr_t pReserved) { TraceContextBumper trcCtx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"invalid_parameter_handler", L"Func='%s', expr='%s', file='%s', line=%d.", function, expression, file, line)}; Assert (false); Execution::ThrowSystemErrNo (ERROR_INVALID_PARAMETER); } } void Execution::Platform::Windows::RegisterDefaultHandler_invalid_parameter () { (void)_set_invalid_parameter_handler (invalid_parameter_handler_); }
remove ifdefed comemnted out excpetion code
remove ifdefed comemnted out excpetion code
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
eb973b48fb55774fafb4e001f08cb334e22fa829
src/application/Window.cpp
src/application/Window.cpp
#include "Window.h" #include "devices/Mouse.h" #include "devices/Keyboard.h" #include "devices/Touches.h" #include "devices/Joystick.h" #include "collision/area/EventsToCollisions.h" #include "Collision/Quadtree/Quadtree.h" #include "widgets/systems/DragSystem.h" #include "widgets/systems/TooltipSystem.h" #include "widgets/Widget.h" #include "SDL_video.h" #include "SDL_render.h" #include "graphic/OpenGL.h" #include "graphic/Blender.h" #include "graphic/renderer/MVP.h" #include "graphic/renderer/Viewport.h" #include "glm/gtc/matrix_transform.hpp" using namespace MX; Window::Window(unsigned width, unsigned height, bool fullscreen) :_window{ nullptr, SDL_DestroyWindow } { _timer = std::make_shared<Time::SimpleTimer>(); _width = width; _height = height; _fullscreen = fullscreen; Uint32 flags = SDL_WINDOW_OPENGL; if (_fullscreen) flags |= SDL_WINDOW_FULLSCREEN; _window.reset(SDL_CreateWindow( "", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position _width, // width, in pixels _height, // height, in pixels flags // flags - see below )); if (!_window) throw std::runtime_error("SDL_CreateWindow"); auto area = std::make_shared<Collision::QuadtreeWeakLayeredArea>((float)width, (float)height); _windowArea = area; _windowArea->DefineLayerCollision(ClassID<Collision::EventsToCollisions>::id(), ClassID<Widgets::WidgetsLayer>::id()); _windowArea->DefineLayerCollision(ClassID<Widgets::DragLayer>::id(), ClassID<Widgets::WidgetsLayer>::id()); _mouse = Mouse::CreateForWindow(this); _keyboard = Keyboard::CreateForWindow(this); _touches = Touches::CreateForWindow(this); _joysticks = Joysticks::CreateForWindow(this); _mouseTouches = MouseTouches::CreateMouseTouchesForDisplay(_timer, _mouse); _dragSystem = std::make_shared<MX::Widgets::DragSystem>(); _tooltipSystem = std::make_shared<MX::Widgets::TooltipSystem>(); _eventsToCollisions.reset(new Collision::EventsToCollisions(_windowArea, _mouse, _touches, _mouseTouches, _dragSystem)); _glcontext = SDL_GL_CreateContext(_window.get()); if (!_glcontext) throw std::runtime_error("SDL_GL_CreateContext"); GLenum err = glewInit(); if (err != GLEW_OK) throw std::runtime_error("glewInit"); SDL_GL_SetSwapInterval(1); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } Window::~Window() { if (_glcontext) SDL_GL_DeleteContext(_glcontext); } void Window::Init() { } void Window::OnRender() { Viewport::Set(Rectangle{0.0f, 0.0f, (float)_width, (float)_height}); glm::mat4x4 projection = glm::orthoLH(0.0f, (float)_width, (float)_height, 0.0f, -100.0f, 100.0f); MVP::SetProjection(projection); glEnable(GL_BLEND); Graphic::Blender::SetCurrent(Graphic::Blender::defaultNormal()); Graphic::Blender::defaultNormal().Apply(); } void Window::AfterRender() { SDL_GL_SwapWindow(_window.get()); } bool Window::OnLoop() { _timer->Step(); return true; }
#include "Window.h" #include "devices/Mouse.h" #include "devices/Keyboard.h" #include "devices/Touches.h" #include "devices/Joystick.h" #include "collision/area/EventsToCollisions.h" #include "collision/quadtree/Quadtree.h" #include "widgets/systems/DragSystem.h" #include "widgets/systems/TooltipSystem.h" #include "widgets/Widget.h" #include "SDL_video.h" #include "SDL_render.h" #include "graphic/OpenGL.h" #include "graphic/Blender.h" #include "graphic/renderer/MVP.h" #include "graphic/renderer/Viewport.h" #include "glm/gtc/matrix_transform.hpp" using namespace MX; Window::Window(unsigned width, unsigned height, bool fullscreen) :_window{ nullptr, SDL_DestroyWindow } { _timer = std::make_shared<Time::SimpleTimer>(); _width = width; _height = height; _fullscreen = fullscreen; Uint32 flags = SDL_WINDOW_OPENGL; if (_fullscreen) flags |= SDL_WINDOW_FULLSCREEN; _window.reset(SDL_CreateWindow( "", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position _width, // width, in pixels _height, // height, in pixels flags // flags - see below )); if (!_window) throw std::runtime_error("SDL_CreateWindow"); auto area = std::make_shared<Collision::QuadtreeWeakLayeredArea>((float)width, (float)height); _windowArea = area; _windowArea->DefineLayerCollision(ClassID<Collision::EventsToCollisions>::id(), ClassID<Widgets::WidgetsLayer>::id()); _windowArea->DefineLayerCollision(ClassID<Widgets::DragLayer>::id(), ClassID<Widgets::WidgetsLayer>::id()); _mouse = Mouse::CreateForWindow(this); _keyboard = Keyboard::CreateForWindow(this); _touches = Touches::CreateForWindow(this); _joysticks = Joysticks::CreateForWindow(this); _mouseTouches = MouseTouches::CreateMouseTouchesForDisplay(_timer, _mouse); _dragSystem = std::make_shared<MX::Widgets::DragSystem>(); _tooltipSystem = std::make_shared<MX::Widgets::TooltipSystem>(); _eventsToCollisions.reset(new Collision::EventsToCollisions(_windowArea, _mouse, _touches, _mouseTouches, _dragSystem)); _glcontext = SDL_GL_CreateContext(_window.get()); if (!_glcontext) throw std::runtime_error("SDL_GL_CreateContext"); GLenum err = glewInit(); if (err != GLEW_OK) throw std::runtime_error("glewInit"); SDL_GL_SetSwapInterval(1); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } Window::~Window() { if (_glcontext) SDL_GL_DeleteContext(_glcontext); } void Window::Init() { } void Window::OnRender() { Viewport::Set(Rectangle{0.0f, 0.0f, (float)_width, (float)_height}); glm::mat4x4 projection = glm::orthoLH(0.0f, (float)_width, (float)_height, 0.0f, -100.0f, 100.0f); MVP::SetProjection(projection); glEnable(GL_BLEND); Graphic::Blender::SetCurrent(Graphic::Blender::defaultNormal()); Graphic::Blender::defaultNormal().Apply(); } void Window::AfterRender() { SDL_GL_SwapWindow(_window.get()); } bool Window::OnLoop() { _timer->Step(); return true; }
Fix path.
Fix path.
C++
mit
Kaosumaru/libmx,Kaosumaru/libmx,Kaosumaru/libmx
6aa70e148ef9380fddd0fa6ab14b82bb59718f91
Modules/Filtering/DimensionalityReduction/include/otbFastICAImageFilter.hxx
Modules/Filtering/DimensionalityReduction/include/otbFastICAImageFilter.hxx
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbFastICAImageFilter_hxx #define otbFastICAImageFilter_hxx #include "otbFastICAImageFilter.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include <vnl/vnl_matrix.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vnl/algo/vnl_generalized_eigensystem.h> namespace otb { template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::FastICAImageFilter () { this->SetNumberOfRequiredInputs(1); m_NumberOfPrincipalComponentsRequired = 0; m_GivenTransformationMatrix = false; m_IsTransformationForward = true; m_NumberOfIterations = 50; m_ConvergenceThreshold = 1E-4; m_ContrastFunction = [](double x) {return std::tanh(x);}; m_ContrastFunctionDerivative = [](double x) {return 1-std::pow( std::tanh(x), 2. );}; m_Mu = 1.; m_PCAFilter = PCAFilterType::New(); m_PCAFilter->SetUseNormalization(true); m_PCAFilter->SetUseVarianceForNormalization(false); m_TransformFilter = TransformFilterType::New(); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateOutputInformation() // throw itk::ExceptionObject { Superclass::GenerateOutputInformation(); switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { if ( m_NumberOfPrincipalComponentsRequired == 0 || m_NumberOfPrincipalComponentsRequired > this->GetInput()->GetNumberOfComponentsPerPixel() ) { m_NumberOfPrincipalComponentsRequired = this->GetInput()->GetNumberOfComponentsPerPixel(); } this->GetOutput()->SetNumberOfComponentsPerPixel( m_NumberOfPrincipalComponentsRequired ); break; } case static_cast<int>(Transform::INVERSE): { unsigned int theOutputDimension = 0; if ( m_GivenTransformationMatrix ) { theOutputDimension = m_TransformationMatrix.Rows() >= m_TransformationMatrix.Cols() ? m_TransformationMatrix.Rows() : m_TransformationMatrix.Cols(); } else { throw itk::ExceptionObject(__FILE__, __LINE__, "Mixture matrix is required to know the output size", ITK_LOCATION); } this->GetOutput()->SetNumberOfComponentsPerPixel( theOutputDimension ); break; } default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templeted with FORWARD or INVERSE only...", ITK_LOCATION ); } switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { ForwardGenerateOutputInformation(); break; } case static_cast<int>(Transform::INVERSE): { ReverseGenerateOutputInformation(); break; } } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateOutputInformation() { typename InputImageType::Pointer inputImgPtr = const_cast<InputImageType*>( this->GetInput() ); m_PCAFilter->SetInput( inputImgPtr ); m_PCAFilter->GetOutput()->UpdateOutputInformation(); if ( !m_GivenTransformationMatrix ) { GenerateTransformationMatrix(); } else if ( !m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = true; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } m_TransformFilter->SetInput( m_PCAFilter->GetOutput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateOutputInformation() { if ( !m_GivenTransformationMatrix ) { throw itk::ExceptionObject( __FILE__, __LINE__, "No Transformation matrix given", ITK_LOCATION ); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } if ( m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = false; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } m_TransformFilter->SetInput( this->GetInput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); /* * PCA filter may throw exception if * the mean, stdDev and transformation matrix * have not been given at this point */ m_PCAFilter->SetInput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateData () { switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): return ForwardGenerateData(); case static_cast<int>(Transform::INVERSE): return ReverseGenerateData(); default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templated with FORWARD or INVERSE only...", ITK_LOCATION ); } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateData () { m_TransformFilter->GraftOutput( this->GetOutput() ); m_TransformFilter->Update(); this->GraftOutput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateData () { m_PCAFilter->GraftOutput( this->GetOutput() ); m_PCAFilter->Update(); this->GraftOutput( m_PCAFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateTransformationMatrix () { itk::ProgressReporter reporter ( this, 0, GetNumberOfIterations(), GetNumberOfIterations() ); double convergence = itk::NumericTraits<double>::max(); unsigned int iteration = 0; const unsigned int size = this->GetInput()->GetNumberOfComponentsPerPixel(); // transformation matrix InternalMatrixType W ( size, size, vnl_matrix_identity ); while ( iteration++ < GetNumberOfIterations() && convergence > GetConvergenceThreshold() ) { InternalMatrixType W_old ( W ); typename InputImageType::Pointer img = const_cast<InputImageType*>( m_PCAFilter->GetOutput() ); TransformFilterPointerType transformer = TransformFilterType::New(); if ( !W.is_identity() ) { transformer->SetInput( GetPCAFilter()->GetOutput() ); transformer->SetMatrix( W ); transformer->Update(); img = const_cast<InputImageType*>( transformer->GetOutput() ); } for ( unsigned int band = 0; band < size; band++ ) { otbMsgDebugMacro( << "Iteration " << iteration << ", bande " << band << ", convergence " << convergence ); InternalOptimizerPointerType optimizer = InternalOptimizerType::New(); optimizer->SetInput( 0, m_PCAFilter->GetOutput() ); optimizer->SetInput( 1, img ); optimizer->SetW( W ); optimizer->SetContrastFunction( this->GetContrastFunction(), this->GetContrastFunctionDerivative() ); optimizer->SetCurrentBandForLoop( band ); MeanEstimatorFilterPointerType estimator = MeanEstimatorFilterType::New(); estimator->SetInput( optimizer->GetOutput() ); // Here we have a pipeline of two persistent filters, we have to manually // call Reset() and Synthetize () on the first one (optimizer). optimizer->Reset(); estimator->Update(); optimizer->Synthetize(); double norm = 0.; for ( unsigned int bd = 0; bd < size; bd++ ) { W(band, bd) -= m_Mu * ( estimator->GetMean()[bd] - optimizer->GetBeta() * W(band, bd) ) / optimizer->GetDen(); norm += std::pow( W(band, bd), 2. ); } for ( unsigned int bd = 0; bd < size; bd++ ) W(band, bd) /= std::sqrt( norm ); } // Decorrelation of the W vectors InternalMatrixType W_tmp = W * W.transpose(); vnl_svd< MatrixElementType > solver ( W_tmp ); InternalMatrixType valP = solver.W(); for ( unsigned int i = 0; i < valP.rows(); ++i ) valP(i, i) = 1. / std::sqrt( static_cast<double>( valP(i, i) ) ); // Watch for 0 or neg InternalMatrixType transf = solver.U(); W_tmp = transf * valP * transf.transpose(); W = W_tmp * W; // Convergence evaluation convergence = 0.; for ( unsigned int i = 0; i < W.rows(); ++i ) for ( unsigned int j = 0; j < W.cols(); ++j ) convergence += std::abs( W(i, j) - W_old(i, j) ); reporter.CompletedPixel(); } // end of while loop if ( size != this->GetNumberOfPrincipalComponentsRequired() ) { this->m_TransformationMatrix = W.get_n_columns( 0, this->GetNumberOfPrincipalComponentsRequired() ); } else { this->m_TransformationMatrix = W; } otbMsgDebugMacro( << "Final convergence " << convergence << " after " << iteration << " iterations" ); } } // end of namespace otb #endif
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbFastICAImageFilter_hxx #define otbFastICAImageFilter_hxx #include "otbFastICAImageFilter.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include <vnl/vnl_matrix.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vnl/algo/vnl_generalized_eigensystem.h> namespace otb { template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::FastICAImageFilter () { this->SetNumberOfRequiredInputs(1); m_NumberOfPrincipalComponentsRequired = 0; m_GivenTransformationMatrix = false; m_IsTransformationForward = true; m_NumberOfIterations = 50; m_ConvergenceThreshold = 1E-4; m_ContrastFunction = [](double x) {return std::tanh(x);}; m_ContrastFunctionDerivative = [](double x) {return 1-std::pow( std::tanh(x), 2. );}; m_Mu = 1.; m_PCAFilter = PCAFilterType::New(); m_PCAFilter->SetUseNormalization(true); m_PCAFilter->SetUseVarianceForNormalization(false); m_TransformFilter = TransformFilterType::New(); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateOutputInformation() // throw itk::ExceptionObject { Superclass::GenerateOutputInformation(); switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { if ( m_NumberOfPrincipalComponentsRequired == 0 || m_NumberOfPrincipalComponentsRequired > this->GetInput()->GetNumberOfComponentsPerPixel() ) { m_NumberOfPrincipalComponentsRequired = this->GetInput()->GetNumberOfComponentsPerPixel(); } this->GetOutput()->SetNumberOfComponentsPerPixel( m_NumberOfPrincipalComponentsRequired ); break; } case static_cast<int>(Transform::INVERSE): { unsigned int theOutputDimension = 0; if ( m_GivenTransformationMatrix ) { theOutputDimension = m_TransformationMatrix.Rows() >= m_TransformationMatrix.Cols() ? m_TransformationMatrix.Rows() : m_TransformationMatrix.Cols(); } else { throw itk::ExceptionObject(__FILE__, __LINE__, "Mixture matrix is required to know the output size", ITK_LOCATION); } this->GetOutput()->SetNumberOfComponentsPerPixel( theOutputDimension ); break; } default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templeted with FORWARD or INVERSE only...", ITK_LOCATION ); } switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { ForwardGenerateOutputInformation(); break; } case static_cast<int>(Transform::INVERSE): { ReverseGenerateOutputInformation(); break; } } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateOutputInformation() { typename InputImageType::Pointer inputImgPtr = const_cast<InputImageType*>( this->GetInput() ); m_PCAFilter->SetInput( inputImgPtr ); m_PCAFilter->GetOutput()->UpdateOutputInformation(); if ( !m_GivenTransformationMatrix ) { GenerateTransformationMatrix(); } else if ( !m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = true; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } m_TransformFilter->SetInput( m_PCAFilter->GetOutput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateOutputInformation() { if ( !m_GivenTransformationMatrix ) { throw itk::ExceptionObject( __FILE__, __LINE__, "No Transformation matrix given", ITK_LOCATION ); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } if ( m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = false; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } m_TransformFilter->SetInput( this->GetInput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); /* * PCA filter may throw exception if * the mean, stdDev and transformation matrix * have not been given at this point */ m_PCAFilter->SetInput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateData () { switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): return ForwardGenerateData(); case static_cast<int>(Transform::INVERSE): return ReverseGenerateData(); default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templated with FORWARD or INVERSE only...", ITK_LOCATION ); } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateData () { m_TransformFilter->GraftOutput( this->GetOutput() ); m_TransformFilter->Update(); this->GraftOutput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateData () { m_PCAFilter->GraftOutput( this->GetOutput() ); m_PCAFilter->Update(); this->GraftOutput( m_PCAFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateTransformationMatrix () { itk::ProgressReporter reporter ( this, 0, GetNumberOfIterations(), GetNumberOfIterations() ); double convergence = itk::NumericTraits<double>::max(); unsigned int iteration = 0; const unsigned int size = this->GetInput()->GetNumberOfComponentsPerPixel(); // transformation matrix InternalMatrixType W ( size, size, vnl_matrix_identity ); while ( iteration++ < GetNumberOfIterations() && convergence > GetConvergenceThreshold() ) { InternalMatrixType W_old ( W ); typename InputImageType::Pointer img = const_cast<InputImageType*>( m_PCAFilter->GetOutput() ); TransformFilterPointerType transformer = TransformFilterType::New(); if ( !W.is_identity() ) { transformer->SetInput( GetPCAFilter()->GetOutput() ); transformer->SetMatrix( W ); transformer->Update(); img = const_cast<InputImageType*>( transformer->GetOutput() ); } for ( unsigned int band = 0; band < size; band++ ) { otbMsgDebugMacro( << "Iteration " << iteration << ", bande " << band << ", convergence " << convergence ); InternalOptimizerPointerType optimizer = InternalOptimizerType::New(); optimizer->SetInput( 0, m_PCAFilter->GetOutput() ); optimizer->SetInput( 1, img ); optimizer->SetW( W ); optimizer->SetContrastFunction( this->GetContrastFunction(), this->GetContrastFunctionDerivative() ); optimizer->SetCurrentBandForLoop( band ); MeanEstimatorFilterPointerType estimator = MeanEstimatorFilterType::New(); estimator->SetInput( optimizer->GetOutput() ); // Here we have a pipeline of two persistent filters, we have to manually // call Reset() and Synthetize () on the first one (optimizer). optimizer->Reset(); estimator->Update(); optimizer->Synthetize(); double norm = 0.; for ( unsigned int bd = 0; bd < size; bd++ ) { W(bd, band) -= m_Mu * ( estimator->GetMean()[bd] - optimizer->GetBeta() * W(bd, band) ) / optimizer->GetDen(); norm += std::pow( W(bd, band), 2. ); } for ( unsigned int bd = 0; bd < size; bd++ ) W(bd, band) /= std::sqrt( norm ); } // Decorrelation of the W vectors InternalMatrixType W_tmp = W * W.transpose(); vnl_svd< MatrixElementType > solver ( W_tmp ); InternalMatrixType valP = solver.W(); for ( unsigned int i = 0; i < valP.rows(); ++i ) valP(i, i) = 1. / std::sqrt( static_cast<double>( valP(i, i) ) ); // Watch for 0 or neg InternalMatrixType transf = solver.U(); W_tmp = transf * valP * transf.transpose(); W = W_tmp * W; // Convergence evaluation convergence = 0.; for ( unsigned int i = 0; i < W.rows(); ++i ) for ( unsigned int j = 0; j < W.cols(); ++j ) convergence += std::abs( W(i, j) - W_old(i, j) ); reporter.CompletedPixel(); } // end of while loop if ( size != this->GetNumberOfPrincipalComponentsRequired() ) { this->m_TransformationMatrix = W.get_n_columns( 0, this->GetNumberOfPrincipalComponentsRequired() ); } else { this->m_TransformationMatrix = W; } otbMsgDebugMacro( << "Final convergence " << convergence << " after " << iteration << " iterations" ); } } // end of namespace otb #endif
swap line/column during the update of W
BUG: swap line/column during the update of W
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
d2c08afd7ec95c40523b0d200e7abb73b86bddca
modules/video_coding/codecs/vp8/vp8_sequence_coder.cc
modules/video_coding/codecs/vp8/vp8_sequence_coder.cc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/common_video/interface/i420_video_frame.h" #include "webrtc/common_video/interface/video_image.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/metrics/video_metrics.h" #include "webrtc/tools/simple_command_line_parser.h" class Vp8SequenceCoderEncodeCallback : public webrtc::EncodedImageCallback { public: explicit Vp8SequenceCoderEncodeCallback(FILE* encoded_file) : encoded_file_(encoded_file), encoded_bytes_(0) {} ~Vp8SequenceCoderEncodeCallback(); int Encoded(const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codecSpecificInfo, const webrtc::RTPFragmentationHeader*); // Returns the encoded image. webrtc::EncodedImage encoded_image() { return encoded_image_; } size_t encoded_bytes() { return encoded_bytes_; } private: webrtc::EncodedImage encoded_image_; FILE* encoded_file_; size_t encoded_bytes_; }; Vp8SequenceCoderEncodeCallback::~Vp8SequenceCoderEncodeCallback() { delete [] encoded_image_._buffer; encoded_image_._buffer = NULL; } int Vp8SequenceCoderEncodeCallback::Encoded( const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codecSpecificInfo, const webrtc::RTPFragmentationHeader* fragmentation) { if (encoded_image_._size < encoded_image._size) { delete [] encoded_image_._buffer; encoded_image_._buffer = NULL; encoded_image_._buffer = new uint8_t[encoded_image._size]; encoded_image_._size = encoded_image._size; } memcpy(encoded_image_._buffer, encoded_image._buffer, encoded_image._size); encoded_image_._length = encoded_image._length; if (encoded_file_ != NULL) { if (fwrite(encoded_image._buffer, 1, encoded_image._length, encoded_file_) != encoded_image._length) { return -1; } } encoded_bytes_ += encoded_image_._length; return 0; } // TODO(mikhal): Add support for varying the frame size. class Vp8SequenceCoderDecodeCallback : public webrtc::DecodedImageCallback { public: explicit Vp8SequenceCoderDecodeCallback(FILE* decoded_file) : decoded_file_(decoded_file) {} int Decoded(webrtc::I420VideoFrame& frame); bool DecodeComplete(); private: FILE* decoded_file_; }; int Vp8SequenceCoderDecodeCallback::Decoded(webrtc::I420VideoFrame& image) { EXPECT_EQ(0, webrtc::PrintI420VideoFrame(image, decoded_file_)); return 0; } int SequenceCoder(webrtc::test::CommandLineParser& parser) { int width = strtol((parser.GetFlag("w")).c_str(), NULL, 10); int height = strtol((parser.GetFlag("h")).c_str(), NULL, 10); int framerate = strtol((parser.GetFlag("f")).c_str(), NULL, 10); if (width <= 0 || height <= 0 || framerate <= 0) { fprintf(stderr, "Error: Resolution cannot be <= 0!\n"); return -1; } int target_bitrate = strtol((parser.GetFlag("b")).c_str(), NULL, 10); if (target_bitrate <= 0) { fprintf(stderr, "Error: Bit-rate cannot be <= 0!\n"); return -1; } // SetUp // Open input file. std::string encoded_file_name = parser.GetFlag("encoded_file"); FILE* encoded_file = fopen(encoded_file_name.c_str(), "wb"); if (encoded_file == NULL) { fprintf(stderr, "Error: Cannot open encoded file\n"); return -1; } std::string input_file_name = parser.GetFlag("input_file"); FILE* input_file = fopen(input_file_name.c_str(), "rb"); if (input_file == NULL) { fprintf(stderr, "Error: Cannot open input file\n"); return -1; } // Open output file. std::string output_file_name = parser.GetFlag("output_file"); FILE* output_file = fopen(output_file_name.c_str(), "wb"); if (output_file == NULL) { fprintf(stderr, "Error: Cannot open output file\n"); return -1; } // Get range of frames: will encode num_frames following start_frame). int start_frame = strtol((parser.GetFlag("start_frame")).c_str(), NULL, 10); int num_frames = strtol((parser.GetFlag("num_frames")).c_str(), NULL, 10); // Codec SetUp. webrtc::VideoCodec inst; memset(&inst, 0, sizeof(inst)); webrtc::VP8Encoder* encoder = webrtc::VP8Encoder::Create(); webrtc::VP8Decoder* decoder = webrtc::VP8Decoder::Create(); inst.codecType = webrtc::kVideoCodecVP8; inst.codecSpecific.VP8.feedbackModeOn = false; inst.codecSpecific.VP8.denoisingOn = true; inst.maxFramerate = framerate; inst.startBitrate = target_bitrate; inst.maxBitrate = 8000; inst.width = width; inst.height = height; if (encoder->InitEncode(&inst, 1, 1440) < 0) { fprintf(stderr, "Error: Cannot initialize vp8 encoder\n"); return -1; } EXPECT_EQ(0, decoder->InitDecode(&inst, 1)); webrtc::I420VideoFrame input_frame; size_t length = webrtc::CalcBufferSize(webrtc::kI420, width, height); rtc::scoped_ptr<uint8_t[]> frame_buffer(new uint8_t[length]); int half_width = (width + 1) / 2; // Set and register callbacks. Vp8SequenceCoderEncodeCallback encoder_callback(encoded_file); encoder->RegisterEncodeCompleteCallback(&encoder_callback); Vp8SequenceCoderDecodeCallback decoder_callback(output_file); decoder->RegisterDecodeCompleteCallback(&decoder_callback); // Read->Encode->Decode sequence. // num_frames = -1 implies unlimited encoding (entire sequence). int64_t starttime = webrtc::TickTime::MillisecondTimestamp(); int frame_cnt = 1; int frames_processed = 0; input_frame.CreateEmptyFrame(width, height, width, half_width, half_width); while (!feof(input_file) && (num_frames == -1 || frames_processed < num_frames)) { if (fread(frame_buffer.get(), 1, length, input_file) != length) continue; if (frame_cnt >= start_frame) { webrtc::ConvertToI420(webrtc::kI420, frame_buffer.get(), 0, 0, width, height, 0, webrtc::kVideoRotation_0, &input_frame); encoder->Encode(input_frame, NULL, NULL); decoder->Decode(encoder_callback.encoded_image(), false, NULL); ++frames_processed; } ++frame_cnt; } printf("\nProcessed %d frames\n", frames_processed); int64_t endtime = webrtc::TickTime::MillisecondTimestamp(); int64_t totalExecutionTime = endtime - starttime; printf("Total execution time: %.2lf ms\n", static_cast<double>(totalExecutionTime)); double actual_bit_rate = 8.0 * encoder_callback.encoded_bytes() / (frame_cnt / inst.maxFramerate); printf("Actual bitrate: %f kbps\n", actual_bit_rate / 1000); webrtc::test::QualityMetricsResult psnr_result, ssim_result; EXPECT_EQ(0, webrtc::test::I420MetricsFromFiles( input_file_name.c_str(), output_file_name.c_str(), inst.width, inst.height, &psnr_result, &ssim_result)); printf("PSNR avg: %f[dB], min: %f[dB]\nSSIM avg: %f, min: %f\n", psnr_result.average, psnr_result.min, ssim_result.average, ssim_result.min); return frame_cnt; } int main(int argc, char** argv) { std::string program_name = argv[0]; std::string usage = "Encode and decodes a video sequence, and writes" "results to a file.\n" "Example usage:\n" + program_name + " functionality" " --w=352 --h=288 --input_file=input.yuv --output_file=output.yuv " " Command line flags:\n" " - width(int): The width of the input file. Default: 352\n" " - height(int): The height of the input file. Default: 288\n" " - input_file(string): The YUV file to encode." " Default: foreman.yuv\n" " - encoded_file(string): The vp8 encoded file (encoder output)." " Default: vp8_encoded.vp8\n" " - output_file(string): The yuv decoded file (decoder output)." " Default: vp8_decoded.yuv\n." " - start_frame - frame number in which encoding will begin. Default: 0" " - num_frames - Number of frames to be processed. " " Default: -1 (entire sequence)."; webrtc::test::CommandLineParser parser; // Init the parser and set the usage message. parser.Init(argc, argv); // Reset flags. parser.SetFlag("w", "352"); parser.SetFlag("h", "288"); parser.SetFlag("f", "30"); parser.SetFlag("b", "500"); parser.SetFlag("start_frame", "0"); parser.SetFlag("num_frames", "-1"); parser.SetFlag("output_file", webrtc::test::OutputPath() + "vp8_decoded.yuv"); parser.SetFlag("encoded_file", webrtc::test::OutputPath() + "vp8_encoded.vp8"); parser.SetFlag("input_file", webrtc::test::ResourcePath("foreman_cif", "yuv")); parser.ProcessFlags(); if (parser.GetFlag("help") == "true") { parser.PrintUsageMessage(); } parser.PrintEnteredFlags(); return SequenceCoder(parser); }
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/common_video/interface/i420_video_frame.h" #include "webrtc/common_video/interface/video_image.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/metrics/video_metrics.h" #include "webrtc/tools/simple_command_line_parser.h" class Vp8SequenceCoderEncodeCallback : public webrtc::EncodedImageCallback { public: explicit Vp8SequenceCoderEncodeCallback(FILE* encoded_file) : encoded_file_(encoded_file), encoded_bytes_(0) {} ~Vp8SequenceCoderEncodeCallback(); int Encoded(const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codecSpecificInfo, const webrtc::RTPFragmentationHeader*); // Returns the encoded image. webrtc::EncodedImage encoded_image() { return encoded_image_; } size_t encoded_bytes() { return encoded_bytes_; } private: webrtc::EncodedImage encoded_image_; FILE* encoded_file_; size_t encoded_bytes_; }; Vp8SequenceCoderEncodeCallback::~Vp8SequenceCoderEncodeCallback() { delete [] encoded_image_._buffer; encoded_image_._buffer = NULL; } int Vp8SequenceCoderEncodeCallback::Encoded( const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codecSpecificInfo, const webrtc::RTPFragmentationHeader* fragmentation) { if (encoded_image_._size < encoded_image._size) { delete [] encoded_image_._buffer; encoded_image_._buffer = NULL; encoded_image_._buffer = new uint8_t[encoded_image._size]; encoded_image_._size = encoded_image._size; } memcpy(encoded_image_._buffer, encoded_image._buffer, encoded_image._size); encoded_image_._length = encoded_image._length; if (encoded_file_ != NULL) { if (fwrite(encoded_image._buffer, 1, encoded_image._length, encoded_file_) != encoded_image._length) { return -1; } } encoded_bytes_ += encoded_image_._length; return 0; } // TODO(mikhal): Add support for varying the frame size. class Vp8SequenceCoderDecodeCallback : public webrtc::DecodedImageCallback { public: explicit Vp8SequenceCoderDecodeCallback(FILE* decoded_file) : decoded_file_(decoded_file) {} int Decoded(webrtc::I420VideoFrame& frame); bool DecodeComplete(); private: FILE* decoded_file_; }; int Vp8SequenceCoderDecodeCallback::Decoded(webrtc::I420VideoFrame& image) { EXPECT_EQ(0, webrtc::PrintI420VideoFrame(image, decoded_file_)); return 0; } int SequenceCoder(webrtc::test::CommandLineParser& parser) { int width = strtol((parser.GetFlag("w")).c_str(), NULL, 10); int height = strtol((parser.GetFlag("h")).c_str(), NULL, 10); int framerate = strtol((parser.GetFlag("f")).c_str(), NULL, 10); if (width <= 0 || height <= 0 || framerate <= 0) { fprintf(stderr, "Error: Resolution cannot be <= 0!\n"); return -1; } int target_bitrate = strtol((parser.GetFlag("b")).c_str(), NULL, 10); if (target_bitrate <= 0) { fprintf(stderr, "Error: Bit-rate cannot be <= 0!\n"); return -1; } // SetUp // Open input file. std::string encoded_file_name = parser.GetFlag("encoded_file"); FILE* encoded_file = fopen(encoded_file_name.c_str(), "wb"); if (encoded_file == NULL) { fprintf(stderr, "Error: Cannot open encoded file\n"); return -1; } std::string input_file_name = parser.GetFlag("input_file"); FILE* input_file = fopen(input_file_name.c_str(), "rb"); if (input_file == NULL) { fprintf(stderr, "Error: Cannot open input file\n"); return -1; } // Open output file. std::string output_file_name = parser.GetFlag("output_file"); FILE* output_file = fopen(output_file_name.c_str(), "wb"); if (output_file == NULL) { fprintf(stderr, "Error: Cannot open output file\n"); return -1; } // Get range of frames: will encode num_frames following start_frame). int start_frame = strtol((parser.GetFlag("start_frame")).c_str(), NULL, 10); int num_frames = strtol((parser.GetFlag("num_frames")).c_str(), NULL, 10); // Codec SetUp. webrtc::VideoCodec inst; memset(&inst, 0, sizeof(inst)); webrtc::VP8Encoder* encoder = webrtc::VP8Encoder::Create(); webrtc::VP8Decoder* decoder = webrtc::VP8Decoder::Create(); inst.codecType = webrtc::kVideoCodecVP8; inst.codecSpecific.VP8.feedbackModeOn = false; inst.codecSpecific.VP8.denoisingOn = true; inst.maxFramerate = framerate; inst.startBitrate = target_bitrate; inst.maxBitrate = 8000; inst.width = width; inst.height = height; if (encoder->InitEncode(&inst, 1, 1440) < 0) { fprintf(stderr, "Error: Cannot initialize vp8 encoder\n"); return -1; } EXPECT_EQ(0, decoder->InitDecode(&inst, 1)); webrtc::I420VideoFrame input_frame; size_t length = webrtc::CalcBufferSize(webrtc::kI420, width, height); rtc::scoped_ptr<uint8_t[]> frame_buffer(new uint8_t[length]); int half_width = (width + 1) / 2; // Set and register callbacks. Vp8SequenceCoderEncodeCallback encoder_callback(encoded_file); encoder->RegisterEncodeCompleteCallback(&encoder_callback); Vp8SequenceCoderDecodeCallback decoder_callback(output_file); decoder->RegisterDecodeCompleteCallback(&decoder_callback); // Read->Encode->Decode sequence. // num_frames = -1 implies unlimited encoding (entire sequence). int64_t starttime = webrtc::TickTime::MillisecondTimestamp(); int frame_cnt = 1; int frames_processed = 0; input_frame.CreateEmptyFrame(width, height, width, half_width, half_width); while (!feof(input_file) && (num_frames == -1 || frames_processed < num_frames)) { if (fread(frame_buffer.get(), 1, length, input_file) != length) continue; if (frame_cnt >= start_frame) { webrtc::ConvertToI420(webrtc::kI420, frame_buffer.get(), 0, 0, width, height, 0, webrtc::kVideoRotation_0, &input_frame); encoder->Encode(input_frame, NULL, NULL); decoder->Decode(encoder_callback.encoded_image(), false, NULL); ++frames_processed; } ++frame_cnt; } printf("\nProcessed %d frames\n", frames_processed); int64_t endtime = webrtc::TickTime::MillisecondTimestamp(); int64_t totalExecutionTime = endtime - starttime; printf("Total execution time: %.2lf ms\n", static_cast<double>(totalExecutionTime)); double actual_bit_rate = 8.0 * encoder_callback.encoded_bytes() / (frame_cnt / inst.maxFramerate); printf("Actual bitrate: %f kbps\n", actual_bit_rate / 1000); webrtc::test::QualityMetricsResult psnr_result, ssim_result; EXPECT_EQ(0, webrtc::test::I420MetricsFromFiles( input_file_name.c_str(), output_file_name.c_str(), inst.width, inst.height, &psnr_result, &ssim_result)); printf("PSNR avg: %f[dB], min: %f[dB]\nSSIM avg: %f, min: %f\n", psnr_result.average, psnr_result.min, ssim_result.average, ssim_result.min); return frame_cnt; } int main(int argc, char** argv) { std::string program_name = argv[0]; std::string usage = "Encode and decodes a video sequence, and writes" "results to a file.\n" "Example usage:\n" + program_name + " functionality" " --w=352 --h=288 --input_file=input.yuv --output_file=output.yuv " " Command line flags:\n" " - width(int): The width of the input file. Default: 352\n" " - height(int): The height of the input file. Default: 288\n" " - input_file(string): The YUV file to encode." " Default: foreman.yuv\n" " - encoded_file(string): The vp8 encoded file (encoder output)." " Default: vp8_encoded.vp8\n" " - output_file(string): The yuv decoded file (decoder output)." " Default: vp8_decoded.yuv\n." " - start_frame - frame number in which encoding will begin. Default: 0" " - num_frames - Number of frames to be processed. " " Default: -1 (entire sequence)."; webrtc::test::CommandLineParser parser; // Init the parser and set the usage message. parser.Init(argc, argv); parser.SetUsageMessage(usage); // Reset flags. parser.SetFlag("w", "352"); parser.SetFlag("h", "288"); parser.SetFlag("f", "30"); parser.SetFlag("b", "500"); parser.SetFlag("start_frame", "0"); parser.SetFlag("num_frames", "-1"); parser.SetFlag("output_file", webrtc::test::OutputPath() + "vp8_decoded.yuv"); parser.SetFlag("encoded_file", webrtc::test::OutputPath() + "vp8_encoded.vp8"); parser.SetFlag("input_file", webrtc::test::ResourcePath("foreman_cif", "yuv")); parser.SetFlag("help", "false"); parser.ProcessFlags(); if (parser.GetFlag("help") == "true") { parser.PrintUsageMessage(); } parser.PrintEnteredFlags(); return SequenceCoder(parser); }
Add missing call to SetUsageMessage().
vp8: Add missing call to SetUsageMessage(). Without it vp8_coder --help does not work. BUG=None TEST=ninja -C out/Debug && out/Debug/vp8_coder --help now shows the usage message. [email protected] Review URL: https://webrtc-codereview.appspot.com/44649005 Patch from Thiago Farina <[email protected]>. git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@8783 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758
65044e8ba223bc01dc8731d6d1207cce8dc471d8
cpp/openlocationcode_test.cc
cpp/openlocationcode_test.cc
#include "openlocationcode.h" #include <stdio.h> #include <stdlib.h> #include <fstream> #include <string> #include "codearea.h" #include "gtest/gtest.h" namespace openlocationcode { namespace internal { namespace { TEST(ParameterChecks, PairCodeLengthIsEven) { EXPECT_EQ(0, internal::kPairCodeLength % 2); } TEST(ParameterChecks, AlphabetIsOrdered) { char last = 0; for (size_t i = 0; i < internal::kEncodingBase; i++) { EXPECT_TRUE(internal::kAlphabet[i] > last); last = internal::kAlphabet[i]; } } TEST(ParameterChecks, SeparatorPositionValid) { EXPECT_TRUE(internal::kSeparatorPosition <= internal::kPairCodeLength); } TEST(ParameterChecks, ShortenDegreesValid) { EXPECT_TRUE(internal::kMinShortenDegrees >= internal::kGridSizeDegrees); } } // namespace } // namespace internal namespace { std::vector<std::vector<std::string>> ParseCsv( const std::string& path_to_file) { std::vector<std::vector<std::string>> csv_records; std::string line; std::ifstream input_stream(path_to_file, std::ifstream::binary); while (std::getline(input_stream, line)) { // Ignore comments in the file if (line.at(0) == '#') { continue; } std::vector<std::string> line_records; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { line_records.push_back(cell); } csv_records.push_back(line_records); } EXPECT_GT(csv_records.size(), 0); return csv_records; } struct EncodingTestData { std::string code; double lat_deg; double lng_deg; double lo_lat_deg; double lo_lng_deg; double hi_lat_deg; double hi_lng_deg; }; class EncodingChecks : public ::testing::TestWithParam<EncodingTestData> {}; const std::string kEncodingTestsFile = "test_data/encodingTests.csv"; std::vector<EncodingTestData> GetEncodingDataFromCsv() { std::vector<EncodingTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kEncodingTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { EncodingTestData test_data = {}; test_data.code = csv_records[i][0]; test_data.lat_deg = strtod(csv_records[i][1].c_str(), nullptr); test_data.lng_deg = strtod(csv_records[i][2].c_str(), nullptr); test_data.lo_lat_deg = strtod(csv_records[i][3].c_str(), nullptr); test_data.lo_lng_deg = strtod(csv_records[i][4].c_str(), nullptr); test_data.hi_lat_deg = strtod(csv_records[i][5].c_str(), nullptr); test_data.hi_lng_deg = strtod(csv_records[i][6].c_str(), nullptr); data_results.push_back(test_data); } return data_results; } TEST_P(EncodingChecks, Encode) { EncodingTestData test_data = GetParam(); CodeArea expected_rect = CodeArea(test_data.lo_lat_deg, test_data.lo_lng_deg, test_data.hi_lat_deg, test_data.hi_lng_deg, CodeLength(test_data.code)); LatLng lat_lng = LatLng{test_data.lat_deg, test_data.lng_deg}; // Encode the test location and make sure we get the expected code. std::string actual_code = Encode(lat_lng, CodeLength(test_data.code)); EXPECT_EQ(test_data.code, actual_code); // Now decode the code and check we get the correct coordinates. CodeArea actual_rect = Decode(test_data.code); EXPECT_NEAR(expected_rect.GetCenter().latitude, actual_rect.GetCenter().latitude, 1e-10); EXPECT_NEAR(expected_rect.GetCenter().longitude, actual_rect.GetCenter().longitude, 1e-10); } INSTANTIATE_TEST_CASE_P(OLC_Tests, EncodingChecks, ::testing::ValuesIn(GetEncodingDataFromCsv())); struct ValidityTestData { std::string code; bool is_valid; bool is_short; bool is_full; }; class ValidityChecks : public ::testing::TestWithParam<ValidityTestData> {}; const std::string kValidityTestsFile = "test_data/validityTests.csv"; std::vector<ValidityTestData> GetValidityDataFromCsv() { std::vector<ValidityTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kValidityTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { ValidityTestData test_data = {}; test_data.code = csv_records[i][0]; test_data.is_valid = csv_records[i][1] == "true"; test_data.is_short = csv_records[i][2] == "true"; test_data.is_full = csv_records[i][3] == "true"; data_results.push_back(test_data); } return data_results; } TEST_P(ValidityChecks, Validity) { ValidityTestData test_data = GetParam(); EXPECT_EQ(test_data.is_valid, IsValid(test_data.code)); EXPECT_EQ(test_data.is_full, IsFull(test_data.code)); EXPECT_EQ(test_data.is_short, IsShort(test_data.code)); } INSTANTIATE_TEST_CASE_P(OLC_Tests, ValidityChecks, ::testing::ValuesIn(GetValidityDataFromCsv())); struct ShortCodeTestData { std::string full_code; double reference_lat; double reference_lng; std::string short_code; std::string test_type; }; class ShortCodeChecks : public ::testing::TestWithParam<ShortCodeTestData> {}; const std::string kShortCodeTestsFile = "test_data/shortCodeTests.csv"; std::vector<ShortCodeTestData> GetShortCodeDataFromCsv() { std::vector<ShortCodeTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kShortCodeTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { ShortCodeTestData test_data = {}; test_data.full_code = csv_records[i][0]; test_data.reference_lat = strtod(csv_records[i][1].c_str(), nullptr); test_data.reference_lng = strtod(csv_records[i][2].c_str(), nullptr); test_data.short_code = csv_records[i][3]; test_data.test_type = csv_records[i][4]; data_results.push_back(test_data); } return data_results; } TEST_P(ShortCodeChecks, ShortCode) { ShortCodeTestData test_data = GetParam(); LatLng reference_loc = LatLng{test_data.reference_lat, test_data.reference_lng}; // Shorten the code using the reference location and check. if (test_data.test_type == "B" || test_data.test_type == "S") { std::string actual_short = Shorten(test_data.full_code, reference_loc); EXPECT_EQ(test_data.short_code, actual_short); } // Now extend the code using the reference location and check. if (test_data.test_type == "B" || test_data.test_type == "R") { std::string actual_full = RecoverNearest(test_data.short_code, reference_loc); EXPECT_EQ(test_data.full_code, actual_full); } } INSTANTIATE_TEST_CASE_P(OLC_Tests, ShortCodeChecks, ::testing::ValuesIn(GetShortCodeDataFromCsv())); TEST(MaxCodeLengthChecks, MaxCodeLength) { LatLng loc = LatLng{51.3701125, -10.202665625}; // Check we do not return a code longer than is valid. std::string long_code = Encode(loc, 1000000); // The code length is the maximum digit count plus one for the separator. EXPECT_EQ(long_code.size(), 1 + internal::kMaximumDigitCount); EXPECT_TRUE(IsValid(long_code)); Decode(long_code); // Extend the code and make sure it is no longer valid. std::string too_long_code = long_code + "W"; EXPECT_FALSE(IsValid(too_long_code)); // Ensure too many characters after the separator also causes a fail, even if // the total number of characters is ok. too_long_code = long_code.substr(6) + "WW"; EXPECT_TRUE(too_long_code.size() < internal::kMaximumDigitCount); EXPECT_FALSE(IsValid(too_long_code)); } } // namespace } // namespace openlocationcode
#include "openlocationcode.h" #include <stdio.h> #include <stdlib.h> #include <fstream> #include <string> #include "codearea.h" #include "gtest/gtest.h" namespace openlocationcode { namespace internal { namespace { TEST(ParameterChecks, PairCodeLengthIsEven) { EXPECT_EQ(0, internal::kPairCodeLength % 2); } TEST(ParameterChecks, AlphabetIsOrdered) { char last = 0; for (size_t i = 0; i < internal::kEncodingBase; i++) { EXPECT_TRUE(internal::kAlphabet[i] > last); last = internal::kAlphabet[i]; } } TEST(ParameterChecks, PositionLUTMatchesAlphabet) { // Loop over all elements of the lookup table. for (size_t i = 0; i < sizeof(internal::kPositionLUT) / sizeof(internal::kPositionLUT[0]); ++i) { const int pos = internal::kPositionLUT[i]; const char c = 'C' + i; if (pos != -1) { // If the LUT entry indicates this character is in kAlphabet, verify it. EXPECT_LT(pos, internal::kEncodingBase); EXPECT_EQ(c, internal::kAlphabet[pos]); } else { // Otherwise, verify this character is not in kAlphabet. const char* end = internal::kAlphabet + internal::kEncodingBase; EXPECT_EQ(std::find(internal::kAlphabet, end, c), end); } } } TEST(ParameterChecks, SeparatorPositionValid) { EXPECT_TRUE(internal::kSeparatorPosition <= internal::kPairCodeLength); } TEST(ParameterChecks, ShortenDegreesValid) { EXPECT_TRUE(internal::kMinShortenDegrees >= internal::kGridSizeDegrees); } } // namespace } // namespace internal namespace { std::vector<std::vector<std::string>> ParseCsv( const std::string& path_to_file) { std::vector<std::vector<std::string>> csv_records; std::string line; std::ifstream input_stream(path_to_file, std::ifstream::binary); while (std::getline(input_stream, line)) { // Ignore comments in the file if (line.at(0) == '#') { continue; } std::vector<std::string> line_records; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { line_records.push_back(cell); } csv_records.push_back(line_records); } EXPECT_GT(csv_records.size(), 0); return csv_records; } struct EncodingTestData { std::string code; double lat_deg; double lng_deg; double lo_lat_deg; double lo_lng_deg; double hi_lat_deg; double hi_lng_deg; }; class EncodingChecks : public ::testing::TestWithParam<EncodingTestData> {}; const std::string kEncodingTestsFile = "test_data/encodingTests.csv"; std::vector<EncodingTestData> GetEncodingDataFromCsv() { std::vector<EncodingTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kEncodingTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { EncodingTestData test_data = {}; test_data.code = csv_records[i][0]; test_data.lat_deg = strtod(csv_records[i][1].c_str(), nullptr); test_data.lng_deg = strtod(csv_records[i][2].c_str(), nullptr); test_data.lo_lat_deg = strtod(csv_records[i][3].c_str(), nullptr); test_data.lo_lng_deg = strtod(csv_records[i][4].c_str(), nullptr); test_data.hi_lat_deg = strtod(csv_records[i][5].c_str(), nullptr); test_data.hi_lng_deg = strtod(csv_records[i][6].c_str(), nullptr); data_results.push_back(test_data); } return data_results; } TEST_P(EncodingChecks, Encode) { EncodingTestData test_data = GetParam(); CodeArea expected_rect = CodeArea(test_data.lo_lat_deg, test_data.lo_lng_deg, test_data.hi_lat_deg, test_data.hi_lng_deg, CodeLength(test_data.code)); LatLng lat_lng = LatLng{test_data.lat_deg, test_data.lng_deg}; // Encode the test location and make sure we get the expected code. std::string actual_code = Encode(lat_lng, CodeLength(test_data.code)); EXPECT_EQ(test_data.code, actual_code); // Now decode the code and check we get the correct coordinates. CodeArea actual_rect = Decode(test_data.code); EXPECT_NEAR(expected_rect.GetCenter().latitude, actual_rect.GetCenter().latitude, 1e-10); EXPECT_NEAR(expected_rect.GetCenter().longitude, actual_rect.GetCenter().longitude, 1e-10); } INSTANTIATE_TEST_CASE_P(OLC_Tests, EncodingChecks, ::testing::ValuesIn(GetEncodingDataFromCsv())); struct ValidityTestData { std::string code; bool is_valid; bool is_short; bool is_full; }; class ValidityChecks : public ::testing::TestWithParam<ValidityTestData> {}; const std::string kValidityTestsFile = "test_data/validityTests.csv"; std::vector<ValidityTestData> GetValidityDataFromCsv() { std::vector<ValidityTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kValidityTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { ValidityTestData test_data = {}; test_data.code = csv_records[i][0]; test_data.is_valid = csv_records[i][1] == "true"; test_data.is_short = csv_records[i][2] == "true"; test_data.is_full = csv_records[i][3] == "true"; data_results.push_back(test_data); } return data_results; } TEST_P(ValidityChecks, Validity) { ValidityTestData test_data = GetParam(); EXPECT_EQ(test_data.is_valid, IsValid(test_data.code)); EXPECT_EQ(test_data.is_full, IsFull(test_data.code)); EXPECT_EQ(test_data.is_short, IsShort(test_data.code)); } INSTANTIATE_TEST_CASE_P(OLC_Tests, ValidityChecks, ::testing::ValuesIn(GetValidityDataFromCsv())); struct ShortCodeTestData { std::string full_code; double reference_lat; double reference_lng; std::string short_code; std::string test_type; }; class ShortCodeChecks : public ::testing::TestWithParam<ShortCodeTestData> {}; const std::string kShortCodeTestsFile = "test_data/shortCodeTests.csv"; std::vector<ShortCodeTestData> GetShortCodeDataFromCsv() { std::vector<ShortCodeTestData> data_results; std::vector<std::vector<std::string>> csv_records = ParseCsv(kShortCodeTestsFile); for (size_t i = 0; i < csv_records.size(); i++) { ShortCodeTestData test_data = {}; test_data.full_code = csv_records[i][0]; test_data.reference_lat = strtod(csv_records[i][1].c_str(), nullptr); test_data.reference_lng = strtod(csv_records[i][2].c_str(), nullptr); test_data.short_code = csv_records[i][3]; test_data.test_type = csv_records[i][4]; data_results.push_back(test_data); } return data_results; } TEST_P(ShortCodeChecks, ShortCode) { ShortCodeTestData test_data = GetParam(); LatLng reference_loc = LatLng{test_data.reference_lat, test_data.reference_lng}; // Shorten the code using the reference location and check. if (test_data.test_type == "B" || test_data.test_type == "S") { std::string actual_short = Shorten(test_data.full_code, reference_loc); EXPECT_EQ(test_data.short_code, actual_short); } // Now extend the code using the reference location and check. if (test_data.test_type == "B" || test_data.test_type == "R") { std::string actual_full = RecoverNearest(test_data.short_code, reference_loc); EXPECT_EQ(test_data.full_code, actual_full); } } INSTANTIATE_TEST_CASE_P(OLC_Tests, ShortCodeChecks, ::testing::ValuesIn(GetShortCodeDataFromCsv())); TEST(MaxCodeLengthChecks, MaxCodeLength) { LatLng loc = LatLng{51.3701125, -10.202665625}; // Check we do not return a code longer than is valid. std::string long_code = Encode(loc, 1000000); // The code length is the maximum digit count plus one for the separator. EXPECT_EQ(long_code.size(), 1 + internal::kMaximumDigitCount); EXPECT_TRUE(IsValid(long_code)); Decode(long_code); // Extend the code and make sure it is no longer valid. std::string too_long_code = long_code + "W"; EXPECT_FALSE(IsValid(too_long_code)); // Ensure too many characters after the separator also causes a fail, even if // the total number of characters is ok. too_long_code = long_code.substr(6) + "WW"; EXPECT_TRUE(too_long_code.size() < internal::kMaximumDigitCount); EXPECT_FALSE(IsValid(too_long_code)); } } // namespace } // namespace openlocationcode
Add unit test to verify internal::kPositionLUT
Add unit test to verify internal::kPositionLUT Add unit test PositionLUTMatchesAlphabet to verify that internal::kPositionLUT matches the contents of internal::kAlphabet.
C++
apache-2.0
google/open-location-code,zongweil/open-location-code,google/open-location-code,zongweil/open-location-code,bocops/open-location-code,zongweil/open-location-code,zongweil/open-location-code,google/open-location-code,google/open-location-code,google/open-location-code,google/open-location-code,google/open-location-code,bocops/open-location-code,zongweil/open-location-code,google/open-location-code,bocops/open-location-code,bocops/open-location-code,zongweil/open-location-code,zongweil/open-location-code,bocops/open-location-code,zongweil/open-location-code,bocops/open-location-code,bocops/open-location-code,google/open-location-code,zongweil/open-location-code,bocops/open-location-code,zongweil/open-location-code,google/open-location-code,bocops/open-location-code,bocops/open-location-code,bocops/open-location-code,zongweil/open-location-code,google/open-location-code
4fb28d1d025eda15f1f61cc6b48ed7fb1898e8dd
src/os/async_thread.cc
src/os/async_thread.cc
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole_api.h" #include "async.h" #include <thread> #include <atomic> #include <unordered_map> #include <condition_variable> #include <mutex> #include <queue> using namespace std; typedef swAio_event async_event; swAsyncIO SwooleAIO; static void swAio_free(void *private_data); int swAio_callback(swReactor *reactor, swEvent *_event) { int i; async_event *events[SW_AIO_EVENT_NUM]; ssize_t n = read(_event->fd, events, sizeof(async_event*) * SW_AIO_EVENT_NUM); if (n < 0) { swSysWarn("read() failed"); return SW_ERR; } for (i = 0; i < n / (int) sizeof(async_event*); i++) { if (!events[i]->canceled) { events[i]->callback(events[i]); } SwooleAIO.task_num--; delete events[i]; } return SW_OK; } struct thread_context { thread *_thread; atomic<bool> *_exit_flag; thread_context(thread *_thread, atomic<bool> *_exit_flag) : _thread(_thread), _exit_flag(_exit_flag) { } }; class async_event_queue { public: inline bool push(async_event *event) { unique_lock<mutex> lock(_mutex); _queue.push(event); return true; } inline async_event* pop() { unique_lock<mutex> lock(_mutex); if (_queue.empty()) { return nullptr; } async_event* retval = _queue.front(); _queue.pop(); return retval; } inline bool empty() { unique_lock<mutex> lock(_mutex); return _queue.empty(); } inline size_t count() { return _queue.size(); } private: queue<async_event*> _queue; mutex _mutex; }; class async_thread_pool { public: async_thread_pool(size_t _min_threads, size_t _max_threads) { n_waiting = 0; running = false; min_threads = _min_threads; max_threads = _max_threads; current_task_id = 0; current_pid = getpid(); if (swPipeBase_create(&_aio_pipe, 0) < 0) { swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL); } _pipe_read = _aio_pipe.getFd(&_aio_pipe, 0); _pipe_write = _aio_pipe.getFd(&_aio_pipe, 1); swoole_event_add(_pipe_read, SW_EVENT_READ, SW_FD_AIO); } ~async_thread_pool() { shutdown(); if (SwooleTG.reactor) { swoole_event_del(_pipe_read); } _aio_pipe.close(&_aio_pipe); } void schedule() { //++ if (n_waiting == 0 && threads.size() < max_threads) { create_thread(); } //-- else if (n_waiting > min_threads) { thread_context *tc = &threads.front(); *tc->_exit_flag = false; tc->_thread->detach(); delete tc->_thread; threads.pop(); } } bool start() { running = true; for (size_t i = 0; i < min_threads; i++) { create_thread(); } return true; } bool shutdown() { if (!running) { return false; } running = false; _mutex.lock(); _cv.notify_all(); _mutex.unlock(); while (!threads.empty()) { thread_context *tc = &threads.front(); if (tc->_thread->joinable()) { tc->_thread->join(); } threads.pop(); } return true; } async_event* dispatch(const async_event *request) { auto _event_copy = new async_event(*request); schedule(); _event_copy->task_id = current_task_id++; queue.push(_event_copy); _cv.notify_one(); return _event_copy; } inline size_t thread_count() { return threads.size(); } inline size_t queue_count() { return queue.count(); } pid_t current_pid; private: void create_thread() { atomic<bool> *exit_flag = new atomic<bool>(false); try { thread *_thread = new thread([this, &exit_flag]() { SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE); if (SwooleTG.buffer_stack == nullptr) { return; } swSignal_none(); while (running) { async_event *event; event = queue.pop(); if (event) { if (sw_unlikely(event->handler == nullptr)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else if (sw_unlikely(event->canceled)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else { event->handler(event); } swTrace("aio_thread ok. ret=%d, error=%d", event->ret, event->error); _error: while (true) { SwooleAIO.lock.lock(&SwooleAIO.lock); int ret = write(_pipe_write, &event, sizeof(event)); SwooleAIO.lock.unlock(&SwooleAIO.lock); if (ret < 0) { if (errno == EAGAIN) { swSocket_wait(_pipe_write, 1000, SW_EVENT_WRITE); continue; } else if (errno == EINTR) { continue; } else { swSysWarn("sendto swoole_aio_pipe_write failed"); } } break; } // exit if (*exit_flag) { break; } } else { unique_lock<mutex> lock(_mutex); if (running) { ++n_waiting; _cv.wait(lock); --n_waiting; } } } delete exit_flag; }); threads.push(thread_context(_thread, exit_flag)); } catch (const std::system_error& e) { swSysNotice("create aio thread failed, please check your system configuration or adjust max_thread_count"); delete exit_flag; return; } } size_t min_threads; size_t max_threads; swPipe _aio_pipe; int _pipe_read; int _pipe_write; int current_task_id; queue<thread_context> threads; async_event_queue queue; bool running; atomic<int> n_waiting; mutex _mutex; condition_variable _cv; }; static async_thread_pool *pool = nullptr; static int swAio_init() { if (SwooleAIO.init) { swWarn("AIO has already been initialized"); return SW_ERR; } if (!SwooleTG.reactor) { swWarn("no event loop, cannot initialized"); return SW_ERR; } if (swMutex_create(&SwooleAIO.lock, 0) < 0) { swWarn("create mutex lock error"); return SW_ERR; } if (SwooleAIO.min_thread_num == 0) { SwooleAIO.min_thread_num = SW_AIO_THREAD_DEFAULT_NUM; } if (SwooleAIO.max_thread_num == 0) { SwooleAIO.max_thread_num = (SW_CPU_NUM * 2) * SW_AIO_THREAD_NUM_MULTIPLE; } if (SwooleAIO.min_thread_num > SwooleAIO.max_thread_num) { SwooleAIO.max_thread_num = SwooleAIO.min_thread_num; } swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr); pool = new async_thread_pool(SwooleAIO.min_thread_num, SwooleAIO.max_thread_num); pool->start(); SwooleAIO.init = 1; return SW_OK; } size_t swAio_thread_count() { return pool ? pool->thread_count() : 0; } int swAio_dispatch(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; async_event *event = pool->dispatch(request); return event->task_id; } swAio_event* swAio_dispatch2(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; return pool->dispatch(request); } static void swAio_free(void *private_data) { if (!SwooleAIO.init) { return; } if (pool->current_pid == getpid()) { delete pool; } pool = nullptr; SwooleAIO.init = 0; }
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole_api.h" #include "async.h" #include <thread> #include <atomic> #include <unordered_map> #include <condition_variable> #include <mutex> #include <queue> using namespace std; typedef swAio_event async_event; swAsyncIO SwooleAIO; static void swAio_free(void *private_data); int swAio_callback(swReactor *reactor, swEvent *_event) { int i; async_event *events[SW_AIO_EVENT_NUM]; ssize_t n = read(_event->fd, events, sizeof(async_event*) * SW_AIO_EVENT_NUM); if (n < 0) { swSysWarn("read() failed"); return SW_ERR; } for (i = 0; i < n / (int) sizeof(async_event*); i++) { if (!events[i]->canceled) { events[i]->callback(events[i]); } SwooleAIO.task_num--; delete events[i]; } return SW_OK; } struct thread_context { thread *_thread; atomic<bool> *_exit_flag; thread_context(thread *_thread, atomic<bool> *_exit_flag) : _thread(_thread), _exit_flag(_exit_flag) { } }; class async_event_queue { public: inline bool push(async_event *event) { unique_lock<mutex> lock(_mutex); _queue.push(event); return true; } inline async_event* pop() { unique_lock<mutex> lock(_mutex); if (_queue.empty()) { return nullptr; } async_event* retval = _queue.front(); _queue.pop(); return retval; } inline bool empty() { unique_lock<mutex> lock(_mutex); return _queue.empty(); } inline size_t count() { return _queue.size(); } private: queue<async_event*> _queue; mutex _mutex; }; class async_thread_pool { public: async_thread_pool(size_t _min_threads, size_t _max_threads) { n_waiting = 0; running = false; min_threads = _min_threads; max_threads = _max_threads; current_task_id = 0; current_pid = getpid(); if (swPipeBase_create(&_aio_pipe, 0) < 0) { swoole_throw_error(SW_ERROR_SYSTEM_CALL_FAIL); } _pipe_read = _aio_pipe.getFd(&_aio_pipe, 0); _pipe_write = _aio_pipe.getFd(&_aio_pipe, 1); swoole_event_add(_pipe_read, SW_EVENT_READ, SW_FD_AIO); } ~async_thread_pool() { shutdown(); if (SwooleTG.reactor) { swoole_event_del(_pipe_read); } _aio_pipe.close(&_aio_pipe); } void schedule() { //++ if (n_waiting == 0 && threads.size() < max_threads) { create_thread(); } //-- else if (n_waiting > min_threads) { thread_context *tc = &threads.front(); *tc->_exit_flag = false; tc->_thread->detach(); delete tc->_thread; threads.pop(); } } bool start() { running = true; for (size_t i = 0; i < min_threads; i++) { create_thread(); } return true; } bool shutdown() { if (!running) { return false; } running = false; _mutex.lock(); _cv.notify_all(); _mutex.unlock(); while (!threads.empty()) { thread_context *tc = &threads.front(); if (tc->_thread->joinable()) { tc->_thread->join(); } threads.pop(); } return true; } async_event* dispatch(const async_event *request) { auto _event_copy = new async_event(*request); schedule(); _event_copy->task_id = current_task_id++; _queue.push(_event_copy); _cv.notify_one(); return _event_copy; } inline size_t thread_count() { return threads.size(); } inline size_t queue_count() { return _queue.count(); } pid_t current_pid; private: void create_thread() { atomic<bool> *exit_flag = new atomic<bool>(false); try { thread *_thread = new thread([this, &exit_flag]() { SwooleTG.buffer_stack = swString_new(SW_STACK_BUFFER_SIZE); if (SwooleTG.buffer_stack == nullptr) { return; } swSignal_none(); while (running) { async_event *event; event = _queue.pop(); if (event) { if (sw_unlikely(event->handler == nullptr)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else if (sw_unlikely(event->canceled)) { event->error = SW_ERROR_AIO_BAD_REQUEST; event->ret = -1; goto _error; } else { event->handler(event); } swTrace("aio_thread ok. ret=%d, error=%d", event->ret, event->error); _error: while (true) { SwooleAIO.lock.lock(&SwooleAIO.lock); int ret = write(_pipe_write, &event, sizeof(event)); SwooleAIO.lock.unlock(&SwooleAIO.lock); if (ret < 0) { if (errno == EAGAIN) { swSocket_wait(_pipe_write, 1000, SW_EVENT_WRITE); continue; } else if (errno == EINTR) { continue; } else { swSysWarn("sendto swoole_aio_pipe_write failed"); } } break; } // exit if (*exit_flag) { break; } } else { unique_lock<mutex> lock(_mutex); if (running) { ++n_waiting; _cv.wait(lock); --n_waiting; } } } delete exit_flag; }); threads.push(thread_context(_thread, exit_flag)); } catch (const std::system_error& e) { swSysNotice("create aio thread failed, please check your system configuration or adjust max_thread_count"); delete exit_flag; return; } } size_t min_threads; size_t max_threads; swPipe _aio_pipe; int _pipe_read; int _pipe_write; int current_task_id; queue<thread_context> threads; async_event_queue _queue; bool running; atomic<int> n_waiting; mutex _mutex; condition_variable _cv; }; static async_thread_pool *pool = nullptr; static int swAio_init() { if (SwooleAIO.init) { swWarn("AIO has already been initialized"); return SW_ERR; } if (!SwooleTG.reactor) { swWarn("no event loop, cannot initialized"); return SW_ERR; } if (swMutex_create(&SwooleAIO.lock, 0) < 0) { swWarn("create mutex lock error"); return SW_ERR; } if (SwooleAIO.min_thread_num == 0) { SwooleAIO.min_thread_num = SW_AIO_THREAD_DEFAULT_NUM; } if (SwooleAIO.max_thread_num == 0) { SwooleAIO.max_thread_num = (SW_CPU_NUM * 2) * SW_AIO_THREAD_NUM_MULTIPLE; } if (SwooleAIO.min_thread_num > SwooleAIO.max_thread_num) { SwooleAIO.max_thread_num = SwooleAIO.min_thread_num; } swReactor_add_destroy_callback(SwooleTG.reactor, swAio_free, nullptr); pool = new async_thread_pool(SwooleAIO.min_thread_num, SwooleAIO.max_thread_num); pool->start(); SwooleAIO.init = 1; return SW_OK; } size_t swAio_thread_count() { return pool ? pool->thread_count() : 0; } int swAio_dispatch(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; async_event *event = pool->dispatch(request); return event->task_id; } swAio_event* swAio_dispatch2(const swAio_event *request) { if (sw_unlikely(!SwooleAIO.init)) { swAio_init(); } SwooleAIO.task_num++; return pool->dispatch(request); } static void swAio_free(void *private_data) { if (!SwooleAIO.init) { return; } if (pool->current_pid == getpid()) { delete pool; } pool = nullptr; SwooleAIO.init = 0; }
Fix compilation
Fix compilation
C++
apache-2.0
LinkedDestiny/swoole-src,swoole/swoole-src,LinkedDestiny/swoole-src,LinkedDestiny/swoole-src,LinkedDestiny/swoole-src,LinkedDestiny/swoole-src,swoole/swoole-src,swoole/swoole-src,swoole/swoole-src,swoole/swoole-src,swoole/swoole-src,LinkedDestiny/swoole-src,LinkedDestiny/swoole-src,swoole/swoole-src
be21e8d19d5abfcc3629532ca886b56834bb9478
deps/CoinQ/src/CoinQ_blocks.cpp
deps/CoinQ/src/CoinQ_blocks.cpp
/////////////////////////////////////////////////////////////////////////////// // // CoinQ_blocks.cpp // // Copyright (c) 2013 Eric Lombrozo // // All Rights Reserved. #include "CoinQ_blocks.h" #include <logger/logger.h> using namespace CoinQ; bool CoinQBlockTreeMem::setBestChain(ChainHeader& header) { if (header.inBestChain) return false; // Retrace back to earliest best block std::stack<ChainHeader*> newBestChain; ChainHeader* pParent = &header; while (!pParent->inBestChain) { newBestChain.push(pParent); pParent = &mHeaderHashMap.at(pParent->prevBlockHash()); } for (auto it = pParent->childHashes.begin(); it != pParent->childHashes.end(); ++it) { ChainHeader& child = mHeaderHashMap.at(*it); if (child.inBestChain) { unsetBestChain(child); break; } } // First set these so we have the most current info. mBestHeight = header.height; mTotalWork = header.chainWork; // Pop back up stack and make this the best chain int count = 0; while (!newBestChain.empty()) { ChainHeader* pChild = newBestChain.top(); pChild->inBestChain = true; mHeaderHeightMap[pChild->height] = pChild; if (count == 0) notifyReorg(*pChild); notifyAddBestChain(*pChild); newBestChain.pop(); count++; } pHead = &header; return true; } bool CoinQBlockTreeMem::unsetBestChain(ChainHeader& header) { if (!header.inBestChain) return false; if (header.height == 0) throw std::runtime_error("Cannot remove genesis block from best chain."); ChainHeader* pParent = &mHeaderHashMap.at(header.prevBlockHash()); if (pParent->inBestChain) { mBestHeight = pParent->height; mTotalWork = pParent->chainWork; } header.inBestChain = false; notifyRemoveBestChain(header); pParent = &header; while (pParent->childHashes.size() != 0) { for (auto it = pParent->childHashes.begin(); it != pParent->childHashes.end(); ++it) { ChainHeader* pChild = &mHeaderHashMap.at(*it); if (pChild->inBestChain) { pParent = pChild; mHeaderHeightMap.erase(pChild->height); pChild->inBestChain = false; notifyRemoveBestChain(*pChild); break; } } } return true; } void CoinQBlockTreeMem::setGenesisBlock(const Coin::CoinBlockHeader& header) { if (mHeaderHashMap.size() != 0) throw std::runtime_error("Tree is not empty."); bFlushed = false; uchar_vector hash = header.hash(); ChainHeader& genesisHeader = mHeaderHashMap[hash] = header; mHeaderHeightMap[0] = &genesisHeader; genesisHeader.height = 0; genesisHeader.inBestChain = true; genesisHeader.chainWork = genesisHeader.getWork(); mBestHeight = 0; mTotalWork = genesisHeader.chainWork; pHead = &genesisHeader; notifyInsert(header); notifyAddBestChain(header); } bool CoinQBlockTreeMem::insertHeader(const Coin::CoinBlockHeader& header, bool bCheckProofOfWork) { if (mHeaderHashMap.size() == 0) throw std::runtime_error("No genesis block."); uchar_vector headerHash = header.hash(); if (hasHeader(headerHash)) return false; header_hash_map_t::iterator it = mHeaderHashMap.find(header.prevBlockHash()); if (it == mHeaderHashMap.end()) throw std::runtime_error("Parent not found."); ChainHeader& parent = it->second; // TODO: Check version, compute work required. // Check timestamp /* if (bCheckTimestamp && header.timestamp > time(NULL) + 2 * 60 * 60) { throw std::runtime_error("Timestamp too far in the future."); }*/ // Check proof of work if (bCheckProofOfWork && BigInt(header.getPOWHashLittleEndian()) > header.getTarget()) throw std::runtime_error("Header hash is too big."); ChainHeader& chainHeader = mHeaderHashMap[headerHash] = header; chainHeader.height = parent.height + 1; chainHeader.chainWork = parent.chainWork + chainHeader.getWork(); parent.childHashes.insert(headerHash); notifyInsert(chainHeader); if (chainHeader.chainWork > mTotalWork) { setBestChain(chainHeader); } bFlushed = false; return true; } bool CoinQBlockTreeMem::deleteHeader(const uchar_vector& hash) { header_hash_map_t::iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end()) return false; ChainHeader& header = it->second; unsetBestChain(header); header_hash_map_t::iterator itParent = mHeaderHashMap.find(header.hash()); if (itParent == mHeaderHashMap.end()) throw std::runtime_error("Critical error: parent for block not found."); // Recurse through children for (auto itChild = header.childHashes.begin(); itChild != header.childHashes.end(); ++itChild) { deleteHeader(*itChild); } // TODO: Find new best chain if this header was in best chain. // Remove header ChainHeader& parent = itParent->second; unsigned int nErased = parent.childHashes.erase(hash); assert(nErased == 1); notifyDelete(header); mHeaderHashMap.erase(hash); bFlushed = false; return true; } bool CoinQBlockTreeMem::hasHeader(const uchar_vector& hash) const { return (mHeaderHashMap.find(hash) != mHeaderHashMap.end()); } const ChainHeader& CoinQBlockTreeMem::getHeader(const uchar_vector& hash) const { header_hash_map_t::const_iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end()) throw std::runtime_error("Not found."); return it->second; } const ChainHeader& CoinQBlockTreeMem::getHeader(int height) const { if (mHeaderHeightMap.size() > 0) { if (height < 0) height += mBestHeight + 1; if (height >= 0) { header_height_map_t::const_iterator it = mHeaderHeightMap.find((unsigned int)height); if (it != mHeaderHeightMap.end()) return *it->second; } } throw std::runtime_error("Not found."); } const ChainHeader& CoinQBlockTreeMem::getTip() const { if (!pHead) throw std::runtime_error("Tree is empty."); return *pHead; } int CoinQBlockTreeMem::getTipHeight() const { if (!pHead) throw std::runtime_error("Tree is empty."); return pHead->height; } const ChainHeader& CoinQBlockTreeMem::getHeaderBefore(uint32_t timestamp) const { if (mBestHeight == -1) throw std::runtime_error("Tree is empty."); int i; for (i = 1; i <= mBestHeight; i++) { ChainHeader* header = mHeaderHeightMap.at(i); if (header->timestamp() > timestamp) break; } return *mHeaderHeightMap.at(i - 1); } std::vector<uchar_vector> CoinQBlockTreeMem::getLocatorHashes(int maxSize = -1) const { std::vector<uchar_vector> locatorHashes; if (mBestHeight == -1) { locatorHashes.push_back(g_zero32bytes); return locatorHashes; } if (maxSize < 0) maxSize = mBestHeight + 1; int i = mBestHeight; int n = 0; int step = 1; while ((i >= 0) && (n < maxSize)) { locatorHashes.push_back(mHeaderHeightMap.at(i)->hash()); i -= step; n++; if (n > 10) step *= 2; } return locatorHashes; } int CoinQBlockTreeMem::getConfirmations(const uchar_vector& hash) const { header_hash_map_t::const_iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end() || !it->second.inBestChain) return 0; return mBestHeight - it->second.height + 1; } void CoinQBlockTreeMem::loadFromFile(const std::string& filename, bool bCheckProofOfWork, CoinQBlockTreeMem::callback_t callback) { boost::filesystem::path p(filename); if (!boost::filesystem::exists(p)) throw BlockTreeFileNotFoundException(); if (!boost::filesystem::is_regular_file(p)) throw BlockTreeInvalidFileTypeException(); const unsigned int RECORD_SIZE = MIN_COIN_BLOCK_HEADER_SIZE + 4; if (boost::filesystem::file_size(p) % RECORD_SIZE != 0) throw BlockTreeInvalidFileLengthException(); #ifndef _WIN32 std::ifstream fs(p.native(), std::ios::binary); #else std::ifstream fs(filename, std::ios::binary); #endif if (!fs.good()) throw BlockTreeFailedToOpenFileForReadException(); clear(); uchar_vector headerBytes; uchar_vector hash; Coin::CoinBlockHeader header; unsigned int count = 0; char buf[RECORD_SIZE * 64]; while (fs) { fs.read(buf, RECORD_SIZE * 64); if (fs.bad()) throw BlockTreeFileReadFailureException(); unsigned int nbytesread = fs.gcount(); unsigned int pos = 0; for (; pos <= nbytesread - RECORD_SIZE; pos += RECORD_SIZE) { headerBytes.assign((unsigned char*)&buf[pos], (unsigned char*)&buf[pos + MIN_COIN_BLOCK_HEADER_SIZE]); header.setSerialized(headerBytes); hash = header.hash(); if (memcmp(&buf[pos + MIN_COIN_BLOCK_HEADER_SIZE], &hash[0], 4)) throw BlockTreeChecksumErrorException(); try { if (mBestHeight >= 0) { insertHeader(header, bCheckProofOfWork); if (count % 10000 == 0) { if (callback && !callback(*this)) throw BlockTreeLoadInterruptedException(); LOGGER(debug) << "CoinQBlockTreeMem::loadFromFile() - header hash: " << header.hash().getHex() << " height: " << count << std::endl; } count++; } else { setGenesisBlock(header); if (callback && !callback(*this)) throw BlockTreeLoadInterruptedException(); LOGGER(debug) << "CoinQBlockTreeMem::loadFromFile() - genesis hash: " << header.hash().getHex() << std::endl; count++; } } catch (const BlockTreeException& e) { throw e; } catch (const std::exception& e) { throw std::runtime_error(std::string("Block ") + hash.getHex() + ": " + e.what()); } } if (pos != nbytesread) throw BlockTreeUnexpectedEndOfFileException(); } if (callback) callback(*this); // No need to interrupt since we're done. } void CoinQBlockTreeMem::flushToFile(const std::string& filename) { if (mBestHeight == -1) throw std::runtime_error("Tree is empty."); boost::filesystem::path swapfile(filename + ".swp"); if (boost::filesystem::exists(swapfile)) throw BlockTreeSwapfileAlreadyExistsException(); { #ifndef _WIN32 std::ofstream fs(swapfile.native(), std::ios::binary); #else std::ofstream fs(filename + ".swp", std::ios::binary); #endif uchar_vector headerBytes, hash; for (int i = 0; i <= mBestHeight; i++) { ChainHeader* pHeader = mHeaderHeightMap.at(i); headerBytes = pHeader->getSerialized(); hash = pHeader->hash(); fs.write((const char*)&headerBytes[0], MIN_COIN_BLOCK_HEADER_SIZE); if (fs.bad()) throw BlockTreeFileWriteFailureException(); fs.write((const char*)&hash[0], 4); if (fs.bad()) throw BlockTreeFileWriteFailureException(); } } boost::system::error_code ec; boost::filesystem::path p(filename); boost::filesystem::rename(swapfile, p, ec); if (!!ec) throw std::runtime_error(ec.message()); bFlushed = true; }
/////////////////////////////////////////////////////////////////////////////// // // CoinQ_blocks.cpp // // Copyright (c) 2013 Eric Lombrozo // // All Rights Reserved. #include "CoinQ_blocks.h" #include <logger/logger.h> using namespace CoinQ; bool CoinQBlockTreeMem::setBestChain(ChainHeader& header) { if (header.inBestChain) return false; // Retrace back to earliest best block std::stack<ChainHeader*> newBestChain; ChainHeader* pParent = &header; while (!pParent->inBestChain) { newBestChain.push(pParent); pParent = &mHeaderHashMap.at(pParent->prevBlockHash()); } for (auto it = pParent->childHashes.begin(); it != pParent->childHashes.end(); ++it) { ChainHeader& child = mHeaderHashMap.at(*it); if (child.inBestChain) { unsetBestChain(child); break; } } // First set these so we have the most current info. mBestHeight = header.height; mTotalWork = header.chainWork; // Pop back up stack and make this the best chain int count = 0; while (!newBestChain.empty()) { ChainHeader* pChild = newBestChain.top(); pChild->inBestChain = true; mHeaderHeightMap[pChild->height] = pChild; if (count == 0) notifyReorg(*pChild); notifyAddBestChain(*pChild); newBestChain.pop(); count++; } pHead = &header; return true; } bool CoinQBlockTreeMem::unsetBestChain(ChainHeader& header) { if (!header.inBestChain) return false; if (header.height == 0) throw std::runtime_error("Cannot remove genesis block from best chain."); ChainHeader* pParent = &mHeaderHashMap.at(header.prevBlockHash()); if (pParent->inBestChain) { mBestHeight = pParent->height; mTotalWork = pParent->chainWork; } header.inBestChain = false; notifyRemoveBestChain(header); pParent = &header; while (pParent->childHashes.size() != 0) { for (auto it = pParent->childHashes.begin(); it != pParent->childHashes.end(); ++it) { ChainHeader* pChild = &mHeaderHashMap.at(*it); if (pChild->inBestChain) { pParent = pChild; mHeaderHeightMap.erase(pChild->height); pChild->inBestChain = false; notifyRemoveBestChain(*pChild); break; } } } return true; } void CoinQBlockTreeMem::setGenesisBlock(const Coin::CoinBlockHeader& header) { if (mHeaderHashMap.size() != 0) throw std::runtime_error("Tree is not empty."); bFlushed = false; uchar_vector hash = header.hash(); ChainHeader& genesisHeader = mHeaderHashMap[hash] = header; mHeaderHeightMap[0] = &genesisHeader; genesisHeader.height = 0; genesisHeader.inBestChain = true; genesisHeader.chainWork = genesisHeader.getWork(); mBestHeight = 0; mTotalWork = genesisHeader.chainWork; pHead = &genesisHeader; notifyInsert(header); notifyAddBestChain(header); } bool CoinQBlockTreeMem::insertHeader(const Coin::CoinBlockHeader& header, bool bCheckProofOfWork) { if (mHeaderHashMap.size() == 0) throw std::runtime_error("No genesis block."); uchar_vector headerHash = header.hash(); if (hasHeader(headerHash)) return false; header_hash_map_t::iterator it = mHeaderHashMap.find(header.prevBlockHash()); if (it == mHeaderHashMap.end()) throw std::runtime_error("Parent not found."); ChainHeader& parent = it->second; // TODO: Check version, compute work required. // Check timestamp /* if (bCheckTimestamp && header.timestamp > time(NULL) + 2 * 60 * 60) { throw std::runtime_error("Timestamp too far in the future."); }*/ // Check proof of work if (bCheckProofOfWork && BigInt(header.getPOWHashLittleEndian()) > header.getTarget()) throw std::runtime_error("Header hash is too big."); ChainHeader& chainHeader = mHeaderHashMap[headerHash] = header; chainHeader.height = parent.height + 1; chainHeader.chainWork = parent.chainWork + chainHeader.getWork(); parent.childHashes.insert(headerHash); notifyInsert(chainHeader); if (chainHeader.chainWork > mTotalWork) { setBestChain(chainHeader); } bFlushed = false; return true; } bool CoinQBlockTreeMem::deleteHeader(const uchar_vector& hash) { header_hash_map_t::iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end()) return false; ChainHeader& header = it->second; unsetBestChain(header); header_hash_map_t::iterator itParent = mHeaderHashMap.find(header.hash()); if (itParent == mHeaderHashMap.end()) throw std::runtime_error("Critical error: parent for block not found."); // Recurse through children for (auto itChild = header.childHashes.begin(); itChild != header.childHashes.end(); ++itChild) { deleteHeader(*itChild); } // TODO: Find new best chain if this header was in best chain. // Remove header ChainHeader& parent = itParent->second; unsigned int nErased = parent.childHashes.erase(hash); assert(nErased == 1); notifyDelete(header); mHeaderHashMap.erase(hash); bFlushed = false; return true; } bool CoinQBlockTreeMem::hasHeader(const uchar_vector& hash) const { return (mHeaderHashMap.find(hash) != mHeaderHashMap.end()); } const ChainHeader& CoinQBlockTreeMem::getHeader(const uchar_vector& hash) const { header_hash_map_t::const_iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end()) throw std::runtime_error("Not found."); return it->second; } const ChainHeader& CoinQBlockTreeMem::getHeader(int height) const { if (mHeaderHeightMap.size() > 0) { if (height < 0) height += mBestHeight + 1; if (height >= 0) { header_height_map_t::const_iterator it = mHeaderHeightMap.find((unsigned int)height); if (it != mHeaderHeightMap.end()) return *it->second; } } throw std::runtime_error("Not found."); } const ChainHeader& CoinQBlockTreeMem::getTip() const { if (!pHead) throw std::runtime_error("Tree is empty."); return *pHead; } int CoinQBlockTreeMem::getTipHeight() const { if (!pHead) throw std::runtime_error("Tree is empty."); return pHead->height; } const ChainHeader& CoinQBlockTreeMem::getHeaderBefore(uint32_t timestamp) const { if (mBestHeight == -1) throw std::runtime_error("Tree is empty."); int i; for (i = 1; i <= mBestHeight; i++) { ChainHeader* header = mHeaderHeightMap.at(i); if (header->timestamp() > timestamp) break; } return *mHeaderHeightMap.at(i - 1); } std::vector<uchar_vector> CoinQBlockTreeMem::getLocatorHashes(int maxSize = -1) const { std::vector<uchar_vector> locatorHashes; if (mBestHeight == -1) { locatorHashes.push_back(g_zero32bytes); return locatorHashes; } if (maxSize < 0) maxSize = mBestHeight + 1; int i = mBestHeight; int n = 0; int step = 1; while ((i >= 0) && (n < maxSize)) { locatorHashes.push_back(mHeaderHeightMap.at(i)->hash()); i -= step; n++; if (n > 10) step *= 2; } return locatorHashes; } int CoinQBlockTreeMem::getConfirmations(const uchar_vector& hash) const { header_hash_map_t::const_iterator it = mHeaderHashMap.find(hash); if (it == mHeaderHashMap.end() || !it->second.inBestChain) return 0; return mBestHeight - it->second.height + 1; } void CoinQBlockTreeMem::loadFromFile(const std::string& filename, bool bCheckProofOfWork, CoinQBlockTreeMem::callback_t callback) { boost::filesystem::path p(filename); if (!boost::filesystem::exists(p)) throw BlockTreeFileNotFoundException(); if (!boost::filesystem::is_regular_file(p)) throw BlockTreeInvalidFileTypeException(); const unsigned int RECORD_SIZE = MIN_COIN_BLOCK_HEADER_SIZE + 4; if (boost::filesystem::file_size(p) % RECORD_SIZE != 0) throw BlockTreeInvalidFileLengthException(); #ifndef _WIN32 std::ifstream fs(p.native(), std::ios::binary); #else std::ifstream fs(filename, std::ios::binary); #endif if (!fs.good()) throw BlockTreeFailedToOpenFileForReadException(); clear(); uchar_vector headerBytes; uchar_vector hash; Coin::CoinBlockHeader header; unsigned int count = 0; char buf[RECORD_SIZE * 64]; while (fs) { fs.read(buf, RECORD_SIZE * 64); if (fs.bad()) throw BlockTreeFileReadFailureException(); unsigned int nbytesread = fs.gcount(); unsigned int pos = 0; for (; pos <= nbytesread - RECORD_SIZE; pos += RECORD_SIZE) { headerBytes.assign((unsigned char*)&buf[pos], (unsigned char*)&buf[pos + MIN_COIN_BLOCK_HEADER_SIZE]); header.setSerialized(headerBytes); hash = header.hash(); if (memcmp(&buf[pos + MIN_COIN_BLOCK_HEADER_SIZE], &hash[0], 4)) throw BlockTreeChecksumErrorException(); try { if (mBestHeight >= 0) { insertHeader(header, bCheckProofOfWork); if (count % 10000 == 0) { if (callback && !callback(*this)) throw BlockTreeLoadInterruptedException(); LOGGER(debug) << "CoinQBlockTreeMem::loadFromFile() - header hash: " << header.hash().getHex() << " height: " << count << std::endl; } count++; } else { setGenesisBlock(header); if (callback && !callback(*this)) throw BlockTreeLoadInterruptedException(); LOGGER(debug) << "CoinQBlockTreeMem::loadFromFile() - genesis hash: " << header.hash().getHex() << std::endl; count++; } } catch (const BlockTreeException& e) { throw e; } catch (const std::exception& e) { throw std::runtime_error(std::string("Block ") + hash.getHex() + ": " + e.what()); } } if (pos != nbytesread) throw BlockTreeUnexpectedEndOfFileException(); } if (callback) callback(*this); // No need to interrupt since we're done. } void CoinQBlockTreeMem::flushToFile(const std::string& filename) { if (mBestHeight == -1) throw std::runtime_error("Tree is empty."); boost::filesystem::path swapfile(filename + ".swp"); //if (boost::filesystem::exists(swapfile)) throw BlockTreeSwapfileAlreadyExistsException(); { #ifndef _WIN32 std::ofstream fs(swapfile.native(), std::ios::binary | std::ios::trunc); #else std::ofstream fs(filename + ".swp", std::ios::binary | std::ios::trunc); #endif uchar_vector headerBytes, hash; for (int i = 0; i <= mBestHeight; i++) { ChainHeader* pHeader = mHeaderHeightMap.at(i); headerBytes = pHeader->getSerialized(); hash = pHeader->hash(); fs.write((const char*)&headerBytes[0], MIN_COIN_BLOCK_HEADER_SIZE); if (fs.bad()) throw BlockTreeFileWriteFailureException(); fs.write((const char*)&hash[0], 4); if (fs.bad()) throw BlockTreeFileWriteFailureException(); } } boost::system::error_code ec; boost::filesystem::path p(filename); boost::filesystem::rename(swapfile, p, ec); if (!!ec) throw std::runtime_error(ec.message()); bFlushed = true; }
Truncate blocktree swapfile if exists.
Truncate blocktree swapfile if exists.
C++
mit
ciphrex/mSIGNA,Faldon/mSIGNA,ciphrex/mSIGNA,ciphrex/mSIGNA,Faldon/mSIGNA
67aca772ef630913f09454c4e068192749f37ebb
src/split/splitBed.cpp
src/split/splitBed.cpp
/***************************************************************************** splitBed.cpp (c) 2015 - Pierre Lindenbaum PhD @yokofakun http://plindenbaum.blogspot.com Univ. Nantes, France Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include <cmath> #include <climits> #include <inttypes.h> #include <getopt.h> #include "lineFileUtilities.h" #include "version.h" #include "splitBed.h" using namespace std; // define our program name #define PROGRAM_NAME "bedtools split" #define SAVE_BEDITEMS(splits) do {\ for(size_t _i = 0; _i < splits.size();++_i) {\ BedSplitItems* bedItems=splits[_i];\ saveBedItems(bedItems,_i);\ delete bedItems;\ } } while(0) #define REPORT_CHUNK(FILENAME,NBASES,COUNT) \ cout << FILENAME << "\t";\ if( NBASES >= LONG_MAX) \ {\ cout << NBASES << "\t";\ }\ else\ {\ cout << (long)(NBASES) << "\t";\ }\ cout << COUNT << endl class BedSplitItems { public: vector<BED*> items; double nbases; BedSplitItems():nbases(0.0) { } ~BedSplitItems() { } void add(BED* entry) { items.push_back(entry); nbases += (double)entry->size(); } vector<BED*>::size_type size() const { return items.size(); } }; BedSplit::BedSplit():outfileprefix("_split"),num_chuncks(0) { } BedSplit::~BedSplit(void) { } int BedSplit::main(int argc,char** argv) { char* algorithm = NULL; for(;;) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"prefix", required_argument, 0, 'p'}, {"input", required_argument, 0, 'i'}, {"bed", required_argument, 0, 'i'}, {"number", required_argument, 0, 'n'}, {"algorithm", required_argument, 0, 'a'}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long (argc, argv, "vhp:i:n:a:", long_options, &option_index ); if (c == -1) break; switch (c) { case 'v': cout << VERSION << endl; return EXIT_SUCCESS; case 'h': usage(cout); return EXIT_SUCCESS; case 'p': outfileprefix.assign(optarg); break; case 'i': bedFileName.assign(optarg); break; case 'a': algorithm = optarg ; break; case 'n': num_chuncks = (unsigned int)atoi(optarg); break; case '?': cerr << "Unknown option -"<< (char)optopt<< ".\n"; return EXIT_FAILURE; default: cerr << "Bad input" << endl; return EXIT_FAILURE; } } if(optind+1==argc && bedFileName.empty()) { bedFileName.assign(argv[optind++]); } else if(optind==argc && bedFileName.empty()) { bedFileName.assign("-"); } if(optind!=argc) { cerr << "Illegal number of arguments.\n" << endl; return EXIT_FAILURE; } if(outfileprefix.empty()) { cerr << "Error: output file prefix is empty.\n" << endl; return EXIT_FAILURE; } if(num_chuncks<=0) { cerr << "Error: num_chunks==0.\n" << endl; usage(cerr); return EXIT_FAILURE; } if(algorithm==NULL || strcmp(algorithm,"size")==0 ) { return doEuristicSplitOnTotalSize(); } else if(strcmp(algorithm,"simple")==0) { return doSimpleSplit(); } else { cerr << "Unknown split algorithm " << algorithm << endl; return EXIT_FAILURE; } } std::FILE* BedSplit::saveFileChunk(std::string& filename,size_t file_index) { char tmp[10]; filename.assign(this->outfileprefix); sprintf(tmp,"%05d",(file_index+1)); filename.append(".").append(tmp).append(".bed"); FILE* out = fopen(filename.c_str(),"w"); if(out==NULL) { fprintf(stderr,"Cannot open \"%s\". %s\n", filename.c_str(), strerror(errno) ); exit(EXIT_FAILURE); } return out; } void BedSplit::saveBedItems(void* data,size_t file_index) { BedSplitItems* bedItems=(BedSplitItems*)data; string filename; FILE* out = saveFileChunk(filename,file_index); BedFile bf; bf.bedType = this->bedType; for(size_t j=0;j< bedItems->items.size();++j) { bf.reportToFileBedNewLine(out,*(bedItems->items[j])); } fflush(out); fclose(out); REPORT_CHUNK(filename, bedItems->nbases,bedItems->items.size()); } /* load whole bed in memory */ void BedSplit::loadBed() { BED bedEntry; BedFile bed(this->bedFileName); bed.Open(); while(bed.GetNextBed(bedEntry)) { if (bed._status != BED_VALID) continue; this->items.push_back(bedEntry); } bed.Close(); this->bedType = bed.bedType; if(this->items.empty()) { cerr << "[WARNING] no BED record found in "<< this->bedFileName << endl; } } class SimpleSplitInfo { public: FILE* out; std::string filename; size_t count; double nbases; SimpleSplitInfo():out(0),count(0),nbases(0) { } }; int BedSplit::doSimpleSplit() { if( this->num_chuncks + 3 < FOPEN_MAX)//3 for security ?, not too much... { size_t i=0,count=0; vector<SimpleSplitInfo*> outputs; BED bedEntry; BedFile bed(this->bedFileName); bed.Open(); while(bed.GetNextBed(bedEntry)) { if (bed._status != BED_VALID) continue; if(count==0) this->bedType = bed.bedType; size_t file_index= count % this->num_chuncks; if(file_index == outputs.size()) { SimpleSplitInfo* newinfo = new SimpleSplitInfo; outputs.push_back(newinfo); newinfo->out = saveFileChunk(newinfo->filename,file_index); } SimpleSplitInfo* info = outputs[file_index]; info->nbases += bedEntry.size(); info->count++; bed.reportToFileBedNewLine(info->out,bedEntry); ++count; } for(i=0;i< outputs.size();++i) { SimpleSplitInfo* info = outputs[i]; fflush(info->out); fclose(info->out); REPORT_CHUNK(info->filename, info->nbases,info->count); delete info; } bed.Close(); } else { vector<BedSplitItems*> splits; loadBed(); for(size_t i = 0; i< this->items.size();++i) { BED* bedEntry = &(this->items[i]); if( splits.size() < this->num_chuncks ) { BedSplitItems* bedItems=new BedSplitItems; splits.push_back(bedItems); bedItems->add(bedEntry); } else { splits[ i % this->num_chuncks]->add(bedEntry); } } SAVE_BEDITEMS(splits); } return 0; } int BedSplit::doEuristicSplitOnTotalSize() { double total_bases = 0.0; vector<BedSplitItems*> splits; loadBed(); //biggest first std::sort(items.begin(),items.end(),sortBySizeDesc); for(size_t item_index = 0; item_index< this->items.size();++item_index) { BED* bedEntry = &(this->items[item_index]); if( splits.size() < num_chuncks ) { BedSplitItems* bedItems=new BedSplitItems; splits.push_back(bedItems); bedItems->add(bedEntry); total_bases += bedEntry->size(); } else if( num_chuncks == 1 ) { splits.front()->add(bedEntry); total_bases += bedEntry->size(); } else /* what is the best place to insert this record ?*/ { size_t index_insert = 0UL; vector<double> stdevs; double lowest_stddev=-1; /* expected mean number of bases in each bedItems */ double mean = (total_bases + bedEntry->size() )/ (double)num_chuncks; /** try to insert the bedEntry in any of the split */ for(size_t try_index_insert = 0; try_index_insert < splits.size(); ++try_index_insert ) { /* get the stddev of the split */ double stddev=0.0; for(size_t i=0;i< splits.size() ; ++i) { double split_size = splits[i]->nbases + ( i==try_index_insert ? bedEntry->size() : 0 ); stddev += fabs( split_size - mean); } /* this position in BED index is better = stddev of size lowest */ if( try_index_insert == 0 || lowest_stddev> stddev ) { lowest_stddev = stddev ; index_insert = try_index_insert; } } splits[index_insert]->add(bedEntry); total_bases += bedEntry->size(); } } SAVE_BEDITEMS(splits); return 0; } void BedSplit::usage(std::ostream& out) { out << "\nTool: bedtools split" << endl; out << "Version: " << VERSION << "\n"; out << "Summary: Split a Bed file." << endl << endl; out << "Usage: " << PROGRAM_NAME << " [OPTIONS] -i <bed> -n number-of-files" << endl << endl; out << "Options: " << endl; out << "\t-i|--input (file)\tBED input file (req'd)." << endl; out << "\t-n|--number (int)\tNumber of files to create (req'd)." << endl; out << "\t-p|--prefix (string)\tOutput BED file prefix." << endl; out << "\t-a|--algorithm (string) Algorithm used to split data." << endl; out << "\t\t* size (default): uses a heuristic algorithm to group the items" << endl; out << "\t\t so all files contain the ~ same number of bases" << endl; out << "\t\t* simple : route records such that each split file has" << endl; out << "\t\t approximately equal records (like Unix split)." << endl << endl; out << "\t-h|--help\t\tPrint help (this screen)." << endl; out << "\t-v|--version\t\tPrint version." << endl; out << "\n\nNote: This programs stores the input BED records in memory." << endl; out << endl; }
/***************************************************************************** splitBed.cpp (c) 2015 - Pierre Lindenbaum PhD @yokofakun http://plindenbaum.blogspot.com Univ. Nantes, France Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include <cmath> #include <climits> #include <sstream> #include <iomanip> #include <inttypes.h> #include <getopt.h> #include "lineFileUtilities.h" #include "version.h" #include "splitBed.h" using namespace std; // define our program name #define PROGRAM_NAME "bedtools split" #define SAVE_BEDITEMS(splits) do {\ for(size_t _i = 0; _i < splits.size();++_i) {\ BedSplitItems* bedItems=splits[_i];\ saveBedItems(bedItems,_i);\ delete bedItems;\ } } while(0) #define REPORT_CHUNK(FILENAME,NBASES,COUNT) \ cout << FILENAME << "\t";\ if( NBASES >= LONG_MAX) \ {\ cout << NBASES << "\t";\ }\ else\ {\ cout << (long)(NBASES) << "\t";\ }\ cout << COUNT << endl class BedSplitItems { public: vector<BED*> items; double nbases; BedSplitItems():nbases(0.0) { } ~BedSplitItems() { } void add(BED* entry) { items.push_back(entry); nbases += (double)entry->size(); } vector<BED*>::size_type size() const { return items.size(); } }; BedSplit::BedSplit():outfileprefix("_split"),num_chuncks(0) { } BedSplit::~BedSplit(void) { } int BedSplit::main(int argc,char** argv) { char* algorithm = NULL; for(;;) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"prefix", required_argument, 0, 'p'}, {"input", required_argument, 0, 'i'}, {"bed", required_argument, 0, 'i'}, {"number", required_argument, 0, 'n'}, {"algorithm", required_argument, 0, 'a'}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long (argc, argv, "vhp:i:n:a:", long_options, &option_index ); if (c == -1) break; switch (c) { case 'v': cout << VERSION << endl; return EXIT_SUCCESS; case 'h': usage(cout); return EXIT_SUCCESS; case 'p': outfileprefix.assign(optarg); break; case 'i': bedFileName.assign(optarg); break; case 'a': algorithm = optarg ; break; case 'n': num_chuncks = (unsigned int)atoi(optarg); break; case '?': cerr << "Unknown option -"<< (char)optopt<< ".\n"; return EXIT_FAILURE; default: cerr << "Bad input" << endl; return EXIT_FAILURE; } } if(optind+1==argc && bedFileName.empty()) { bedFileName.assign(argv[optind++]); } else if(optind==argc && bedFileName.empty()) { bedFileName.assign("-"); } if(optind!=argc) { cerr << "Illegal number of arguments.\n" << endl; return EXIT_FAILURE; } if(outfileprefix.empty()) { cerr << "Error: output file prefix is empty.\n" << endl; return EXIT_FAILURE; } if(num_chuncks<=0) { cerr << "Error: num_chunks==0.\n" << endl; usage(cerr); return EXIT_FAILURE; } if(algorithm==NULL || strcmp(algorithm,"size")==0 ) { return doEuristicSplitOnTotalSize(); } else if(strcmp(algorithm,"simple")==0) { return doSimpleSplit(); } else { cerr << "Unknown split algorithm " << algorithm << endl; return EXIT_FAILURE; } } std::FILE* BedSplit::saveFileChunk(std::string& filename,size_t file_index) { ostringstream name; name << this->outfileprefix << '.' << setfill('0') << setw(5) << file_index+1 << ".bed"; filename = name.str(); FILE* out = fopen(filename.c_str(),"w"); if(out==NULL) { fprintf(stderr,"Cannot open \"%s\". %s\n", filename.c_str(), strerror(errno) ); exit(EXIT_FAILURE); } return out; } void BedSplit::saveBedItems(void* data,size_t file_index) { BedSplitItems* bedItems=(BedSplitItems*)data; string filename; FILE* out = saveFileChunk(filename,file_index); BedFile bf; bf.bedType = this->bedType; for(size_t j=0;j< bedItems->items.size();++j) { bf.reportToFileBedNewLine(out,*(bedItems->items[j])); } fflush(out); fclose(out); REPORT_CHUNK(filename, bedItems->nbases,bedItems->items.size()); } /* load whole bed in memory */ void BedSplit::loadBed() { BED bedEntry; BedFile bed(this->bedFileName); bed.Open(); while(bed.GetNextBed(bedEntry)) { if (bed._status != BED_VALID) continue; this->items.push_back(bedEntry); } bed.Close(); this->bedType = bed.bedType; if(this->items.empty()) { cerr << "[WARNING] no BED record found in "<< this->bedFileName << endl; } } class SimpleSplitInfo { public: FILE* out; std::string filename; size_t count; double nbases; SimpleSplitInfo():out(0),count(0),nbases(0) { } }; int BedSplit::doSimpleSplit() { if( this->num_chuncks + 3 < FOPEN_MAX)//3 for security ?, not too much... { size_t i=0,count=0; vector<SimpleSplitInfo*> outputs; BED bedEntry; BedFile bed(this->bedFileName); bed.Open(); while(bed.GetNextBed(bedEntry)) { if (bed._status != BED_VALID) continue; if(count==0) this->bedType = bed.bedType; size_t file_index= count % this->num_chuncks; if(file_index == outputs.size()) { SimpleSplitInfo* newinfo = new SimpleSplitInfo; outputs.push_back(newinfo); newinfo->out = saveFileChunk(newinfo->filename,file_index); } SimpleSplitInfo* info = outputs[file_index]; info->nbases += bedEntry.size(); info->count++; bed.reportToFileBedNewLine(info->out,bedEntry); ++count; } for(i=0;i< outputs.size();++i) { SimpleSplitInfo* info = outputs[i]; fflush(info->out); fclose(info->out); REPORT_CHUNK(info->filename, info->nbases,info->count); delete info; } bed.Close(); } else { vector<BedSplitItems*> splits; loadBed(); for(size_t i = 0; i< this->items.size();++i) { BED* bedEntry = &(this->items[i]); if( splits.size() < this->num_chuncks ) { BedSplitItems* bedItems=new BedSplitItems; splits.push_back(bedItems); bedItems->add(bedEntry); } else { splits[ i % this->num_chuncks]->add(bedEntry); } } SAVE_BEDITEMS(splits); } return 0; } int BedSplit::doEuristicSplitOnTotalSize() { double total_bases = 0.0; vector<BedSplitItems*> splits; loadBed(); //biggest first std::sort(items.begin(),items.end(),sortBySizeDesc); for(size_t item_index = 0; item_index< this->items.size();++item_index) { BED* bedEntry = &(this->items[item_index]); if( splits.size() < num_chuncks ) { BedSplitItems* bedItems=new BedSplitItems; splits.push_back(bedItems); bedItems->add(bedEntry); total_bases += bedEntry->size(); } else if( num_chuncks == 1 ) { splits.front()->add(bedEntry); total_bases += bedEntry->size(); } else /* what is the best place to insert this record ?*/ { size_t index_insert = 0UL; vector<double> stdevs; double lowest_stddev=-1; /* expected mean number of bases in each bedItems */ double mean = (total_bases + bedEntry->size() )/ (double)num_chuncks; /** try to insert the bedEntry in any of the split */ for(size_t try_index_insert = 0; try_index_insert < splits.size(); ++try_index_insert ) { /* get the stddev of the split */ double stddev=0.0; for(size_t i=0;i< splits.size() ; ++i) { double split_size = splits[i]->nbases + ( i==try_index_insert ? bedEntry->size() : 0 ); stddev += fabs( split_size - mean); } /* this position in BED index is better = stddev of size lowest */ if( try_index_insert == 0 || lowest_stddev> stddev ) { lowest_stddev = stddev ; index_insert = try_index_insert; } } splits[index_insert]->add(bedEntry); total_bases += bedEntry->size(); } } SAVE_BEDITEMS(splits); return 0; } void BedSplit::usage(std::ostream& out) { out << "\nTool: bedtools split" << endl; out << "Version: " << VERSION << "\n"; out << "Summary: Split a Bed file." << endl << endl; out << "Usage: " << PROGRAM_NAME << " [OPTIONS] -i <bed> -n number-of-files" << endl << endl; out << "Options: " << endl; out << "\t-i|--input (file)\tBED input file (req'd)." << endl; out << "\t-n|--number (int)\tNumber of files to create (req'd)." << endl; out << "\t-p|--prefix (string)\tOutput BED file prefix." << endl; out << "\t-a|--algorithm (string) Algorithm used to split data." << endl; out << "\t\t* size (default): uses a heuristic algorithm to group the items" << endl; out << "\t\t so all files contain the ~ same number of bases" << endl; out << "\t\t* simple : route records such that each split file has" << endl; out << "\t\t approximately equal records (like Unix split)." << endl << endl; out << "\t-h|--help\t\tPrint help (this screen)." << endl; out << "\t-v|--version\t\tPrint version." << endl; out << "\n\nNote: This programs stores the input BED records in memory." << endl; out << endl; }
Use ostringstream to format filename
Use ostringstream to format filename Using C++'s native facility here avoids a warning from the sprintf() in the previous code.
C++
mit
arq5x/bedtools2,jmarshall/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,arq5x/bedtools2
8f719512ba7c6529368c62135d5bd6ab7a0e3aff
src/syscoin-wallet.cpp
src/syscoin-wallet.cpp
// Copyright (c) 2016-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <chainparamsbase.h> #include <logging.h> #include <util/system.h> #include <util/translation.h> #include <wallet/wallettool.h> #include <functional> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupWalletToolArgs() { SetupHelpOptions(gArgs); SetupChainParamsBaseOptions(); gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS); gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); } static bool WalletAppInit(int argc, char* argv[]) { SetupWalletToolArgs(); std::string error_message; if (!gArgs.ParseParameters(argc, argv, error_message)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message); return false; } if (argc < 2 || HelpRequested(gArgs)) { std::string usage = strprintf("%s syscoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" + "syscoin-wallet is an offline tool for creating and interacting with Syscoin Core wallet files.\n" + "By default syscoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" + "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" + "Usage:\n" + " syscoin-wallet [options] <command>\n\n" + gArgs.GetHelpMessage(); tfm::format(std::cout, "%s", usage); return false; } // check for printtoconsole, allow -debug LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false)); if (!CheckDataDirOption()) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) SelectParams(gArgs.GetChainName()); return true; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); RandomInit(); try { if (!WalletAppInit(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "WalletAppInit()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "WalletAppInit()"); return EXIT_FAILURE; } std::string method {}; for(int i = 1; i < argc; ++i) { if (!IsSwitchChar(argv[i][0])) { if (!method.empty()) { tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]); return EXIT_FAILURE; } method = argv[i]; } } if (method.empty()) { tfm::format(std::cerr, "No method provided. Run `syscoin-wallet -help` for valid methods.\n"); return EXIT_FAILURE; } // A name must be provided when creating a file if (method == "create" && !gArgs.IsArgSet("-wallet")) { tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n"); return EXIT_FAILURE; } std::string name = gArgs.GetArg("-wallet", ""); ECCVerifyHandle globalVerifyHandle; ECC_Start(); if (!WalletTool::ExecuteWalletToolFunc(method, name)) return EXIT_FAILURE; ECC_Stop(); return EXIT_SUCCESS; }
// Copyright (c) 2016-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <chainparamsbase.h> #include <logging.h> #include <util/system.h> #include <util/translation.h> #include <wallet/wallettool.h> #include <functional> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupWalletToolArgs() { SetupHelpOptions(gArgs); SetupChainParamsBaseOptions(); gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS); gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); } static bool WalletAppInit(int argc, char* argv[]) { SetupWalletToolArgs(); std::string error_message; if (!gArgs.ParseParameters(argc, argv, error_message)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message); return false; } if (argc < 2 || HelpRequested(gArgs)) { std::string usage = strprintf("%s syscoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" + "syscoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n" + "By default syscoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" + "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" + "Usage:\n" + " syscoin-wallet [options] <command>\n\n" + gArgs.GetHelpMessage(); tfm::format(std::cout, "%s", usage); return false; } // check for printtoconsole, allow -debug LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false)); if (!CheckDataDirOption()) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) SelectParams(gArgs.GetChainName()); return true; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); RandomInit(); try { if (!WalletAppInit(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "WalletAppInit()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "WalletAppInit()"); return EXIT_FAILURE; } std::string method {}; for(int i = 1; i < argc; ++i) { if (!IsSwitchChar(argv[i][0])) { if (!method.empty()) { tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]); return EXIT_FAILURE; } method = argv[i]; } } if (method.empty()) { tfm::format(std::cerr, "No method provided. Run `syscoin-wallet -help` for valid methods.\n"); return EXIT_FAILURE; } // A name must be provided when creating a file if (method == "create" && !gArgs.IsArgSet("-wallet")) { tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n"); return EXIT_FAILURE; } std::string name = gArgs.GetArg("-wallet", ""); ECCVerifyHandle globalVerifyHandle; ECC_Start(); if (!WalletTool::ExecuteWalletToolFunc(method, name)) return EXIT_FAILURE; ECC_Stop(); return EXIT_SUCCESS; }
Use PACKAGE_NAME in usage help
bitcoin-wallet: Use PACKAGE_NAME in usage help Former-commit-id: 2e23d0c700cc3cca587e00eab12ae5d64cbd7c1c
C++
mit
syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin2
ac11672067b543ce415748e64ee079a72849be3e
opencog/reasoning/pln/rules/simsubst/SimSubstRule1.cc
opencog/reasoning/pln/rules/simsubst/SimSubstRule1.cc
/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/platform.h> #include "../../PLN.h" #include "../Rule.h" #include "../Rules.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" // Issue: Makes a real link with children in a vtree. --JaredW // Issue: i2oType is ambiguous? --JaredW namespace opencog { namespace pln { Rule::setOfMPs SimSubstRule1::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { /** For simplicity (but sacrificing applicability), FW_VARs cannot be replaced with children structs. Links are assumed not inheritable either. */ if (outh->begin().number_of_children() != 2 || GET_ASW->inheritsType(GET_ASW->getType(boost::get<pHandle>(*outh->begin())), FW_VARIABLE_NODE)) return Rule::setOfMPs(); /* puts("X1"); rawPrint(*outh,0,0); puts("X2");*/ Rule::setOfMPs ret; // set<atom> child_nodes; // find_child_nodes(outh, child_nodes); Vertex child = CreateVar(asw); // Should it use different variables for each MPs (MP vector)? -- JaredW // Makes weird stuff like inheriting from EvaluationLink (with no args) -- JaredW // Seems to allow replacing _any_ part of the vtree. Must check that it actually produces // the result you need! // The input _should_ be: an inheritance from any part of the output atom, // and a version of the output atom that has that atom in it. for(tree<Vertex>::pre_order_iterator i = outh->begin(); i != outh->end(); i++) // for (set<atom>::iterator i = child_nodes.begin(); i != child_nodes.end(); i++) { /* puts("-"); printAtomTree(outh,0,0); */ Vertex old_i = *i; *i = child; BBvtree templated_atom1(new BoundVTree(*outh)); *i = old_i; BBvtree inhPattern1(new BoundVTree(mva((pHandle)INHERITANCE_LINK, mva(child), mva(*i)))); MPs ret1; ret1.push_back(inhPattern1); ret1.push_back(templated_atom1); /* puts("X"); rawPrint(*outh,0,0); puts("-"); rawPrint(*templated_atom1,0,0); puts("-"); rawPrint(*inhPattern1,0,0); puts("-");*/ overrideInputFilter = true; ret.insert(ret1); } return ret; } /// Should really use vtree. Make/find a substitute method for vtree. meta SimSubstRule1::i2oType(const vector<Vertex>& h) const { pHandle h0 = boost::get<pHandle>(h[0]); pHandle h1 = boost::get<pHandle>(h[1]); const int N = h.size(); assert(2==N); assert(asw->getType(h0) == INHERITANCE_LINK); // ( any, Inh(a,b) ) atom ret(h1); //assert(ret.hs[1].real == nm->getOutgoing(h[1])[0]); vector<pHandle> hs = nm->getOutgoing(h0); /// subst hs[0] to hs[1] (child => parent): //ret.hs[0]->substitute(atom(hs[1]), atom(hs[0])); ret.substitute(atom(hs[1]), atom(hs[0])); //printAtomTree(ret,0,0); /* meta ret(new Tree<Vertex>(mva(nm->getType(boost::get<pHandle>(h[0])), mva(nm->getOutgoing(boost::get<pHandle>(h[1]))[0]), mva(nm->getOutgoing(boost::get<pHandle>(h[0]))[1])));*/ return BBvtree(new BoundVTree(ret.makeHandletree(asw))); // this is the line that crashes the BIT. It should be making a normal vtree out of it (or just using a normal vtree) } }} // namespace opencog { namespace pln {
/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/platform.h> #include "../../PLN.h" #include "../Rule.h" #include "../Rules.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" #include <algorithm> // Issue: Makes a real link with children in a vtree. -- JaredW // Issue: i2oType is ambiguous? --JaredW namespace opencog { namespace pln { Rule::setOfMPs SimSubstRule1::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { /** For simplicity (but sacrificing applicability), FW_VARs cannot be replaced with children structs. Links are assumed not inheritable either. */ // I'm not sure if any of that is true -- JaredW if (outh->begin().number_of_children() != 2 || GET_ASW->inheritsType(GET_ASW->getType(boost::get<pHandle>(*outh->begin())), FW_VARIABLE_NODE)) return Rule::setOfMPs(); /* puts("X1"); rawPrint(*outh,0,0); puts("X2");*/ Rule::setOfMPs ret; // set<atom> child_nodes; // find_child_nodes(outh, child_nodes); Vertex child = CreateVar(asw); // Should it use different variables for each MPs (MP vector)? -- JaredW // Makes weird stuff like inheriting from EvaluationLink (with no args) -- JaredW // Seems to allow replacing _any_ part of the vtree. Must check that it actually produces // the result you need! // The input is: an inheritance from any part of the output atom, // and a version of the output atom that has that atom in it. for(tree<Vertex>::pre_order_iterator i = outh->begin(); i != outh->end(); i++) // for (set<atom>::iterator i = child_nodes.begin(); i != child_nodes.end(); i++) { /* puts("-"); printAtomTree(outh,0,0); */ Vertex old_i = *i; *i = child; BBvtree templated_atom1(new BoundVTree(*outh)); *i = old_i; BBvtree inhPattern1(new BoundVTree(mva((pHandle)INHERITANCE_LINK, mva(child), mva(*i)))); MPs ret1; ret1.push_back(inhPattern1); ret1.push_back(templated_atom1); /* puts("X"); rawPrint(*outh,0,0); puts("-"); rawPrint(*templated_atom1,0,0); puts("-"); rawPrint(*inhPattern1,0,0); puts("-");*/ overrideInputFilter = true; ret.insert(ret1); } return ret; } /// fixme This presumably puts a real link with children into a vtree, which is wrong. /// The problem may even be in the BIT itself. meta SimSubstRule1::i2oType(const vector<Vertex>& h) const { pHandle h0 = boost::get<pHandle>(h[0]); pHandle h1 = boost::get<pHandle>(h[1]); const int N = h.size(); assert(2==N); assert(asw->getType(h0) == INHERITANCE_LINK); // ( any, Inh(a,b) ) // Make a vtree out of h1 meta h1_mp = meta(new vtree(h[1])); NMPrinter printer(NMP_HANDLE|NMP_TYPE_NAME, NM_PRINTER_DEFAULT_TRUTH_VALUE_PRECISION, NM_PRINTER_DEFAULT_INDENTATION_TAB_SIZE, 3); printer.print(h1_mp->begin()); // Make it virtual (to get the structure of the link, not just the handle) meta ret = ForceAllLinksVirtual(h1_mp); printer.print(ret->begin()); vector<pHandle> hs = nm->getOutgoing(h0); // the InhLink (h[0]) is real when this method is called // @todo if the child is a link, it will be real. This is OK. /// @todo What if child has a different structure to parent? std::replace(ret->begin(), ret->end(), Vertex(hs[0]), Vertex(hs[1])); printer.print(ret->begin()); return ret; #if 0 atom ret(h1); //assert(ret.hs[1].real == nm->getOutgoing(h[1])[0]); vector<pHandle> hs = nm->getOutgoing(h0); /// subst hs[0] to hs[1] (child => parent): //ret.hs[0]->substitute(atom(hs[1]), atom(hs[0])); ret.substitute(atom(hs[1]), atom(hs[0])); //printAtomTree(ret,0,0); /* meta ret(new Tree<Vertex>(mva(nm->getType(boost::get<pHandle>(h[0])), mva(nm->getOutgoing(boost::get<pHandle>(h[1]))[0]), mva(nm->getOutgoing(boost::get<pHandle>(h[0]))[1])));*/ return BBvtree(new BoundVTree(ret.makeHandletree(asw))); // this is the line that crashes the BIT. It should be making a normal vtree out of it (or just using a normal vtree) #endif } }} // namespace opencog { namespace pln {
Convert SimSubstRule1 to use vtree instead of the obsolete PLN atom class. It now works properly with applyRule (pln-ar) but still crashes the BIT.
Convert SimSubstRule1 to use vtree instead of the obsolete PLN atom class. It now works properly with applyRule (pln-ar) but still crashes the BIT.
C++
agpl-3.0
TheNameIsNigel/opencog,shujingke/opencog,Tiggels/opencog,williampma/atomspace,ceefour/opencog,cosmoharrigan/atomspace,Tiggels/opencog,sumitsourabh/opencog,eddiemonroe/atomspace,cosmoharrigan/atomspace,misgeatgit/atomspace,gaapt/opencog,rodsol/opencog,printedheart/opencog,ceefour/opencog,UIKit0/atomspace,shujingke/opencog,inflector/opencog,ceefour/atomspace,virneo/opencog,printedheart/opencog,rohit12/opencog,rohit12/opencog,inflector/atomspace,gavrieltal/opencog,sumitsourabh/opencog,cosmoharrigan/atomspace,anitzkin/opencog,ArvinPan/opencog,eddiemonroe/atomspace,misgeatgit/atomspace,andre-senna/opencog,TheNameIsNigel/opencog,prateeksaxena2809/opencog,kim135797531/opencog,Allend575/opencog,misgeatgit/atomspace,ruiting/opencog,ceefour/opencog,rodsol/opencog,UIKit0/atomspace,Tiggels/opencog,misgeatgit/opencog,TheNameIsNigel/opencog,iAMr00t/opencog,misgeatgit/opencog,ArvinPan/opencog,rohit12/atomspace,inflector/opencog,andre-senna/opencog,inflector/atomspace,Selameab/atomspace,yantrabuddhi/atomspace,ArvinPan/opencog,cosmoharrigan/opencog,eddiemonroe/opencog,jlegendary/opencog,ceefour/opencog,yantrabuddhi/atomspace,roselleebarle04/opencog,ruiting/opencog,printedheart/opencog,kinoc/opencog,virneo/atomspace,yantrabuddhi/opencog,AmeBel/opencog,inflector/atomspace,cosmoharrigan/opencog,ceefour/opencog,iAMr00t/opencog,roselleebarle04/opencog,Selameab/atomspace,anitzkin/opencog,rohit12/atomspace,jlegendary/opencog,printedheart/opencog,gaapt/opencog,yantrabuddhi/atomspace,jswiergo/atomspace,rTreutlein/atomspace,rodsol/atomspace,misgeatgit/opencog,jlegendary/opencog,cosmoharrigan/opencog,gaapt/opencog,yantrabuddhi/opencog,rodsol/opencog,shujingke/opencog,roselleebarle04/opencog,misgeatgit/opencog,Selameab/opencog,ruiting/opencog,eddiemonroe/opencog,anitzkin/opencog,jlegendary/opencog,kinoc/opencog,virneo/opencog,roselleebarle04/opencog,eddiemonroe/opencog,rTreutlein/atomspace,zhaozengguang/opencog,rohit12/opencog,virneo/opencog,inflector/opencog,MarcosPividori/atomspace,TheNameIsNigel/opencog,virneo/atomspace,sumitsourabh/opencog,andre-senna/opencog,inflector/opencog,kim135797531/opencog,misgeatgit/opencog,AmeBel/atomspace,printedheart/atomspace,virneo/opencog,Allend575/opencog,kim135797531/opencog,AmeBel/opencog,williampma/opencog,zhaozengguang/opencog,rohit12/opencog,Selameab/opencog,yantrabuddhi/opencog,andre-senna/opencog,UIKit0/atomspace,Allend575/opencog,gaapt/opencog,gavrieltal/opencog,sumitsourabh/opencog,iAMr00t/opencog,rTreutlein/atomspace,jswiergo/atomspace,AmeBel/opencog,TheNameIsNigel/opencog,williampma/opencog,UIKit0/atomspace,AmeBel/atomspace,sanuj/opencog,anitzkin/opencog,printedheart/opencog,williampma/opencog,andre-senna/opencog,Selameab/opencog,AmeBel/atomspace,iAMr00t/opencog,roselleebarle04/opencog,AmeBel/opencog,andre-senna/opencog,eddiemonroe/opencog,prateeksaxena2809/opencog,eddiemonroe/atomspace,kim135797531/opencog,inflector/opencog,williampma/atomspace,MarcosPividori/atomspace,sanuj/opencog,rodsol/opencog,ceefour/opencog,jswiergo/atomspace,eddiemonroe/atomspace,yantrabuddhi/opencog,cosmoharrigan/opencog,virneo/opencog,gavrieltal/opencog,Selameab/opencog,kinoc/opencog,misgeatgit/opencog,prateeksaxena2809/opencog,Selameab/opencog,Allend575/opencog,misgeatgit/opencog,sanuj/opencog,rohit12/atomspace,kim135797531/opencog,AmeBel/opencog,prateeksaxena2809/opencog,Allend575/opencog,rodsol/atomspace,rodsol/opencog,AmeBel/atomspace,cosmoharrigan/opencog,ruiting/opencog,williampma/atomspace,eddiemonroe/opencog,ceefour/opencog,rTreutlein/atomspace,anitzkin/opencog,misgeatgit/atomspace,gavrieltal/opencog,sanuj/opencog,jswiergo/atomspace,ArvinPan/opencog,misgeatgit/atomspace,ArvinPan/atomspace,rohit12/opencog,jlegendary/opencog,shujingke/opencog,williampma/opencog,sanuj/opencog,rohit12/opencog,virneo/opencog,Allend575/opencog,ArvinPan/atomspace,gavrieltal/opencog,virneo/atomspace,anitzkin/opencog,shujingke/opencog,sumitsourabh/opencog,virneo/atomspace,gavrieltal/opencog,rTreutlein/atomspace,iAMr00t/opencog,Tiggels/opencog,williampma/opencog,cosmoharrigan/atomspace,williampma/atomspace,gaapt/opencog,kinoc/opencog,AmeBel/opencog,eddiemonroe/atomspace,tim777z/opencog,printedheart/atomspace,ceefour/atomspace,ruiting/opencog,eddiemonroe/opencog,roselleebarle04/opencog,misgeatgit/opencog,Tiggels/opencog,Selameab/atomspace,kinoc/opencog,inflector/atomspace,jlegendary/opencog,ceefour/atomspace,tim777z/opencog,kinoc/opencog,tim777z/opencog,Allend575/opencog,yantrabuddhi/opencog,virneo/opencog,zhaozengguang/opencog,Selameab/opencog,Selameab/atomspace,printedheart/atomspace,sumitsourabh/opencog,rodsol/atomspace,inflector/opencog,MarcosPividori/atomspace,ArvinPan/opencog,printedheart/opencog,sanuj/opencog,zhaozengguang/opencog,cosmoharrigan/opencog,AmeBel/atomspace,inflector/atomspace,tim777z/opencog,yantrabuddhi/opencog,kim135797531/opencog,prateeksaxena2809/opencog,eddiemonroe/opencog,andre-senna/opencog,shujingke/opencog,TheNameIsNigel/opencog,kinoc/opencog,tim777z/opencog,tim777z/opencog,prateeksaxena2809/opencog,prateeksaxena2809/opencog,misgeatgit/opencog,anitzkin/opencog,ruiting/opencog,inflector/opencog,ruiting/opencog,gaapt/opencog,rodsol/opencog,ArvinPan/atomspace,gaapt/opencog,zhaozengguang/opencog,printedheart/atomspace,roselleebarle04/opencog,yantrabuddhi/atomspace,rohit12/atomspace,shujingke/opencog,kim135797531/opencog,ArvinPan/opencog,rodsol/atomspace,iAMr00t/opencog,yantrabuddhi/opencog,MarcosPividori/atomspace,gavrieltal/opencog,inflector/opencog,ceefour/atomspace,zhaozengguang/opencog,Tiggels/opencog,ArvinPan/atomspace,jlegendary/opencog,yantrabuddhi/atomspace,sumitsourabh/opencog,williampma/opencog,AmeBel/opencog
b519be027882c09d5f94b3ef7baecae1d1de3812
src/SimplifySpecializations.cpp
src/SimplifySpecializations.cpp
#include "SimplifySpecializations.h" #include "IROperator.h" #include "IRMutator.h" #include "Simplify.h" #include "Substitute.h" #include "Definition.h" #include "IREquality.h" #include <set> namespace Halide{ namespace Internal { using std::map; using std::set; using std::string; using std::vector; namespace { void substitute_value_in_var(const string &var, Expr value, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(substitute(var, value, def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(substitute(var, value, def_val)); } } } class SimplifyUsingFact : public IRMutator { public: using IRMutator::mutate; Expr mutate(Expr e) { if (e.type().is_bool()) { if (equal(fact, e) || can_prove(!fact || e)) { // fact implies e return const_true(); } if (equal(fact, !e) || equal(!fact, e) || can_prove(!fact || !e)) { // fact implies !e return const_false(); } } return IRMutator::mutate(e); } Expr fact; SimplifyUsingFact(Expr f) : fact(f) {} }; void simplify_using_fact(Expr fact, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(SimplifyUsingFact(fact).mutate(def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(SimplifyUsingFact(fact).mutate(def_val)); } } } bool equal(const std::vector<Expr> &a, const std::vector<Expr> &b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); ++i) { if (!equal(a[i], b[i])) return false; } return true; } vector<Definition> propagate_specialization_in_definition(Definition &def, const string &name) { vector<Definition> result; result.push_back(def); vector<Specialization> &specializations = def.specializations(); // Prune specializations based on constants: // -- Any Specializations that have const-false as a condition // can never trigger; go ahead and prune them now to save time & energy // during later phases. // -- Once we encounter a Specialization that is const-true, no subsequent // Specializations can ever trigger (since we evaluate them in order), // so erase them. bool seen_const_true = false; for (auto it = specializations.begin(); it != specializations.end(); /*no-increment*/) { Expr old_c = it->condition; Expr c = simplify(it->condition); // Go ahead and save the simplified condition now it->condition = c; if (is_zero(c) || seen_const_true) { debug(1) << "Erasing unreachable specialization (" << old_c << ") -> (" << c << ") for function \"" << name << "\"\n"; it = specializations.erase(it); } else { it++; } seen_const_true |= is_one(c); } // If the final Specialization is const-true, then the default schedule // for the definition will never be run: replace the definition's main // schedule with the one from the final Specialization and prune it from // the list. This may leave the list of Specializations empty. if (!specializations.empty() && is_one(specializations.back().condition)) { debug(1) << "Replacing default Schedule with const-true specialization for function \"" << name << "\"\n"; const Definition s_def = specializations.back().definition; specializations.pop_back(); def.predicate() = s_def.predicate(); // values and args should be identical -- if not, something is badly wrong. internal_assert(equal(def.values(), s_def.values())); internal_assert(equal(def.args(), s_def.args())); def.schedule() = s_def.schedule(); // Append our sub-specializations to the Definition's list specializations.insert(specializations.end(), s_def.specializations().begin(), s_def.specializations().end()); } for (size_t i = specializations.size(); i > 0; i--) { Expr c = specializations[i-1].condition; Definition &s_def = specializations[i-1].definition; const EQ *eq = c.as<EQ>(); const Variable *var = eq ? eq->a.as<Variable>() : c.as<Variable>(); vector<Definition> s_result = propagate_specialization_in_definition(s_def, name); if (var && eq) { // Then case substitute_value_in_var(var->name, eq->b, s_result); // Else case if (eq->b.type().is_bool()) { substitute_value_in_var(var->name, !eq->b, result); } } else if (var) { // Then case substitute_value_in_var(var->name, const_true(), s_result); // Else case substitute_value_in_var(var->name, const_false(), result); } else { simplify_using_fact(c, s_result); simplify_using_fact(!c, result); } result.insert(result.end(), s_result.begin(), s_result.end()); } return result; } } void simplify_specializations(map<string, Function> &env) { for (auto &iter : env) { Function &func = iter.second; propagate_specialization_in_definition(func.definition(), func.name()); } } } }
#include "SimplifySpecializations.h" #include "IROperator.h" #include "IRMutator.h" #include "Simplify.h" #include "Substitute.h" #include "Definition.h" #include "IREquality.h" #include <set> namespace Halide{ namespace Internal { using std::map; using std::set; using std::string; using std::vector; namespace { void substitute_value_in_var(const string &var, Expr value, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(substitute(var, value, def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(substitute(var, value, def_val)); } } } class SimplifyUsingFact : public IRMutator { public: using IRMutator::mutate; Expr mutate(Expr e) { if (e.type().is_bool()) { if (equal(fact, e) || can_prove(!fact || e)) { // fact implies e return const_true(); } if (equal(fact, !e) || equal(!fact, e) || can_prove(!fact || !e)) { // fact implies !e return const_false(); } } return IRMutator::mutate(e); } Expr fact; SimplifyUsingFact(Expr f) : fact(f) {} }; void simplify_using_fact(Expr fact, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(SimplifyUsingFact(fact).mutate(def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(SimplifyUsingFact(fact).mutate(def_val)); } } } vector<Definition> propagate_specialization_in_definition(Definition &def, const string &name) { vector<Definition> result; result.push_back(def); vector<Specialization> &specializations = def.specializations(); // Prune specializations based on constants: // -- Any Specializations that have const-false as a condition // can never trigger; go ahead and prune them now to save time & energy // during later phases. // -- Once we encounter a Specialization that is const-true, no subsequent // Specializations can ever trigger (since we evaluate them in order), // so erase them. bool seen_const_true = false; for (auto it = specializations.begin(); it != specializations.end(); /*no-increment*/) { Expr old_c = it->condition; Expr c = simplify(it->condition); // Go ahead and save the simplified condition now it->condition = c; if (is_zero(c) || seen_const_true) { debug(1) << "Erasing unreachable specialization (" << old_c << ") -> (" << c << ") for function \"" << name << "\"\n"; it = specializations.erase(it); } else { it++; } seen_const_true |= is_one(c); } // If the final Specialization is const-true, then the default schedule // for the definition will never be run: replace the definition's main // schedule with the one from the final Specialization and prune it from // the list. This may leave the list of Specializations empty. if (!specializations.empty() && is_one(specializations.back().condition)) { debug(1) << "Replacing default Schedule with const-true specialization for function \"" << name << "\"\n"; const Definition s_def = specializations.back().definition; specializations.pop_back(); def.predicate() = s_def.predicate(); def.values() = s_def.values(); def.args() = s_def.args(); def.schedule() = s_def.schedule(); // Append our sub-specializations to the Definition's list specializations.insert(specializations.end(), s_def.specializations().begin(), s_def.specializations().end()); } for (size_t i = specializations.size(); i > 0; i--) { Expr c = specializations[i-1].condition; Definition &s_def = specializations[i-1].definition; const EQ *eq = c.as<EQ>(); const Variable *var = eq ? eq->a.as<Variable>() : c.as<Variable>(); vector<Definition> s_result = propagate_specialization_in_definition(s_def, name); if (var && eq) { // Then case substitute_value_in_var(var->name, eq->b, s_result); // Else case if (eq->b.type().is_bool()) { substitute_value_in_var(var->name, !eq->b, result); } } else if (var) { // Then case substitute_value_in_var(var->name, const_true(), s_result); // Else case substitute_value_in_var(var->name, const_false(), result); } else { simplify_using_fact(c, s_result); simplify_using_fact(!c, result); } result.insert(result.end(), s_result.begin(), s_result.end()); } return result; } } void simplify_specializations(map<string, Function> &env) { for (auto &iter : env) { Function &func = iter.second; propagate_specialization_in_definition(func.definition(), func.name()); } } } }
Revert previous change
Revert previous change values and args *can* vary across specializations in some cases, per psuriana@ Former-commit-id: d76ea81df849239dff5d959bf9b4141dc68e9f80
C++
mit
Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide
04a5298a72d53fa990383ccbe1825a93f09d55df
api/impl/halValidate.cpp
api/impl/halValidate.cpp
/* * Copyright (C) 2012 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " length of segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << childSegment->getLength() << " which does not match " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { throw hal_exception("parent / child index mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index out of range"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } }
/* * Copyright (C) 2012 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " with index " << childSegment->getArrayIndex() << " and start position " << childSegment->getStartPosition() << " and sequence " << childSegment->getSequence()->getName() << " has length " << childSegment->getLength() << " but parent with index " << bottomSegment->getArrayIndex() << " and start position " << bottomSegment->getStartPosition() << " in sequence " << bottomSegment->getSequence()->getName() << " has length " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { throw hal_exception("parent / child index mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index out of range"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } }
add a bit more information to error message
add a bit more information to error message
C++
mit
glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal
b256fd8a4b87e9ae30847d9e1995d9de2b59076b
src/Mod/Part/Gui/AppPartGui.cpp
src/Mod/Part/Gui/AppPartGui.cpp
/*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * for detail see the LICENCE text file. * * J�rgen Riegel 2002 * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> #endif #include <Base/Console.h> #include <Base/Interpreter.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/WidgetFactory.h> #include <Mod/Part/App/PropertyTopoShape.h> #include "SoBrepFaceSet.h" #include "SoBrepEdgeSet.h" #include "SoBrepPointSet.h" #include "SoFCShapeObject.h" #include "ViewProvider.h" #include "ViewProviderExt.h" #include "ViewProviderPython.h" #include "ViewProviderBox.h" #include "ViewProviderCurveNet.h" #include "ViewProviderImport.h" #include "ViewProviderExtrusion.h" #include "ViewProvider2DObject.h" #include "ViewProviderMirror.h" #include "ViewProviderBoolean.h" #include "ViewProviderCompound.h" #include "ViewProviderCircleParametric.h" #include "ViewProviderLineParametric.h" #include "ViewProviderPointParametric.h" #include "ViewProviderEllipseParametric.h" #include "ViewProviderHelixParametric.h" #include "ViewProviderPlaneParametric.h" #include "ViewProviderSphereParametric.h" #include "ViewProviderCylinderParametric.h" #include "ViewProviderConeParametric.h" #include "ViewProviderTorusParametric.h" #include "ViewProviderRuledSurface.h" #include "ViewProviderPrism.h" #include "ViewProviderSpline.h" #include "ViewProviderRegularPolygon.h" #include "DlgSettingsGeneral.h" #include "DlgSettingsObjectColor.h" #include "DlgSettings3DViewPartImp.h" #include "Workbench.h" #include <Gui/Language/Translator.h> #include "Resources/icons/PartFeature.xpm" #include "Resources/icons/PartFeatureImport.xpm" // use a different name to CreateCommand() void CreatePartCommands(void); void CreateSimplePartCommands(void); void CreateParamPartCommands(void); void loadPartResource() { // add resources and reloads the translators Q_INIT_RESOURCE(Part); Gui::Translator::instance()->refresh(); } /* registration table */ static struct PyMethodDef PartGui_methods[] = { {NULL, NULL} /* end of table marker */ }; extern "C" { void PartGuiExport initPartGui() { if (!Gui::Application::Instance) { PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application."); return; } // load needed modules try { Base::Interpreter().runString("import Part"); } catch(const Base::Exception& e) { PyErr_SetString(PyExc_ImportError, e.what()); return; } (void) Py_InitModule("PartGui", PartGui_methods); /* mod name, table ptr */ Base::Console().Log("Loading GUI of Part module... done\n"); PartGui::SoBrepFaceSet ::initClass(); PartGui::SoBrepEdgeSet ::initClass(); PartGui::SoBrepPointSet ::initClass(); PartGui::SoFCControlPoints ::initClass(); PartGui::ViewProviderPartBase ::init(); PartGui::ViewProviderPartExt ::init(); PartGui::ViewProviderPart ::init(); PartGui::ViewProviderEllipsoid ::init(); PartGui::ViewProviderPython ::init(); PartGui::ViewProviderBox ::init(); PartGui::ViewProviderPrism ::init(); PartGui::ViewProviderWedge ::init(); PartGui::ViewProviderImport ::init(); PartGui::ViewProviderCurveNet ::init(); PartGui::ViewProviderExtrusion ::init(); PartGui::ViewProvider2DObject ::init(); PartGui::ViewProvider2DObjectPython ::init(); PartGui::ViewProviderMirror ::init(); PartGui::ViewProviderFillet ::init(); PartGui::ViewProviderChamfer ::init(); PartGui::ViewProviderRevolution ::init(); PartGui::ViewProviderLoft ::init(); PartGui::ViewProviderSweep ::init(); PartGui::ViewProviderOffset ::init(); PartGui::ViewProviderThickness ::init(); PartGui::ViewProviderCustom ::init(); PartGui::ViewProviderCustomPython ::init(); PartGui::ViewProviderBoolean ::init(); PartGui::ViewProviderMultiFuse ::init(); PartGui::ViewProviderMultiCommon ::init(); PartGui::ViewProviderCompound ::init(); PartGui::ViewProviderSpline ::init(); PartGui::ViewProviderCircleParametric ::init(); PartGui::ViewProviderLineParametric ::init(); PartGui::ViewProviderPointParametric ::init(); PartGui::ViewProviderEllipseParametric ::init(); PartGui::ViewProviderHelixParametric ::init(); PartGui::ViewProviderSpiralParametric ::init(); PartGui::ViewProviderPlaneParametric ::init(); PartGui::ViewProviderSphereParametric ::init(); PartGui::ViewProviderCylinderParametric ::init(); PartGui::ViewProviderConeParametric ::init(); PartGui::ViewProviderTorusParametric ::init(); PartGui::ViewProviderRuledSurface ::init(); PartGui::Workbench ::init(); // instantiating the commands CreatePartCommands(); CreateSimplePartCommands(); CreateParamPartCommands(); // register preferences pages (void)new Gui::PrefPageProducer<PartGui::DlgSettingsGeneral> ( QT_TRANSLATE_NOOP("QObject","Part design") ); (void)new Gui::PrefPageProducer<PartGui::DlgSettings3DViewPart> ( QT_TRANSLATE_NOOP("QObject","Part design") ); (void)new Gui::PrefPageProducer<PartGui::DlgSettingsObjectColor> ( QT_TRANSLATE_NOOP("QObject","Display") ); Gui::ViewProviderBuilder::add( Part::PropertyPartShape::getClassTypeId(), PartGui::ViewProviderPart::getClassTypeId()); // add resources and reloads the translators loadPartResource(); // register bitmaps Gui::BitmapFactoryInst& rclBmpFactory = Gui::BitmapFactory(); rclBmpFactory.addXPM("PartFeature",(const char**) PartFeature_xpm); rclBmpFactory.addXPM("PartFeatureImport",(const char**) PartFeatureImport_xpm); } } // extern "C"
/*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * for detail see the LICENCE text file. * * J�rgen Riegel 2002 * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> #endif #include <Base/Console.h> #include <Base/Interpreter.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/WidgetFactory.h> #include <Mod/Part/App/PropertyTopoShape.h> #include "SoBrepFaceSet.h" #include "SoBrepEdgeSet.h" #include "SoBrepPointSet.h" #include "SoFCShapeObject.h" #include "ViewProvider.h" #include "ViewProviderExt.h" #include "ViewProviderPython.h" #include "ViewProviderBox.h" #include "ViewProviderCurveNet.h" #include "ViewProviderImport.h" #include "ViewProviderExtrusion.h" #include "ViewProvider2DObject.h" #include "ViewProviderMirror.h" #include "ViewProviderBoolean.h" #include "ViewProviderCompound.h" #include "ViewProviderCircleParametric.h" #include "ViewProviderLineParametric.h" #include "ViewProviderPointParametric.h" #include "ViewProviderEllipseParametric.h" #include "ViewProviderHelixParametric.h" #include "ViewProviderPlaneParametric.h" #include "ViewProviderSphereParametric.h" #include "ViewProviderCylinderParametric.h" #include "ViewProviderConeParametric.h" #include "ViewProviderTorusParametric.h" #include "ViewProviderRuledSurface.h" #include "ViewProviderPrism.h" #include "ViewProviderSpline.h" #include "ViewProviderRegularPolygon.h" #include "DlgSettingsGeneral.h" #include "DlgSettingsObjectColor.h" #include "DlgSettings3DViewPartImp.h" #include "Workbench.h" #include <Gui/Language/Translator.h> #include "Resources/icons/PartFeature.xpm" #include "Resources/icons/PartFeatureImport.xpm" // use a different name to CreateCommand() void CreatePartCommands(void); void CreateSimplePartCommands(void); void CreateParamPartCommands(void); void loadPartResource() { // add resources and reloads the translators Q_INIT_RESOURCE(Part); Gui::Translator::instance()->refresh(); } /* registration table */ static struct PyMethodDef PartGui_methods[] = { {NULL, NULL} /* end of table marker */ }; extern "C" { void PartGuiExport initPartGui() { if (!Gui::Application::Instance) { PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application."); return; } // load needed modules try { Base::Interpreter().runString("import Part"); } catch(const Base::Exception& e) { PyErr_SetString(PyExc_ImportError, e.what()); return; } (void) Py_InitModule("PartGui", PartGui_methods); /* mod name, table ptr */ Base::Console().Log("Loading GUI of Part module... done\n"); PartGui::SoBrepFaceSet ::initClass(); PartGui::SoBrepEdgeSet ::initClass(); PartGui::SoBrepPointSet ::initClass(); PartGui::SoFCControlPoints ::initClass(); PartGui::ViewProviderPartBase ::init(); PartGui::ViewProviderPartExt ::init(); PartGui::ViewProviderPart ::init(); PartGui::ViewProviderEllipsoid ::init(); PartGui::ViewProviderPython ::init(); PartGui::ViewProviderBox ::init(); PartGui::ViewProviderPrism ::init(); PartGui::ViewProviderRegularPolygon ::init(); PartGui::ViewProviderWedge ::init(); PartGui::ViewProviderImport ::init(); PartGui::ViewProviderCurveNet ::init(); PartGui::ViewProviderExtrusion ::init(); PartGui::ViewProvider2DObject ::init(); PartGui::ViewProvider2DObjectPython ::init(); PartGui::ViewProviderMirror ::init(); PartGui::ViewProviderFillet ::init(); PartGui::ViewProviderChamfer ::init(); PartGui::ViewProviderRevolution ::init(); PartGui::ViewProviderLoft ::init(); PartGui::ViewProviderSweep ::init(); PartGui::ViewProviderOffset ::init(); PartGui::ViewProviderThickness ::init(); PartGui::ViewProviderCustom ::init(); PartGui::ViewProviderCustomPython ::init(); PartGui::ViewProviderBoolean ::init(); PartGui::ViewProviderMultiFuse ::init(); PartGui::ViewProviderMultiCommon ::init(); PartGui::ViewProviderCompound ::init(); PartGui::ViewProviderSpline ::init(); PartGui::ViewProviderCircleParametric ::init(); PartGui::ViewProviderLineParametric ::init(); PartGui::ViewProviderPointParametric ::init(); PartGui::ViewProviderEllipseParametric ::init(); PartGui::ViewProviderHelixParametric ::init(); PartGui::ViewProviderSpiralParametric ::init(); PartGui::ViewProviderPlaneParametric ::init(); PartGui::ViewProviderSphereParametric ::init(); PartGui::ViewProviderCylinderParametric ::init(); PartGui::ViewProviderConeParametric ::init(); PartGui::ViewProviderTorusParametric ::init(); PartGui::ViewProviderRuledSurface ::init(); PartGui::Workbench ::init(); // instantiating the commands CreatePartCommands(); CreateSimplePartCommands(); CreateParamPartCommands(); // register preferences pages (void)new Gui::PrefPageProducer<PartGui::DlgSettingsGeneral> ( QT_TRANSLATE_NOOP("QObject","Part design") ); (void)new Gui::PrefPageProducer<PartGui::DlgSettings3DViewPart> ( QT_TRANSLATE_NOOP("QObject","Part design") ); (void)new Gui::PrefPageProducer<PartGui::DlgSettingsObjectColor> ( QT_TRANSLATE_NOOP("QObject","Display") ); Gui::ViewProviderBuilder::add( Part::PropertyPartShape::getClassTypeId(), PartGui::ViewProviderPart::getClassTypeId()); // add resources and reloads the translators loadPartResource(); // register bitmaps Gui::BitmapFactoryInst& rclBmpFactory = Gui::BitmapFactory(); rclBmpFactory.addXPM("PartFeature",(const char**) PartFeature_xpm); rclBmpFactory.addXPM("PartFeatureImport",(const char**) PartFeatureImport_xpm); } } // extern "C"
rebase auto merge error fix AppPartGui.cpp
rebase auto merge error fix AppPartGui.cpp add ViewProviderRegularPolygon
C++
lgpl-2.1
Fat-Zer/FreeCAD_sf_master,Creworker/FreeCAD,cypsun/FreeCAD,cypsun/FreeCAD,marcoitur/FreeCAD,cpollard1001/FreeCAD_sf_master,elgambitero/FreeCAD_sf_master,usakhelo/FreeCAD,Alpistinho/FreeCAD,Alpistinho/FreeCAD,marcoitur/Freecad_test,jriegel/FreeCAD,jonnor/FreeCAD,jonnor/FreeCAD,maurerpe/FreeCAD,bblacey/FreeCAD-MacOS-CI,kkoksvik/FreeCAD,Creworker/FreeCAD,wood-galaxy/FreeCAD,cpollard1001/FreeCAD_sf_master,timthelion/FreeCAD,timthelion/FreeCAD_sf_master,marcoitur/Freecad_test,maurerpe/FreeCAD,chrisjaquet/FreeCAD,jriegel/FreeCAD,YuanYouYuan/FreeCAD,yantrabuddhi/FreeCAD,bblacey/FreeCAD-MacOS-CI,bblacey/FreeCAD-MacOS-CI,mickele77/FreeCAD,wood-galaxy/FreeCAD,kkoksvik/FreeCAD,marcoitur/FreeCAD,Alpistinho/FreeCAD,mickele77/FreeCAD,YuanYouYuan/FreeCAD,YuanYouYuan/FreeCAD,dsbrown/FreeCAD,bblacey/FreeCAD-MacOS-CI,jonnor/FreeCAD,YuanYouYuan/FreeCAD,timthelion/FreeCAD,cpollard1001/FreeCAD_sf_master,timthelion/FreeCAD,balazs-bamer/FreeCAD-Surface,dsbrown/FreeCAD,jonnor/FreeCAD,bblacey/FreeCAD-MacOS-CI,timthelion/FreeCAD,marcoitur/Freecad_test,cypsun/FreeCAD,kkoksvik/FreeCAD,usakhelo/FreeCAD,dsbrown/FreeCAD,jriegel/FreeCAD,dsbrown/FreeCAD,elgambitero/FreeCAD_sf_master,usakhelo/FreeCAD,wood-galaxy/FreeCAD,yantrabuddhi/FreeCAD,cpollard1001/FreeCAD_sf_master,chrisjaquet/FreeCAD,marcoitur/Freecad_test,chrisjaquet/FreeCAD,yantrabuddhi/FreeCAD,cypsun/FreeCAD,jriegel/FreeCAD,kkoksvik/FreeCAD,usakhelo/FreeCAD,kkoksvik/FreeCAD,Creworker/FreeCAD,balazs-bamer/FreeCAD-Surface,marcoitur/FreeCAD,Alpistinho/FreeCAD,chrisjaquet/FreeCAD,elgambitero/FreeCAD_sf_master,timthelion/FreeCAD_sf_master,cypsun/FreeCAD,usakhelo/FreeCAD,balazs-bamer/FreeCAD-Surface,thdtjsdn/FreeCAD,chrisjaquet/FreeCAD,usakhelo/FreeCAD,jriegel/FreeCAD,jonnor/FreeCAD,thdtjsdn/FreeCAD,Creworker/FreeCAD,balazs-bamer/FreeCAD-Surface,mickele77/FreeCAD,timthelion/FreeCAD_sf_master,thdtjsdn/FreeCAD,timthelion/FreeCAD,elgambitero/FreeCAD_sf_master,wood-galaxy/FreeCAD,wood-galaxy/FreeCAD,wood-galaxy/FreeCAD,chrisjaquet/FreeCAD,yantrabuddhi/FreeCAD,thdtjsdn/FreeCAD,timthelion/FreeCAD_sf_master,bblacey/FreeCAD-MacOS-CI,maurerpe/FreeCAD,bblacey/FreeCAD-MacOS-CI,marcoitur/FreeCAD,Fat-Zer/FreeCAD_sf_master,timthelion/FreeCAD,thdtjsdn/FreeCAD,yantrabuddhi/FreeCAD,cpollard1001/FreeCAD_sf_master,mickele77/FreeCAD,mickele77/FreeCAD,maurerpe/FreeCAD,timthelion/FreeCAD_sf_master,usakhelo/FreeCAD,Fat-Zer/FreeCAD_sf_master,balazs-bamer/FreeCAD-Surface,marcoitur/Freecad_test,marcoitur/FreeCAD,Fat-Zer/FreeCAD_sf_master,Alpistinho/FreeCAD,dsbrown/FreeCAD,maurerpe/FreeCAD,elgambitero/FreeCAD_sf_master,YuanYouYuan/FreeCAD,Creworker/FreeCAD,Fat-Zer/FreeCAD_sf_master,chrisjaquet/FreeCAD
48cd8d58136ccbb952be1bf536b2a3031a56c1d4
interpreter/cling/test/LibraryCall/call.C
interpreter/cling/test/LibraryCall/call.C
// RUN: clang -shared %S/call_lib.c -olibcall_lib%shlibext && cat %s | %cling | FileCheck %s .L libcall_lib extern "C" int cling_testlibrary_function(); int i = cling_testlibrary_function(); extern "C" int printf(const char* fmt, ...); printf("got i=%d\n", i); // CHECK: got i=66 .q
// RUN: clang -shared %S/call_lib.c -o%p/libcall_lib%shlibext && ls %p/libcall_lib%shlibext && cat %s | %cling -L%p | FileCheck %s .L libcall_lib extern "C" int cling_testlibrary_function(); int i = cling_testlibrary_function(); extern "C" int printf(const char* fmt, ...); printf("got i=%d\n", i); // CHECK: got i=66 .q
Make test more verbose; fix directory for library.
Make test more verbose; fix directory for library. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@47430 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
d42de28bf476643a1b01e749d4fe83ba668821da
src/OrbitGl/ModulesDataView.cpp
src/OrbitGl/ModulesDataView.cpp
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ModulesDataView.h" #include <absl/flags/declare.h> #include <absl/strings/ascii.h> #include <absl/strings/str_format.h> #include <absl/strings/str_split.h> #include <stddef.h> #include <algorithm> #include <cstdint> #include <functional> #include "App.h" #include "CoreUtils.h" #include "DataViewTypes.h" #include "OrbitBase/Logging.h" #include "OrbitClientData/ProcessData.h" #include "absl/flags/flag.h" ABSL_DECLARE_FLAG(bool, enable_frame_pointer_validator); ModulesDataView::ModulesDataView(OrbitApp* app) : DataView(DataViewType::kModules, app) {} const std::vector<DataView::Column>& ModulesDataView::GetColumns() { static const std::vector<Column> columns = [] { std::vector<Column> columns; columns.resize(kNumColumns); columns[kColumnName] = {"Name", .2f, SortingOrder::kAscending}; columns[kColumnPath] = {"Path", .5f, SortingOrder::kAscending}; columns[kColumnAddressRange] = {"Address Range", .15f, SortingOrder::kAscending}; columns[kColumnFileSize] = {"File Size", .0f, SortingOrder::kDescending}; columns[kColumnLoaded] = {"Loaded", .0f, SortingOrder::kDescending}; return columns; }(); return columns; } std::string ModulesDataView::GetValue(int row, int col) { const ModuleData* module = GetModule(row); const MemorySpace* memory_space = module_memory_.at(module); switch (col) { case kColumnName: return module->name(); case kColumnPath: return module->file_path(); case kColumnAddressRange: return memory_space->FormattedAddressRange(); case kColumnFileSize: return GetPrettySize(module->file_size()); case kColumnLoaded: return module->is_loaded() ? "*" : ""; default: return ""; } } #define ORBIT_PROC_SORT(Member) \ [&](int a, int b) { \ return orbit_core::Compare(modules_[a]->Member, modules_[b]->Member, ascending); \ } #define ORBIT_MODULE_SPACE_SORT(Member) \ [&](int a, int b) { \ return orbit_core::Compare(module_memory_.at(modules_[a])->Member, \ module_memory_.at(modules_[b])->Member, ascending); \ } void ModulesDataView::DoSort() { bool ascending = sorting_orders_[sorting_column_] == SortingOrder::kAscending; std::function<bool(int a, int b)> sorter = nullptr; switch (sorting_column_) { case kColumnName: sorter = ORBIT_PROC_SORT(name()); break; case kColumnPath: sorter = ORBIT_PROC_SORT(file_path()); break; case kColumnAddressRange: sorter = ORBIT_MODULE_SPACE_SORT(start); break; case kColumnFileSize: sorter = ORBIT_PROC_SORT(file_size()); break; case kColumnLoaded: sorter = ORBIT_PROC_SORT(is_loaded()); break; default: break; } if (sorter) { std::stable_sort(indices_.begin(), indices_.end(), sorter); } } const std::string ModulesDataView::kMenuActionLoadSymbols = "Load Symbols"; const std::string ModulesDataView::kMenuActionVerifyFramePointers = "Verify Frame Pointers"; std::vector<std::string> ModulesDataView::GetContextMenu(int clicked_index, const std::vector<int>& selected_indices) { bool enable_load = false; bool enable_verify = false; for (int index : selected_indices) { const ModuleData* module = GetModule(index); if (!module->is_loaded()) { enable_load = true; } if (module->is_loaded()) { enable_verify = true; } } std::vector<std::string> menu; if (enable_load) { menu.emplace_back(kMenuActionLoadSymbols); } if (enable_verify && absl::GetFlag(FLAGS_enable_frame_pointer_validator)) { menu.emplace_back(kMenuActionVerifyFramePointers); } Append(menu, DataView::GetContextMenu(clicked_index, selected_indices)); return menu; } void ModulesDataView::OnContextMenu(const std::string& action, int menu_index, const std::vector<int>& item_indices) { if (action == kMenuActionLoadSymbols) { std::vector<ModuleData*> modules_to_load; for (int index : item_indices) { ModuleData* module_data = GetModule(index); if (!module_data->is_loaded()) { modules_to_load.push_back(module_data); } } app_->LoadModules(modules_to_load); } else if (action == kMenuActionVerifyFramePointers) { std::vector<const ModuleData*> modules_to_validate; modules_to_validate.reserve(item_indices.size()); for (int index : item_indices) { const ModuleData* module = GetModule(index); modules_to_validate.push_back(module); } if (!modules_to_validate.empty()) { app_->OnValidateFramePointers(modules_to_validate); } } else { DataView::OnContextMenu(action, menu_index, item_indices); } } void ModulesDataView::OnDoubleClicked(int index) { ModuleData* module_data = GetModule(index); if (!module_data->is_loaded()) { std::vector<ModuleData*> modules_to_load = {module_data}; app_->LoadModules(modules_to_load); } } void ModulesDataView::DoFilter() { std::vector<uint64_t> indices; std::vector<std::string> tokens = absl::StrSplit(ToLower(filter_), ' '); for (size_t i = 0; i < modules_.size(); ++i) { const ModuleData* module = modules_[i]; const MemorySpace* memory_space = module_memory_.at(module); std::string module_string = absl::StrFormat("%s %s", memory_space->FormattedAddressRange(), absl::AsciiStrToLower(module->file_path())); bool match = true; for (std::string& filter_token : tokens) { if (module_string.find(filter_token) == std::string::npos) { match = false; break; } } if (match) { indices.push_back(i); } } indices_ = std::move(indices); } void ModulesDataView::UpdateModules(const ProcessData* process) { modules_.clear(); module_memory_.clear(); for (const auto& [module_path, memory_space] : process->GetMemoryMap()) { ModuleData* module = app_->GetMutableModuleByPath(module_path); modules_.push_back(module); module_memory_[module] = &memory_space; } indices_.resize(modules_.size()); for (size_t i = 0; i < indices_.size(); ++i) { indices_[i] = i; } OnDataChanged(); } void ModulesDataView::OnRefreshButtonClicked() { const ProcessData* process = app_->GetTargetProcess(); if (process == nullptr) { LOG("Unable to refresh module list, no process selected"); return; } app_->UpdateProcessAndModuleList(process->pid()); } bool ModulesDataView::GetDisplayColor(int row, int /*column*/, unsigned char& red, unsigned char& green, unsigned char& blue) { const ModuleData* module = GetModule(row); if (module->is_loaded()) { red = 42; green = 218; blue = 130; return true; } else { red = 42; green = 130; blue = 218; return true; } }
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ModulesDataView.h" #include <absl/flags/declare.h> #include <absl/strings/ascii.h> #include <absl/strings/str_format.h> #include <absl/strings/str_split.h> #include <stddef.h> #include <algorithm> #include <cstdint> #include <functional> #include "App.h" #include "CoreUtils.h" #include "DataViewTypes.h" #include "OrbitBase/Logging.h" #include "OrbitClientData/ProcessData.h" #include "absl/flags/flag.h" ABSL_DECLARE_FLAG(bool, enable_frame_pointer_validator); ModulesDataView::ModulesDataView(OrbitApp* app) : DataView(DataViewType::kModules, app) {} const std::vector<DataView::Column>& ModulesDataView::GetColumns() { static const std::vector<Column> columns = [] { std::vector<Column> columns; columns.resize(kNumColumns); columns[kColumnName] = {"Name", .2f, SortingOrder::kAscending}; columns[kColumnPath] = {"Path", .5f, SortingOrder::kAscending}; columns[kColumnAddressRange] = {"Address Range", .15f, SortingOrder::kAscending}; columns[kColumnFileSize] = {"File Size", .0f, SortingOrder::kDescending}; columns[kColumnLoaded] = {"Loaded", .0f, SortingOrder::kDescending}; return columns; }(); return columns; } std::string ModulesDataView::GetValue(int row, int col) { const ModuleData* module = GetModule(row); const MemorySpace* memory_space = module_memory_.at(module); switch (col) { case kColumnName: return module->name(); case kColumnPath: return module->file_path(); case kColumnAddressRange: return memory_space->FormattedAddressRange(); case kColumnFileSize: return GetPrettySize(module->file_size()); case kColumnLoaded: return module->is_loaded() ? "*" : ""; default: return ""; } } #define ORBIT_PROC_SORT(Member) \ [&](int a, int b) { \ return orbit_core::Compare(modules_[a]->Member, modules_[b]->Member, ascending); \ } #define ORBIT_MODULE_SPACE_SORT(Member) \ [&](int a, int b) { \ return orbit_core::Compare(module_memory_.at(modules_[a])->Member, \ module_memory_.at(modules_[b])->Member, ascending); \ } void ModulesDataView::DoSort() { bool ascending = sorting_orders_[sorting_column_] == SortingOrder::kAscending; std::function<bool(int a, int b)> sorter = nullptr; switch (sorting_column_) { case kColumnName: sorter = ORBIT_PROC_SORT(name()); break; case kColumnPath: sorter = ORBIT_PROC_SORT(file_path()); break; case kColumnAddressRange: sorter = ORBIT_MODULE_SPACE_SORT(start); break; case kColumnFileSize: sorter = ORBIT_PROC_SORT(file_size()); break; case kColumnLoaded: sorter = ORBIT_PROC_SORT(is_loaded()); break; default: break; } if (sorter) { std::stable_sort(indices_.begin(), indices_.end(), sorter); } } const std::string ModulesDataView::kMenuActionLoadSymbols = "Load Symbols"; const std::string ModulesDataView::kMenuActionVerifyFramePointers = "Verify Frame Pointers"; std::vector<std::string> ModulesDataView::GetContextMenu(int clicked_index, const std::vector<int>& selected_indices) { bool enable_load = false; bool enable_verify = false; for (int index : selected_indices) { const ModuleData* module = GetModule(index); if (!module->is_loaded()) { enable_load = true; } if (module->is_loaded()) { enable_verify = true; } } std::vector<std::string> menu; if (enable_load) { menu.emplace_back(kMenuActionLoadSymbols); } if (enable_verify && absl::GetFlag(FLAGS_enable_frame_pointer_validator)) { menu.emplace_back(kMenuActionVerifyFramePointers); } Append(menu, DataView::GetContextMenu(clicked_index, selected_indices)); return menu; } void ModulesDataView::OnContextMenu(const std::string& action, int menu_index, const std::vector<int>& item_indices) { if (action == kMenuActionLoadSymbols) { std::vector<ModuleData*> modules_to_load; for (int index : item_indices) { ModuleData* module_data = GetModule(index); if (!module_data->is_loaded()) { modules_to_load.push_back(module_data); } } app_->LoadModules(modules_to_load); } else if (action == kMenuActionVerifyFramePointers) { std::vector<const ModuleData*> modules_to_validate; modules_to_validate.reserve(item_indices.size()); for (int index : item_indices) { const ModuleData* module = GetModule(index); modules_to_validate.push_back(module); } if (!modules_to_validate.empty()) { app_->OnValidateFramePointers(modules_to_validate); } } else { DataView::OnContextMenu(action, menu_index, item_indices); } } void ModulesDataView::OnDoubleClicked(int index) { ModuleData* module_data = GetModule(index); if (!module_data->is_loaded()) { std::vector<ModuleData*> modules_to_load = {module_data}; app_->LoadModules(modules_to_load); } } void ModulesDataView::DoFilter() { std::vector<uint64_t> indices; std::vector<std::string> tokens = absl::StrSplit(ToLower(filter_), ' '); for (size_t i = 0; i < modules_.size(); ++i) { const ModuleData* module = modules_[i]; const MemorySpace* memory_space = module_memory_.at(module); std::string module_string = absl::StrFormat("%s %s", memory_space->FormattedAddressRange(), absl::AsciiStrToLower(module->file_path())); bool match = true; for (std::string& filter_token : tokens) { if (module_string.find(filter_token) == std::string::npos) { match = false; break; } } if (match) { indices.push_back(i); } } indices_ = std::move(indices); } void ModulesDataView::UpdateModules(const ProcessData* process) { modules_.clear(); module_memory_.clear(); for (const auto& [module_path, memory_space] : process->GetMemoryMap()) { ModuleData* module = app_->GetMutableModuleByPath(module_path); modules_.push_back(module); module_memory_[module] = &memory_space; } indices_.resize(modules_.size()); for (size_t i = 0; i < indices_.size(); ++i) { indices_[i] = i; } OnDataChanged(); } void ModulesDataView::OnRefreshButtonClicked() { const ProcessData* process = app_->GetTargetProcess(); if (process == nullptr) { LOG("Unable to refresh module list, no process selected"); return; } app_->UpdateProcessAndModuleList(process->pid()); } bool ModulesDataView::GetDisplayColor(int row, int /*column*/, unsigned char& red, unsigned char& green, unsigned char& blue) { const ModuleData* module = GetModule(row); if (module->is_loaded()) { red = 42; green = 218; blue = 130; } else { red = 42; green = 130; blue = 218; } return true; }
Address lint warning in ModulesDataView
Address lint warning in ModulesDataView
C++
bsd-2-clause
google/orbit,google/orbit,google/orbit,google/orbit
e548154bbb1cfbe344bd86f9195f40e5ecb6db3a
runtime/vm/os_fuchsia.cc
runtime/vm/os_fuchsia.cc
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/os.h" #include <errno.h> #include <lib/fdio/util.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include <fuchsia/timezone/cpp/fidl.h> #include "lib/component/cpp/startup_context.h" #include "lib/svc/cpp/services.h" #include "platform/assert.h" #include "vm/zone.h" namespace dart { #ifndef PRODUCT DEFINE_FLAG(bool, generate_perf_events_symbols, false, "Generate events symbols for profiling with perf"); #endif // !PRODUCT const char* OS::Name() { return "fuchsia"; } intptr_t OS::ProcessId() { return static_cast<intptr_t>(getpid()); } // TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to // directly get timezone. // // Putting this hack right now due to CP-120 as I need to remove // component:ConnectToEnvironmentServices and this is the only thing that is // blocking it and FL-98 will take time. static fuchsia::timezone::TimezoneSyncPtr tz; static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch, int32_t* local_offset, int32_t* dst_offset) { zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000, local_offset, dst_offset); if (status != ZX_OK) { return status; } *local_offset *= 60; *dst_offset *= 60; return ZX_OK; } const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) { // TODO(abarth): Handle time zone changes. static const auto* tz_name = new std::string([] { fidl::StringPtr result; tz->GetTimezoneId(&result); return *result; }()); return tz_name->c_str(); } int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( seconds_since_epoch, &local_offset, &dst_offset); return status == ZX_OK ? local_offset + dst_offset : 0; } int OS::GetLocalTimeZoneAdjustmentInSeconds() { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset); return status == ZX_OK ? local_offset : 0; } int64_t OS::GetCurrentTimeMillis() { return GetCurrentTimeMicros() / 1000; } int64_t OS::GetCurrentTimeMicros() { return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentMonotonicTicks() { return zx_clock_get(ZX_CLOCK_MONOTONIC); } int64_t OS::GetCurrentMonotonicFrequency() { return kNanosecondsPerSecond; } int64_t OS::GetCurrentMonotonicMicros() { int64_t ticks = GetCurrentMonotonicTicks(); ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond); return ticks / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentThreadCPUMicros() { return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond; } // TODO(5411554): May need to hoist these architecture dependent code // into a architecture specific file e.g: os_ia32_fuchsia.cc intptr_t OS::ActivationFrameAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) const int kMinimumAlignment = 16; #elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 8; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default stack alignment for // testing purposes. // Flags::DebugIsInt("stackalign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); return alignment; } intptr_t OS::PreferredCodeAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 32; #elif defined(TARGET_ARCH_ARM) const int kMinimumAlignment = 16; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default code alignment for // testing purposes. // Flags::DebugIsInt("codealign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); ASSERT(alignment <= OS::kMaxPreferredCodeAlignment); return alignment; } int OS::NumberOfAvailableProcessors() { return sysconf(_SC_NPROCESSORS_CONF); } void OS::Sleep(int64_t millis) { SleepMicros(millis * kMicrosecondsPerMillisecond); } void OS::SleepMicros(int64_t micros) { zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond)); } void OS::DebugBreak() { UNIMPLEMENTED(); } DART_NOINLINE uintptr_t OS::GetProgramCounter() { return reinterpret_cast<uintptr_t>( __builtin_extract_return_addr(__builtin_return_address(0))); } void OS::Print(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stdout, format, args); va_end(args); } void OS::VFPrint(FILE* stream, const char* format, va_list args) { vfprintf(stream, format, args); fflush(stream); } char* OS::SCreate(Zone* zone, const char* format, ...) { va_list args; va_start(args, format); char* buffer = VSCreate(zone, format, args); va_end(args); return buffer; } char* OS::VSCreate(Zone* zone, const char* format, va_list args) { // Measure. va_list measure_args; va_copy(measure_args, args); intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args); va_end(measure_args); char* buffer; if (zone) { buffer = zone->Alloc<char>(len + 1); } else { buffer = reinterpret_cast<char*>(malloc(len + 1)); } ASSERT(buffer != NULL); // Print. va_list print_args; va_copy(print_args, args); Utils::VSNPrint(buffer, len + 1, format, print_args); va_end(print_args); return buffer; } bool OS::StringToInt64(const char* str, int64_t* value) { ASSERT(str != NULL && strlen(str) > 0 && value != NULL); int32_t base = 10; char* endptr; int i = 0; if (str[0] == '-') { i = 1; } else if (str[0] == '+') { i = 1; } if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') && (str[i + 2] != '\0')) { base = 16; } errno = 0; if (base == 16) { // Unsigned 64-bit hexadecimal integer literals are allowed but // immediately interpreted as signed 64-bit integers. *value = static_cast<int64_t>(strtoull(str, &endptr, base)); } else { *value = strtoll(str, &endptr, base); } return ((errno == 0) && (endptr != str) && (*endptr == 0)); } void OS::RegisterCodeObservers() { #ifndef PRODUCT if (FLAG_generate_perf_events_symbols) { UNIMPLEMENTED(); } #endif // !PRODUCT } void OS::PrintErr(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stderr, format, args); va_end(args); } void OS::Init() { auto environment_services = std::make_shared<component::Services>(); auto env_service_root = component::subtle::CreateStaticServiceRootHandle(); environment_services->Bind(std::move(env_service_root)); environment_services->ConnectToService(tz.NewRequest()); } void OS::Cleanup() {} void OS::Abort() { abort(); } void OS::Exit(int code) { exit(code); } } // namespace dart #endif // defined(HOST_OS_FUCHSIA)
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/os.h" #include <errno.h> #include <lib/fdio/util.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include <fuchsia/timezone/cpp/fidl.h> #include "lib/component/cpp/startup_context.h" #include "lib/svc/cpp/services.h" #include "platform/assert.h" #include "vm/zone.h" namespace dart { #ifndef PRODUCT DEFINE_FLAG(bool, generate_perf_events_symbols, false, "Generate events symbols for profiling with perf"); #endif // !PRODUCT const char* OS::Name() { return "fuchsia"; } intptr_t OS::ProcessId() { return static_cast<intptr_t>(getpid()); } // TODO(FL-98): Change this to talk to fuchsia.dart to get timezone service to // directly get timezone. // // Putting this hack right now due to CP-120 as I need to remove // component:ConnectToEnvironmentServices and this is the only thing that is // blocking it and FL-98 will take time. static fuchsia::timezone::TimezoneSyncPtr tz; static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch, int32_t* local_offset, int32_t* dst_offset) { zx_status_t status = tz->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000, local_offset, dst_offset); if (status != ZX_OK) { return status; } *local_offset *= 60; *dst_offset *= 60; return ZX_OK; } const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) { // TODO(abarth): Handle time zone changes. static const auto* tz_name = new std::string([] { #ifdef USE_STD_FOR_NON_NULLABLE_FIDL_FIELDS std::string result; tz->GetTimezoneId(&result); return result; #else fidl::StringPtr result; tz->GetTimezoneId(&result); return *result; #endif }()); return tz_name->c_str(); } int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( seconds_since_epoch, &local_offset, &dst_offset); return status == ZX_OK ? local_offset + dst_offset : 0; } int OS::GetLocalTimeZoneAdjustmentInSeconds() { int32_t local_offset, dst_offset; zx_status_t status = GetLocalAndDstOffsetInSeconds( zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset); return status == ZX_OK ? local_offset : 0; } int64_t OS::GetCurrentTimeMillis() { return GetCurrentTimeMicros() / 1000; } int64_t OS::GetCurrentTimeMicros() { return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentMonotonicTicks() { return zx_clock_get(ZX_CLOCK_MONOTONIC); } int64_t OS::GetCurrentMonotonicFrequency() { return kNanosecondsPerSecond; } int64_t OS::GetCurrentMonotonicMicros() { int64_t ticks = GetCurrentMonotonicTicks(); ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond); return ticks / kNanosecondsPerMicrosecond; } int64_t OS::GetCurrentThreadCPUMicros() { return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond; } // TODO(5411554): May need to hoist these architecture dependent code // into a architecture specific file e.g: os_ia32_fuchsia.cc intptr_t OS::ActivationFrameAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) const int kMinimumAlignment = 16; #elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 8; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default stack alignment for // testing purposes. // Flags::DebugIsInt("stackalign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); return alignment; } intptr_t OS::PreferredCodeAlignment() { #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) || \ defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC) const int kMinimumAlignment = 32; #elif defined(TARGET_ARCH_ARM) const int kMinimumAlignment = 16; #else #error Unsupported architecture. #endif intptr_t alignment = kMinimumAlignment; // TODO(5411554): Allow overriding default code alignment for // testing purposes. // Flags::DebugIsInt("codealign", &alignment); ASSERT(Utils::IsPowerOfTwo(alignment)); ASSERT(alignment >= kMinimumAlignment); ASSERT(alignment <= OS::kMaxPreferredCodeAlignment); return alignment; } int OS::NumberOfAvailableProcessors() { return sysconf(_SC_NPROCESSORS_CONF); } void OS::Sleep(int64_t millis) { SleepMicros(millis * kMicrosecondsPerMillisecond); } void OS::SleepMicros(int64_t micros) { zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond)); } void OS::DebugBreak() { UNIMPLEMENTED(); } DART_NOINLINE uintptr_t OS::GetProgramCounter() { return reinterpret_cast<uintptr_t>( __builtin_extract_return_addr(__builtin_return_address(0))); } void OS::Print(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stdout, format, args); va_end(args); } void OS::VFPrint(FILE* stream, const char* format, va_list args) { vfprintf(stream, format, args); fflush(stream); } char* OS::SCreate(Zone* zone, const char* format, ...) { va_list args; va_start(args, format); char* buffer = VSCreate(zone, format, args); va_end(args); return buffer; } char* OS::VSCreate(Zone* zone, const char* format, va_list args) { // Measure. va_list measure_args; va_copy(measure_args, args); intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args); va_end(measure_args); char* buffer; if (zone) { buffer = zone->Alloc<char>(len + 1); } else { buffer = reinterpret_cast<char*>(malloc(len + 1)); } ASSERT(buffer != NULL); // Print. va_list print_args; va_copy(print_args, args); Utils::VSNPrint(buffer, len + 1, format, print_args); va_end(print_args); return buffer; } bool OS::StringToInt64(const char* str, int64_t* value) { ASSERT(str != NULL && strlen(str) > 0 && value != NULL); int32_t base = 10; char* endptr; int i = 0; if (str[0] == '-') { i = 1; } else if (str[0] == '+') { i = 1; } if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') && (str[i + 2] != '\0')) { base = 16; } errno = 0; if (base == 16) { // Unsigned 64-bit hexadecimal integer literals are allowed but // immediately interpreted as signed 64-bit integers. *value = static_cast<int64_t>(strtoull(str, &endptr, base)); } else { *value = strtoll(str, &endptr, base); } return ((errno == 0) && (endptr != str) && (*endptr == 0)); } void OS::RegisterCodeObservers() { #ifndef PRODUCT if (FLAG_generate_perf_events_symbols) { UNIMPLEMENTED(); } #endif // !PRODUCT } void OS::PrintErr(const char* format, ...) { va_list args; va_start(args, format); VFPrint(stderr, format, args); va_end(args); } void OS::Init() { auto environment_services = std::make_shared<component::Services>(); auto env_service_root = component::subtle::CreateStaticServiceRootHandle(); environment_services->Bind(std::move(env_service_root)); environment_services->ConnectToService(tz.NewRequest()); } void OS::Cleanup() {} void OS::Abort() { abort(); } void OS::Exit(int code) { exit(code); } } // namespace dart #endif // defined(HOST_OS_FUCHSIA)
Update to new FIDL API
[fuchsia] Update to new FIDL API There's an incoming change to use std:: types for non-nullable strings and vectors. See: https://fuchsia-review.googlesource.com/c/garnet/+/236996 Change-Id: Ib924e812a679213928a26dbf29402f40cb5f4cb3 Reviewed-on: https://dart-review.googlesource.com/c/88122 Commit-Queue: Zach Anderson <[email protected]> Reviewed-by: Zach Anderson <[email protected]>
C++
bsd-3-clause
dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk
82cf3dc55da6d4aeda197f0c1d01bc2925cd9657
encoder/file_writer.cc
encoder/file_writer.cc
// Copyright (c) 2015 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "encoder/file_writer.h" #include <condition_variable> #include <cstdio> #include <ctime> #include <functional> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "glog/logging.h" namespace webmlive { bool FileWriter::Init(bool dash_mode, const std::string& directory) { if (!dash_mode) { char file_name[30] = {0}; // %Y - year // %m - month, zero padded (01-12) // %d - day of month, zero padded (01-31). // %H - hour, zero padded, 24 hour clock (00-23) // %M - minute, zero padded (00-59) // %S - second, zero padded (00-61) const char format_string[] = "%Y%m%d%H%M%S"; const time_t raw_time_now = time(NULL); const struct tm* time_now = localtime(&raw_time_now); if (strftime(&file_name[0], sizeof(file_name), format_string, time_now) == 0) { LOG(ERROR) << "FileWriter cannot generate file name."; return false; } file_name_ = file_name; file_name_ += ".webm"; } directory_ = directory; return true; } bool FileWriter::Run() { using std::bind; using std::shared_ptr; using std::thread; using std::nothrow; thread_ = shared_ptr<thread>( new (nothrow) thread(bind(&FileWriter::WriterThread, // NOLINT this))); if (!thread_) { LOG(ERROR) << "Out of memory."; return false; } return true; } bool FileWriter::Stop() { // Tell WriterThread() to stop. mutex_.lock(); stop_ = true; mutex_.unlock(); // Wake and wait for WriterThread() to exit. wake_condition_.notify_one(); thread_->join(); return true; } // Copies data into |buffer_q_| and returns true. bool FileWriter::WriteData(DataSinkInterface::SharedDataSinkBuffer buffer) { // TODO(tomfinegan): Copying data is not necessary; SharedDataBufferQueue or // something should be provided by data_sink.h. Abusing BufferQueue // temporarily since it just works and incoming buffers aren't that large. if (!buffer_q_.EnqueueBuffer(buffer->id, &buffer->data[0], buffer->data.size())) { LOG(ERROR) << "Write buffer enqueue failed."; return false; } // Wake WriterThread(). LOG(INFO) << "waking WriterThread with " << buffer->data.size() << " bytes"; wake_condition_.notify_one(); return true; } // Try to obtain lock on |mutex_|, and return the value of |stop_| if lock is // obtained. Returns false if unable to obtain the lock. bool FileWriter::StopRequested() { bool stop_requested = false; std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock); if (lock.owns_lock()) { stop_requested = stop_; } return stop_requested; } // Idle the upload thread while awaiting user data. void FileWriter::WaitForUserData() { std::unique_lock<std::mutex> lock(mutex_); wake_condition_.wait(lock); // Unlock |mutex_| and idle the thread while we // wait for the next chunk of user data. } // Writes |data| contents to file and returns true upon success. bool FileWriter::WriteFile(const BufferQueue::Buffer& data) const { std::string file_name; if (dash_mode_) { file_name = directory_ + data.id; } else { file_name = directory_ + file_name_; } FILE* file = fopen(file_name.c_str(), "ab"); if (!file) { LOG(ERROR) << "Unable to open output file."; return false; } const size_t bytes_written = fwrite(reinterpret_cast<const void*>(&data.data[0]), 1, data.data.size(), file); fclose(file); return (bytes_written == data.data.size()); } // Runs until StopRequested() returns true. void FileWriter::WriterThread() { while (!StopRequested() || buffer_q_.GetNumBuffers() > 0) { const BufferQueue::Buffer* buffer = buffer_q_.DequeueBuffer(); if (!buffer) { // Wait for a buffer. WaitForUserData(); continue; } if (!WriteFile(*buffer)) { LOG(ERROR) << "Write failed for id: " << buffer->id; } } } } // namespace webmlive
// Copyright (c) 2015 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "encoder/file_writer.h" #include <condition_variable> #include <cstdio> #include <ctime> #include <functional> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "glog/logging.h" #include "encoder/time_util.h" namespace webmlive { bool FileWriter::Init(bool dash_mode, const std::string& directory) { if (!dash_mode) { file_name_ = LocalDateString() + LocalTimeString() + ".webm"; } directory_ = directory; return true; } bool FileWriter::Run() { using std::bind; using std::shared_ptr; using std::thread; using std::nothrow; thread_ = shared_ptr<thread>( new (nothrow) thread(bind(&FileWriter::WriterThread, // NOLINT this))); if (!thread_) { LOG(ERROR) << "Out of memory."; return false; } return true; } bool FileWriter::Stop() { // Tell WriterThread() to stop. mutex_.lock(); stop_ = true; mutex_.unlock(); // Wake and wait for WriterThread() to exit. wake_condition_.notify_one(); thread_->join(); return true; } // Copies data into |buffer_q_| and returns true. bool FileWriter::WriteData(DataSinkInterface::SharedDataSinkBuffer buffer) { // TODO(tomfinegan): Copying data is not necessary; SharedDataBufferQueue or // something should be provided by data_sink.h. Abusing BufferQueue // temporarily since it just works and incoming buffers aren't that large. if (!buffer_q_.EnqueueBuffer(buffer->id, &buffer->data[0], buffer->data.size())) { LOG(ERROR) << "Write buffer enqueue failed."; return false; } // Wake WriterThread(). LOG(INFO) << "waking WriterThread with " << buffer->data.size() << " bytes"; wake_condition_.notify_one(); return true; } // Try to obtain lock on |mutex_|, and return the value of |stop_| if lock is // obtained. Returns false if unable to obtain the lock. bool FileWriter::StopRequested() { bool stop_requested = false; std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock); if (lock.owns_lock()) { stop_requested = stop_; } return stop_requested; } // Idle the upload thread while awaiting user data. void FileWriter::WaitForUserData() { std::unique_lock<std::mutex> lock(mutex_); wake_condition_.wait(lock); // Unlock |mutex_| and idle the thread while we // wait for the next chunk of user data. } // Writes |data| contents to file and returns true upon success. bool FileWriter::WriteFile(const BufferQueue::Buffer& data) const { std::string file_name; if (dash_mode_) { file_name = directory_ + data.id; } else { file_name = directory_ + file_name_; } FILE* file = fopen(file_name.c_str(), "ab"); if (!file) { LOG(ERROR) << "Unable to open output file."; return false; } const size_t bytes_written = fwrite(reinterpret_cast<const void*>(&data.data[0]), 1, data.data.size(), file); fclose(file); return (bytes_written == data.data.size()); } // Runs until StopRequested() returns true. void FileWriter::WriterThread() { while (!StopRequested() || buffer_q_.GetNumBuffers() > 0) { const BufferQueue::Buffer* buffer = buffer_q_.DequeueBuffer(); if (!buffer) { // Wait for a buffer. WaitForUserData(); continue; } if (!WriteFile(*buffer)) { LOG(ERROR) << "Write failed for id: " << buffer->id; } } } } // namespace webmlive
Use time_util.
file_writer: Use time_util. Change-Id: Ia85efea5c01fb8f3811b72b895e53a2307ec1ac7
C++
bsd-3-clause
webmproject/webmlive,felipebetancur/webmlive,webmproject/webmlive,felipebetancur/webmlive,webmproject/webmlive,felipebetancur/webmlive,felipebetancur/webmlive,webmproject/webmlive,webmproject/webmlive,felipebetancur/webmlive
cacf9fc8199eff800a4ed2d55a13c377443b0ae2
gears/io/lines.hpp
gears/io/lines.hpp
// The MIT License (MIT) // Copyright (c) 2012-2014 Danny Y., Rapptz // 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. #ifndef GEARS_IO_LINES_HPP #define GEARS_IO_LINES_HPP #include <istream> #include <string> #include <iterator> namespace gears { namespace io { /** * @ingroup io * @brief Iterator that iterates through stdin lines. * @details An iterator that iterates through lines given by stdin such as * `std::cin`, `std::ifstream`, and `std::istringstream`. This iterator is basically * a wrapper around `std::getline` and `std::istream`. This should not be used directly. * * @tparam CharT Underlying character type of the string. * @tparam Traits Underlying `std::char_traits`-like of the string. */ template<typename CharT = char, typename Traits = std::char_traits<CharT>> struct line_iterator : std::iterator<std::input_iterator_tag, std::basic_string<CharT, Traits>> { private: std::basic_istream<CharT, Traits>* reader; std::basic_string<CharT, Traits> value; bool status; public: line_iterator() noexcept: reader(nullptr), status(false) {} line_iterator(std::basic_istream<CharT, Traits>& out) noexcept: reader(&out) { status = reader && *reader && std::getline(*reader, value); } auto operator++() noexcept -> decltype(*this) { status = reader && *reader && std::getline(*reader, value); return *this; } line_iterator operator++(int) noexcept { auto copy = *this; ++(*this); return copy; } auto operator*() noexcept -> decltype(value) { return value; } auto operator->() noexcept -> decltype(&value) { return &value; } bool operator==(const line_iterator& other) const noexcept { return (status == other.status) && (!status || reader == other.reader); } bool operator!=(const line_iterator& other) const noexcept { return not (*this == other); } }; /** * @ingroup io * @brief A range object that returns line_iterators. * @details A range object that returns line_iterators. This shouldn't be used * directly and instead should be used with `lines`. * * @tparam CharT Underlying character type. * @tparam Traits Underlying character traits type. */ template<typename CharT, typename Traits> struct line_reader { private: std::basic_istream<CharT, Traits>& in; public: line_reader(std::basic_istream<CharT, Traits>& in) noexcept: in(in) {} line_iterator<CharT, Traits> begin() noexcept { return { in }; } line_iterator<CharT, Traits> end() noexcept { return { }; } }; /** * @ingroup io * @brief Returns a range object to iterate through input lines. * @details Iterates through input lines. Best used with the range-based * for loop. * * @param in `std::istream` derived object to iterate through lines * @return `line_reader` object to iterate through. */ template<typename CharT, typename Traits> inline line_reader<CharT, Traits> lines(std::basic_istream<CharT, Traits>& in) { return line_reader<CharT, Traits>(in); } } // io } // gears #endif // GEARS_IO_LINES_HPP
// The MIT License (MIT) // Copyright (c) 2012-2014 Danny Y., Rapptz // 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. #ifndef GEARS_IO_LINES_HPP #define GEARS_IO_LINES_HPP #include <istream> #include <string> #include <iterator> namespace gears { namespace io { /** * @ingroup io * @brief Iterator that iterates through stdin lines. * @details An iterator that iterates through lines given by stdin such as * `std::cin`, `std::ifstream`, and `std::istringstream`. This iterator is basically * a wrapper around `std::getline` and `std::istream`. This should not be used directly. * * @tparam CharT Underlying character type of the string. * @tparam Traits Underlying `std::char_traits`-like of the string. */ template<typename CharT = char, typename Traits = std::char_traits<CharT>> struct line_iterator : std::iterator<std::input_iterator_tag, std::basic_string<CharT, Traits>> { private: std::basic_istream<CharT, Traits>* reader; std::basic_string<CharT, Traits> value; bool status; public: line_iterator() noexcept: reader(nullptr), status(false) {} line_iterator(std::basic_istream<CharT, Traits>& out) noexcept: reader(&out) { status = reader && *reader && std::getline(*reader, value); } auto operator++() noexcept -> decltype(*this) { status = reader && *reader && std::getline(*reader, value); return *this; } line_iterator operator++(int) noexcept { auto copy = *this; ++(*this); return copy; } auto operator*() noexcept -> decltype(value) { return value; } auto operator->() noexcept -> decltype(&value) { return &value; } bool operator==(const line_iterator& other) const noexcept { return (status == other.status) && (!status || reader == other.reader); } bool operator!=(const line_iterator& other) const noexcept { return not (*this == other); } }; /** * @ingroup io * @brief A range object that returns line_iterators. * @details A range object that returns line_iterators. This shouldn't be used * directly and instead should be used with `lines`. * * @tparam CharT Underlying character type. * @tparam Traits Underlying character traits type. */ template<typename CharT, typename Traits> struct line_reader { private: std::basic_istream<CharT, Traits>& in; public: line_reader(std::basic_istream<CharT, Traits>& in) noexcept: in(in) {} line_iterator<CharT, Traits> begin() noexcept { return { in }; } line_iterator<CharT, Traits> end() noexcept { return { }; } }; /** * @ingroup io * @brief Returns a range object to iterate through input lines. * @details Iterates through input lines. Best used with the range-based * for loop. * * Example: * @code * #include <gears/io/lines.hpp> * #include <iostream> * #include <fstream> * * namespace io = gears::io; * * int main() { * std::ifstream in("test.txt"); // could be any file * for(auto&& line : io::lines(in)) { * std::cout << line << '\n'; * } * } * @endcode * * @param in `std::istream` derived object to iterate through lines * @return `line_reader` object to iterate through. */ template<typename CharT, typename Traits> inline line_reader<CharT, Traits> lines(std::basic_istream<CharT, Traits>& in) { return line_reader<CharT, Traits>(in); } } // io } // gears #endif // GEARS_IO_LINES_HPP
Add example for gears::io::lines
Add example for gears::io::lines
C++
mit
Rapptz/Gears,Rapptz/Gears
93e57fa31b08f850197009c58ab362f5fe97de3d
aws-cpp-sdk-cognitoidentity-integration-tests/IdentityPoolOperationTest.cpp
aws-cpp-sdk-cognitoidentity-integration-tests/IdentityPoolOperationTest.cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h> #include <aws/testing/MemoryTesting.h> #include <aws/cognito-identity/CognitoIdentityClient.h> #include <aws/cognito-identity/CognitoIdentityErrors.h> #include <aws/cognito-identity/model/CreateIdentityPoolRequest.h> #include <aws/cognito-identity/model/DeleteIdentityPoolRequest.h> #include <aws/cognito-identity/model/DescribeIdentityPoolRequest.h> #include <aws/cognito-identity/model/GetIdentityPoolRolesRequest.h> #include <aws/cognito-identity/model/UpdateIdentityPoolRequest.h> #include <aws/cognito-identity/model/ListIdentityPoolsRequest.h> #include <aws/cognito-identity/model/GetCredentialsForIdentityRequest.h> #include <aws/cognito-identity/model/GetIdRequest.h> #include <aws/cognito-identity/model/ListIdentitiesRequest.h> #include <aws/cognito-identity/model/GetOpenIdTokenRequest.h> #include <aws/cognito-identity/model/UnlinkIdentityRequest.h> #include <aws/cognito-identity/model/GetOpenIdTokenForDeveloperIdentityRequest.h> #include <aws/cognito-identity/model/LookupDeveloperIdentityRequest.h> #include <aws/cognito-identity/CognitoIdentityErrors.h> #include <aws/access-management/AccessManagementClient.h> #include <aws/iam/IAMClient.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/Outcome.h> #include <aws/testing/TestingEnvironment.h> using namespace Aws::CognitoIdentity; using namespace Aws::CognitoIdentity::Model; using namespace Aws::Client; #define TEST_POOL_PREFIX "IntegrationTest_" namespace { static const char* ALLOCATION_TAG = "IdentityPoolOperationTest"; Aws::String GetResourcePrefix() { return Aws::Testing::GetAwsResourcePrefix() + TEST_POOL_PREFIX; } class IdentityPoolOperationTest : public ::testing::Test { public: IdentityPoolOperationTest() : client(nullptr) {} std::shared_ptr<CognitoIdentityClient> client; protected: void SetUp() { //TODO: move this over to profile config file. client = Aws::MakeShared<CognitoIdentityClient>(ALLOCATION_TAG); CleanupPreviousFailedTests(); } void TearDown() { client = nullptr; } static bool WaitForIdentitiesToBeActive(const Aws::String& identityPoolId, const std::shared_ptr<CognitoIdentityClient>& client) { unsigned timeoutCount = 0; const unsigned maxRetries = 10; while (timeoutCount++ < maxRetries) { GetIdentityPoolRolesRequest getIdentityPoolRolesRequest; getIdentityPoolRolesRequest.SetIdentityPoolId(identityPoolId); GetIdentityPoolRolesOutcome getIdentityPoolRolesOutcome = client->GetIdentityPoolRoles(getIdentityPoolRolesRequest); if (getIdentityPoolRolesOutcome.IsSuccess()) { return true; } std::this_thread::sleep_for(std::chrono::seconds(1)); } return false; } void CleanupPreviousFailedTests() { Aws::String resourcePrefix = GetResourcePrefix(); size_t prefixLength = resourcePrefix.length(); Aws::Vector<IdentityPoolShortDescription> pools = GetAllPools(); for (auto& pool : pools) { // Only delete integration test pools if (pool.GetIdentityPoolName().compare(0, prefixLength, resourcePrefix) == 0) { DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(pool.GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); ASSERT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); } } } const Aws::Vector<IdentityPoolShortDescription> GetAllPools() { ListIdentityPoolsRequest request; request.WithMaxResults(50); ListIdentityPoolsOutcome outcome = client->ListIdentityPools(request); if (!outcome.IsSuccess()) { std::cout << "Encountered Unexpected Error:" << outcome.GetError().GetExceptionName() << std::endl; } return outcome.GetResult().GetIdentityPools(); } }; TEST_F(IdentityPoolOperationTest, TestCreateGetUpdateDeleteOperations) { std::size_t initialPoolCount = GetAllPools().size(); Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "BatCave"; CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("BruceWayne") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); ASSERT_FALSE(createIdentityPoolOutcome.GetResult().GetIdentityPoolId().empty()); EXPECT_EQ(createIdentityPoolRequest.GetIdentityPoolName(), createIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(createIdentityPoolOutcome.GetResult().GetAllowUnauthenticatedIdentities()); EXPECT_EQ(createIdentityPoolRequest.GetDeveloperProviderName(), createIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(createIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, createIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); Aws::String identityPoolId = createIdentityPoolOutcome.GetResult().GetIdentityPoolId(); EXPECT_TRUE(WaitForIdentitiesToBeActive(identityPoolId, client)); DescribeIdentityPoolRequest describeIdentityPoolRequest; describeIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DescribeIdentityPoolOutcome describeIdentityPoolOutcome = client->DescribeIdentityPool(describeIdentityPoolRequest); EXPECT_TRUE(describeIdentityPoolOutcome.IsSuccess()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), describeIdentityPoolOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(createIdentityPoolRequest.GetIdentityPoolName(), describeIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(describeIdentityPoolOutcome.GetResult().GetAllowUnauthenticatedIdentities()); EXPECT_EQ(createIdentityPoolRequest.GetDeveloperProviderName(), describeIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(createIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, describeIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); Aws::Vector<IdentityPoolShortDescription> pools = GetAllPools(); ASSERT_EQ(initialPoolCount + 1, GetAllPools().size()); UpdateIdentityPoolRequest updateIdentityPoolRequest; updateIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()) .WithIdentityPoolName(identityPoolName + "20") .WithAllowUnauthenticatedIdentities(true) .WithDeveloperProviderName("BruceWayne") .WithSupportedLoginProviders(createIdentityPoolRequest.GetSupportedLoginProviders()); UpdateIdentityPoolOutcome updateIdentityPoolOutcome = client->UpdateIdentityPool(updateIdentityPoolRequest); EXPECT_TRUE(updateIdentityPoolOutcome.IsSuccess()); EXPECT_EQ(updateIdentityPoolRequest.GetIdentityPoolId(), updateIdentityPoolOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(updateIdentityPoolRequest.GetIdentityPoolName(), updateIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(updateIdentityPoolRequest.GetAllowUnauthenticatedIdentities()); EXPECT_EQ(updateIdentityPoolRequest.GetDeveloperProviderName(), updateIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(updateIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, updateIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); ASSERT_EQ(initialPoolCount, GetAllPools().size()); } TEST_F(IdentityPoolOperationTest, TestExceptionProperlyPropgates) { Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "Bat Cave"; CreateIdentityPoolRequest createIdentityPoolRequest; //spaces should return a Validation Error createIdentityPoolRequest.WithDeveloperProviderName("Bruce Wayne") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_FALSE(createIdentityPoolOutcome.IsSuccess()); ASSERT_EQ(CognitoIdentityErrors::VALIDATION, createIdentityPoolOutcome.GetError().GetErrorType()); } TEST_F(IdentityPoolOperationTest, TestIdentityActions) { Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "FortressOfSolitude"; CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("Superman") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); Aws::String identityPoolId = createIdentityPoolOutcome.GetResult().GetIdentityPoolId(); GetIdRequest getIdRequest; getIdRequest.WithIdentityPoolId(identityPoolId); ClientConfiguration clientConfig; auto iamClient = Aws::MakeShared<Aws::IAM::IAMClient>(ALLOCATION_TAG, clientConfig); Aws::AccessManagement::AccessManagementClient accessManagementClient(iamClient, client); getIdRequest.WithAccountId(accessManagementClient.GetAccountId()); GetIdOutcome getIdOutcome = client->GetId(getIdRequest); EXPECT_TRUE(getIdOutcome.IsSuccess()); EXPECT_FALSE(getIdOutcome.GetResult().GetIdentityId().empty()); // No Roles, so expect this to fail GetCredentialsForIdentityRequest getCredentialsRequest; getCredentialsRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()); GetCredentialsForIdentityOutcome getCredentialsOutcome = client->GetCredentialsForIdentity(getCredentialsRequest); EXPECT_FALSE(getCredentialsOutcome.IsSuccess()); EXPECT_EQ(CognitoIdentityErrors::INVALID_IDENTITY_POOL_CONFIGURATION, getCredentialsOutcome.GetError().GetErrorType()); EXPECT_TRUE(WaitForIdentitiesToBeActive(identityPoolId, client)); ListIdentitiesRequest listIdentitiesRequest; listIdentitiesRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()).WithMaxResults(10); ListIdentitiesOutcome listIdentitiesOutcome = client->ListIdentities(listIdentitiesRequest); EXPECT_TRUE(listIdentitiesOutcome.IsSuccess()); EXPECT_EQ(1u, listIdentitiesOutcome.GetResult().GetIdentities().size()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), listIdentitiesOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), listIdentitiesOutcome.GetResult().GetIdentities()[0].GetIdentityId()); GetOpenIdTokenRequest getOpenIdTokenRequest; getOpenIdTokenRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()); GetOpenIdTokenOutcome getOpenIdTokenOutcome = client->GetOpenIdToken(getOpenIdTokenRequest); EXPECT_TRUE(getOpenIdTokenOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), getOpenIdTokenOutcome.GetResult().GetIdentityId()); EXPECT_FALSE(getOpenIdTokenOutcome.GetResult().GetToken().empty()); /**We need a real open id provider for this to work UnlinkIdentityRequest unlinkIdentityRequest; unlinkIdentityRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()) .WithLogins(createIdentityPoolRequest.GetSupportedLoginProviders()) .AddLoginToRemove("www.amazon.com"); UnlinkIdentityOutcome unlinkIdentityOutcome = client->UnlinkIdentity(unlinkIdentityRequest); EXPECT_TRUE(unlinkIdentityOutcome.IsSuccess()); listIdentitiesOutcome = client->ListIdentities(listIdentitiesRequest); EXPECT_TRUE(listIdentitiesOutcome.IsSuccess()); EXPECT_EQ(0u, listIdentitiesOutcome.GetResult().GetIdentities().size()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), listIdentitiesOutcome.GetResult().GetIdentityPoolId());*/ DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); } /***This Test will not work until we have a live openId provider to link against. TEST_F(IdentityPoolOperationTest, TestDeveloperIdentityActions) { CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("Spiderman") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(TEST_POOL_PREFIX "NYC") .AddSupportedLoginProvider("www.pointstoknowhere.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); GetIdRequest getIdRequest; getIdRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); getIdRequest.WithAccountId("868711054045"); GetIdOutcome getIdOutcome = client->GetId(getIdRequest); EXPECT_TRUE(getIdOutcome.IsSuccess()); EXPECT_FALSE(getIdOutcome.GetResult().GetIdentityId().empty()); GetOpenIdTokenForDeveloperIdentityRequest getOpenIdTokenForDeveloperIdentityRequest; getOpenIdTokenForDeveloperIdentityRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()) .AddLogin("www.pointstoknowhere.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d") .WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); GetOpenIdTokenForDeveloperIdentityOutcome getOpenIdTokenForDeveloperIdentityOutcome = client->GetOpenIdTokenForDeveloperIdentity(getOpenIdTokenForDeveloperIdentityRequest); EXPECT_TRUE(getOpenIdTokenForDeveloperIdentityOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId()); EXPECT_FALSE(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetToken().empty()); LookupDeveloperIdentityRequest lookupDeveloperIdentityRequest; lookupDeveloperIdentityRequest.WithIdentityId(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId()) .WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); LookupDeveloperIdentityOutcome lookupDeveloperIdentityOutcome = client->LookupDeveloperIdentity(lookupDeveloperIdentityRequest); EXPECT_TRUE(lookupDeveloperIdentityOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), lookupDeveloperIdentityOutcome.GetResult().GetIdentityId()); //EXPECT_EQ(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId(), // lookupDeveloperIdentityOutcome.GetResult().GetDeveloperUserIdentifierList()[0]); DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); }*/ }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h> #include <aws/testing/MemoryTesting.h> #include <algorithm> #include <aws/cognito-identity/CognitoIdentityClient.h> #include <aws/cognito-identity/CognitoIdentityErrors.h> #include <aws/cognito-identity/model/CreateIdentityPoolRequest.h> #include <aws/cognito-identity/model/DeleteIdentityPoolRequest.h> #include <aws/cognito-identity/model/DescribeIdentityPoolRequest.h> #include <aws/cognito-identity/model/GetIdentityPoolRolesRequest.h> #include <aws/cognito-identity/model/UpdateIdentityPoolRequest.h> #include <aws/cognito-identity/model/ListIdentityPoolsRequest.h> #include <aws/cognito-identity/model/GetCredentialsForIdentityRequest.h> #include <aws/cognito-identity/model/GetIdRequest.h> #include <aws/cognito-identity/model/ListIdentitiesRequest.h> #include <aws/cognito-identity/model/GetOpenIdTokenRequest.h> #include <aws/cognito-identity/model/UnlinkIdentityRequest.h> #include <aws/cognito-identity/model/GetOpenIdTokenForDeveloperIdentityRequest.h> #include <aws/cognito-identity/model/LookupDeveloperIdentityRequest.h> #include <aws/cognito-identity/CognitoIdentityErrors.h> #include <aws/access-management/AccessManagementClient.h> #include <aws/iam/IAMClient.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/Outcome.h> #include <aws/testing/TestingEnvironment.h> using namespace Aws::CognitoIdentity; using namespace Aws::CognitoIdentity::Model; using namespace Aws::Client; #define TEST_POOL_PREFIX "IntegrationTest_" namespace { static const char* ALLOCATION_TAG = "IdentityPoolOperationTest"; Aws::String GetResourcePrefix() { return Aws::Testing::GetAwsResourcePrefix() + TEST_POOL_PREFIX; } class IdentityPoolOperationTest : public ::testing::Test { public: IdentityPoolOperationTest() : client(nullptr) {} std::shared_ptr<CognitoIdentityClient> client; protected: void SetUp() { //TODO: move this over to profile config file. client = Aws::MakeShared<CognitoIdentityClient>(ALLOCATION_TAG); CleanupPreviousFailedTests(); } void TearDown() { client = nullptr; } static bool WaitForIdentitiesToBeActive(const Aws::String& identityPoolId, const std::shared_ptr<CognitoIdentityClient>& client) { unsigned timeoutCount = 0; const unsigned maxRetries = 10; while (timeoutCount++ < maxRetries) { GetIdentityPoolRolesRequest getIdentityPoolRolesRequest; getIdentityPoolRolesRequest.SetIdentityPoolId(identityPoolId); GetIdentityPoolRolesOutcome getIdentityPoolRolesOutcome = client->GetIdentityPoolRoles(getIdentityPoolRolesRequest); if (getIdentityPoolRolesOutcome.IsSuccess()) { return true; } std::this_thread::sleep_for(std::chrono::seconds(1)); } return false; } void CleanupPreviousFailedTests() { Aws::String resourcePrefix = GetResourcePrefix(); Aws::Vector<IdentityPoolShortDescription> pools = GetAllPoolsWithPrefix(resourcePrefix); for (auto& pool : pools) { // Only delete integration test pools DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(pool.GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); ASSERT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); } } const Aws::Vector<IdentityPoolShortDescription> GetAllPoolsWithPrefix(Aws::String prefix) { ListIdentityPoolsRequest request; request.WithMaxResults(50); ListIdentityPoolsOutcome outcome = client->ListIdentityPools(request); if (!outcome.IsSuccess()) { std::cout << "Encountered Unexpected Error:" << outcome.GetError().GetExceptionName() << std::endl; } EXPECT_TRUE(outcome.IsSuccess()); auto& identityPools = outcome.GetResult().GetIdentityPools(); Aws::Vector<IdentityPoolShortDescription> pools; std::copy_if(identityPools.begin(), identityPools.end(), std::back_inserter(pools), [&](const IdentityPoolShortDescription& pool) { return pool.GetIdentityPoolName().find(prefix) == 0; }); return pools; } }; TEST_F(IdentityPoolOperationTest, TestCreateGetUpdateDeleteOperations) { std::size_t initialPoolCount = GetAllPoolsWithPrefix(GetResourcePrefix()).size(); Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "BatCave"; CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("BruceWayne") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); ASSERT_FALSE(createIdentityPoolOutcome.GetResult().GetIdentityPoolId().empty()); EXPECT_EQ(createIdentityPoolRequest.GetIdentityPoolName(), createIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(createIdentityPoolOutcome.GetResult().GetAllowUnauthenticatedIdentities()); EXPECT_EQ(createIdentityPoolRequest.GetDeveloperProviderName(), createIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(createIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, createIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); Aws::String identityPoolId = createIdentityPoolOutcome.GetResult().GetIdentityPoolId(); EXPECT_TRUE(WaitForIdentitiesToBeActive(identityPoolId, client)); DescribeIdentityPoolRequest describeIdentityPoolRequest; describeIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DescribeIdentityPoolOutcome describeIdentityPoolOutcome = client->DescribeIdentityPool(describeIdentityPoolRequest); EXPECT_TRUE(describeIdentityPoolOutcome.IsSuccess()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), describeIdentityPoolOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(createIdentityPoolRequest.GetIdentityPoolName(), describeIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(describeIdentityPoolOutcome.GetResult().GetAllowUnauthenticatedIdentities()); EXPECT_EQ(createIdentityPoolRequest.GetDeveloperProviderName(), describeIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(createIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, describeIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); ASSERT_EQ(initialPoolCount + 1, GetAllPoolsWithPrefix(GetResourcePrefix()).size()); UpdateIdentityPoolRequest updateIdentityPoolRequest; updateIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()) .WithIdentityPoolName(identityPoolName + "20") .WithAllowUnauthenticatedIdentities(true) .WithDeveloperProviderName("BruceWayne") .WithSupportedLoginProviders(createIdentityPoolRequest.GetSupportedLoginProviders()); UpdateIdentityPoolOutcome updateIdentityPoolOutcome = client->UpdateIdentityPool(updateIdentityPoolRequest); EXPECT_TRUE(updateIdentityPoolOutcome.IsSuccess()); EXPECT_EQ(updateIdentityPoolRequest.GetIdentityPoolId(), updateIdentityPoolOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(updateIdentityPoolRequest.GetIdentityPoolName(), updateIdentityPoolOutcome.GetResult().GetIdentityPoolName()); EXPECT_TRUE(updateIdentityPoolRequest.GetAllowUnauthenticatedIdentities()); EXPECT_EQ(updateIdentityPoolRequest.GetDeveloperProviderName(), updateIdentityPoolOutcome.GetResult().GetDeveloperProviderName()); EXPECT_EQ(updateIdentityPoolRequest.GetSupportedLoginProviders().find("www.amazon.com")->second, updateIdentityPoolOutcome.GetResult().GetSupportedLoginProviders().find("www.amazon.com")->second); DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); ASSERT_EQ(initialPoolCount, GetAllPoolsWithPrefix(GetResourcePrefix()).size()); } TEST_F(IdentityPoolOperationTest, TestExceptionProperlyPropgates) { Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "Bat Cave"; CreateIdentityPoolRequest createIdentityPoolRequest; //spaces should return a Validation Error createIdentityPoolRequest.WithDeveloperProviderName("Bruce Wayne") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_FALSE(createIdentityPoolOutcome.IsSuccess()); ASSERT_EQ(CognitoIdentityErrors::VALIDATION, createIdentityPoolOutcome.GetError().GetErrorType()); } TEST_F(IdentityPoolOperationTest, TestIdentityActions) { Aws::String identityPoolName = GetResourcePrefix(); identityPoolName += "FortressOfSolitude"; CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("Superman") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(identityPoolName) .AddSupportedLoginProviders("www.amazon.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); Aws::String identityPoolId = createIdentityPoolOutcome.GetResult().GetIdentityPoolId(); GetIdRequest getIdRequest; getIdRequest.WithIdentityPoolId(identityPoolId); ClientConfiguration clientConfig; auto iamClient = Aws::MakeShared<Aws::IAM::IAMClient>(ALLOCATION_TAG, clientConfig); Aws::AccessManagement::AccessManagementClient accessManagementClient(iamClient, client); getIdRequest.WithAccountId(accessManagementClient.GetAccountId()); GetIdOutcome getIdOutcome = client->GetId(getIdRequest); EXPECT_TRUE(getIdOutcome.IsSuccess()); EXPECT_FALSE(getIdOutcome.GetResult().GetIdentityId().empty()); // No Roles, so expect this to fail GetCredentialsForIdentityRequest getCredentialsRequest; getCredentialsRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()); GetCredentialsForIdentityOutcome getCredentialsOutcome = client->GetCredentialsForIdentity(getCredentialsRequest); EXPECT_FALSE(getCredentialsOutcome.IsSuccess()); EXPECT_EQ(CognitoIdentityErrors::INVALID_IDENTITY_POOL_CONFIGURATION, getCredentialsOutcome.GetError().GetErrorType()); EXPECT_TRUE(WaitForIdentitiesToBeActive(identityPoolId, client)); ListIdentitiesRequest listIdentitiesRequest; listIdentitiesRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()).WithMaxResults(10); ListIdentitiesOutcome listIdentitiesOutcome = client->ListIdentities(listIdentitiesRequest); EXPECT_TRUE(listIdentitiesOutcome.IsSuccess()); EXPECT_EQ(1u, listIdentitiesOutcome.GetResult().GetIdentities().size()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), listIdentitiesOutcome.GetResult().GetIdentityPoolId()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), listIdentitiesOutcome.GetResult().GetIdentities()[0].GetIdentityId()); GetOpenIdTokenRequest getOpenIdTokenRequest; getOpenIdTokenRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()); GetOpenIdTokenOutcome getOpenIdTokenOutcome = client->GetOpenIdToken(getOpenIdTokenRequest); EXPECT_TRUE(getOpenIdTokenOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), getOpenIdTokenOutcome.GetResult().GetIdentityId()); EXPECT_FALSE(getOpenIdTokenOutcome.GetResult().GetToken().empty()); /**We need a real open id provider for this to work UnlinkIdentityRequest unlinkIdentityRequest; unlinkIdentityRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()) .WithLogins(createIdentityPoolRequest.GetSupportedLoginProviders()) .AddLoginToRemove("www.amazon.com"); UnlinkIdentityOutcome unlinkIdentityOutcome = client->UnlinkIdentity(unlinkIdentityRequest); EXPECT_TRUE(unlinkIdentityOutcome.IsSuccess()); listIdentitiesOutcome = client->ListIdentities(listIdentitiesRequest); EXPECT_TRUE(listIdentitiesOutcome.IsSuccess()); EXPECT_EQ(0u, listIdentitiesOutcome.GetResult().GetIdentities().size()); EXPECT_EQ(createIdentityPoolOutcome.GetResult().GetIdentityPoolId(), listIdentitiesOutcome.GetResult().GetIdentityPoolId());*/ DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); } /***This Test will not work until we have a live openId provider to link against. TEST_F(IdentityPoolOperationTest, TestDeveloperIdentityActions) { CreateIdentityPoolRequest createIdentityPoolRequest; createIdentityPoolRequest.WithDeveloperProviderName("Spiderman") .WithAllowUnauthenticatedIdentities(true) .WithIdentityPoolName(TEST_POOL_PREFIX "NYC") .AddSupportedLoginProvider("www.pointstoknowhere.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d"); CreateIdentityPoolOutcome createIdentityPoolOutcome = client->CreateIdentityPool(createIdentityPoolRequest); ASSERT_TRUE(createIdentityPoolOutcome.IsSuccess()); GetIdRequest getIdRequest; getIdRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); getIdRequest.WithAccountId("868711054045"); GetIdOutcome getIdOutcome = client->GetId(getIdRequest); EXPECT_TRUE(getIdOutcome.IsSuccess()); EXPECT_FALSE(getIdOutcome.GetResult().GetIdentityId().empty()); GetOpenIdTokenForDeveloperIdentityRequest getOpenIdTokenForDeveloperIdentityRequest; getOpenIdTokenForDeveloperIdentityRequest.WithIdentityId(getIdOutcome.GetResult().GetIdentityId()) .AddLogin("www.pointstoknowhere.com", "amzn1.application-oa2-client.188a56d827a7d6555a8b67a5d") .WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); GetOpenIdTokenForDeveloperIdentityOutcome getOpenIdTokenForDeveloperIdentityOutcome = client->GetOpenIdTokenForDeveloperIdentity(getOpenIdTokenForDeveloperIdentityRequest); EXPECT_TRUE(getOpenIdTokenForDeveloperIdentityOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId()); EXPECT_FALSE(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetToken().empty()); LookupDeveloperIdentityRequest lookupDeveloperIdentityRequest; lookupDeveloperIdentityRequest.WithIdentityId(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId()) .WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); LookupDeveloperIdentityOutcome lookupDeveloperIdentityOutcome = client->LookupDeveloperIdentity(lookupDeveloperIdentityRequest); EXPECT_TRUE(lookupDeveloperIdentityOutcome.IsSuccess()); EXPECT_EQ(getIdOutcome.GetResult().GetIdentityId(), lookupDeveloperIdentityOutcome.GetResult().GetIdentityId()); //EXPECT_EQ(getOpenIdTokenForDeveloperIdentityOutcome.GetResult().GetIdentityId(), // lookupDeveloperIdentityOutcome.GetResult().GetDeveloperUserIdentifierList()[0]); DeleteIdentityPoolRequest deleteIdentityPoolRequest; deleteIdentityPoolRequest.WithIdentityPoolId(createIdentityPoolOutcome.GetResult().GetIdentityPoolId()); DeleteIdentityPoolOutcome deleteIdentityPoolOutcome = client->DeleteIdentityPool(deleteIdentityPoolRequest); EXPECT_TRUE(deleteIdentityPoolOutcome.IsSuccess()); }*/ }
Solve cross platform race condition in IdentityPoolOperationTest (#245)
Solve cross platform race condition in IdentityPoolOperationTest (#245)
C++
apache-2.0
JoyIfBam5/aws-sdk-cpp,aws/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,jt70471/aws-sdk-cpp,awslabs/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,aws/aws-sdk-cpp,aws/aws-sdk-cpp,aws/aws-sdk-cpp,cedral/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,cedral/aws-sdk-cpp,cedral/aws-sdk-cpp,cedral/aws-sdk-cpp,aws/aws-sdk-cpp,jt70471/aws-sdk-cpp,cedral/aws-sdk-cpp,jt70471/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,awslabs/aws-sdk-cpp,aws/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,jt70471/aws-sdk-cpp,jt70471/aws-sdk-cpp,awslabs/aws-sdk-cpp,cedral/aws-sdk-cpp,jt70471/aws-sdk-cpp,awslabs/aws-sdk-cpp
bf90e033f4fe86cfb90492c7e0962278ea3a146d
src/wallet/sqlite.cpp
src/wallet/sqlite.cpp
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/sqlite.h> #include <logging.h> #include <sync.h> #include <util/memory.h> #include <util/strencodings.h> #include <util/system.h> #include <util/translation.h> #include <wallet/db.h> #include <sqlite3.h> #include <stdint.h> static const char* const DATABASE_FILENAME = "wallet.dat"; static Mutex g_sqlite_mutex; static int g_sqlite_count GUARDED_BY(g_sqlite_mutex) = 0; static void ErrorLogCallback(void* arg, int code, const char* msg) { // From sqlite3_config() documentation for the SQLITE_CONFIG_LOG option: // "The void pointer that is the second argument to SQLITE_CONFIG_LOG is passed through as // the first parameter to the application-defined logger function whenever that function is // invoked." // Assert that this is the case: assert(arg == nullptr); LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg); } SQLiteDatabase::SQLiteDatabase(const fs::path& dir_path, const fs::path& file_path, bool mock) : WalletDatabase(), m_mock(mock), m_dir_path(dir_path.string()), m_file_path(file_path.string()) { { LOCK(g_sqlite_mutex); LogPrintf("Using SQLite Version %s\n", SQLiteDatabaseVersion()); LogPrintf("Using wallet %s\n", m_dir_path); if (++g_sqlite_count == 1) { // Setup logging int ret = sqlite3_config(SQLITE_CONFIG_LOG, ErrorLogCallback, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup error log: %s\n", sqlite3_errstr(ret))); } } int ret = sqlite3_initialize(); // This is a no-op if sqlite3 is already initialized if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to initialize SQLite: %s\n", sqlite3_errstr(ret))); } } try { Open(); } catch (const std::runtime_error&) { // If open fails, cleanup this object and rethrow the exception Cleanup(); throw; } } void SQLiteBatch::SetupSQLStatements() { int res; if (!m_read_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "SELECT value FROM main WHERE key = ?", -1, &m_read_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_insert_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "INSERT INTO main VALUES(?, ?)", -1, &m_insert_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_overwrite_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "INSERT or REPLACE into main values(?, ?)", -1, &m_overwrite_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_delete_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "DELETE FROM main WHERE key = ?", -1, &m_delete_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_cursor_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "SELECT key, value FROM main", -1, &m_cursor_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements : %s\n", sqlite3_errstr(res))); } } } SQLiteDatabase::~SQLiteDatabase() { Cleanup(); } void SQLiteDatabase::Cleanup() noexcept { Close(); LOCK(g_sqlite_mutex); if (--g_sqlite_count == 0) { int ret = sqlite3_shutdown(); if (ret != SQLITE_OK) { LogPrintf("SQLiteDatabase: Failed to shutdown SQLite: %s\n", sqlite3_errstr(ret)); } } } void SQLiteDatabase::Open() { int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; if (m_mock) { flags |= SQLITE_OPEN_MEMORY; // In memory database for mock db } if (m_db == nullptr) { TryCreateDirectories(m_dir_path); int ret = sqlite3_open_v2(m_file_path.c_str(), &m_db, flags, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(ret))); } } if (sqlite3_db_readonly(m_db, "main") != 0) { throw std::runtime_error("SQLiteDatabase: Database opened in readonly mode but read-write permissions are needed"); } // Acquire an exclusive lock on the database // First change the locking mode to exclusive int ret = sqlite3_exec(m_db, "PRAGMA locking_mode = exclusive", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Unable to change database locking mode to exclusive: %s\n", sqlite3_errstr(ret))); } // Now begin a transaction to acquire the exclusive lock. This lock won't be released until we close because of the exclusive locking mode. ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error("SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another bitcoind?\n"); } ret = sqlite3_exec(m_db, "COMMIT", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Unable to end exclusive lock transaction: %s\n", sqlite3_errstr(ret))); } // Enable fullfsync for the platforms that use it ret = sqlite3_exec(m_db, "PRAGMA fullfsync = true", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable fullfsync: %s\n", sqlite3_errstr(ret))); } // Make the table for our key-value pairs // First check that the main table exists sqlite3_stmt* check_main_stmt{nullptr}; ret = sqlite3_prepare_v2(m_db, "SELECT name FROM sqlite_master WHERE type='table' AND name='main'", -1, &check_main_stmt, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to prepare statement to check table existence: %s\n", sqlite3_errstr(ret))); } ret = sqlite3_step(check_main_stmt); if (sqlite3_finalize(check_main_stmt) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to finalize statement checking table existence: %s\n", sqlite3_errstr(ret))); } bool table_exists; if (ret == SQLITE_DONE) { table_exists = false; } else if (ret == SQLITE_ROW) { table_exists = true; } else { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to execute statement to check table existence: %s\n", sqlite3_errstr(ret))); } // Do the db setup things because the table doesn't exist only when we are creating a new wallet if (!table_exists) { ret = sqlite3_exec(m_db, "CREATE TABLE main(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to create new database: %s\n", sqlite3_errstr(ret))); } } } bool SQLiteDatabase::Rewrite(const char* skip) { return false; } bool SQLiteDatabase::Backup(const std::string& dest) const { return false; } void SQLiteDatabase::Close() { int res = sqlite3_close(m_db); if (res != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to close database: %s\n", sqlite3_errstr(res))); } m_db = nullptr; } std::unique_ptr<DatabaseBatch> SQLiteDatabase::MakeBatch(bool flush_on_close) { return nullptr; } SQLiteBatch::SQLiteBatch(SQLiteDatabase& database) : m_database(database) { // Make sure we have a db handle assert(m_database.m_db); SetupSQLStatements(); } void SQLiteBatch::Close() { // If m_db is in a transaction (i.e. not in autocommit mode), then abort the transaction in progress if (m_database.m_db && sqlite3_get_autocommit(m_database.m_db) == 0) { if (TxnAbort()) { LogPrintf("SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted\n"); } else { LogPrintf("SQLiteBatch: Batch closed and failed to abort transaction\n"); } } // Free all of the prepared statements int ret = sqlite3_finalize(m_read_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize read statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_insert_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize insert statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_overwrite_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize overwrite statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_delete_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize delete statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_cursor_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize cursor statement: %s\n", sqlite3_errstr(ret)); } m_read_stmt = nullptr; m_insert_stmt = nullptr; m_overwrite_stmt = nullptr; m_delete_stmt = nullptr; m_cursor_stmt = nullptr; } bool SQLiteBatch::ReadKey(CDataStream&& key, CDataStream& value) { return false; } bool SQLiteBatch::WriteKey(CDataStream&& key, CDataStream&& value, bool overwrite) { return false; } bool SQLiteBatch::EraseKey(CDataStream&& key) { return false; } bool SQLiteBatch::HasKey(CDataStream&& key) { return false; } bool SQLiteBatch::StartCursor() { return false; } bool SQLiteBatch::ReadAtCursor(CDataStream& key, CDataStream& value, bool& complete) { return false; } void SQLiteBatch::CloseCursor() { } bool SQLiteBatch::TxnBegin() { return false; } bool SQLiteBatch::TxnCommit() { return false; } bool SQLiteBatch::TxnAbort() { return false; } bool ExistsSQLiteDatabase(const fs::path& path) { return false; } std::unique_ptr<SQLiteDatabase> MakeSQLiteDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error) { return MakeUnique<SQLiteDatabase>(path, path / DATABASE_FILENAME); } std::string SQLiteDatabaseVersion() { return std::string(sqlite3_libversion()); }
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/sqlite.h> #include <logging.h> #include <sync.h> #include <util/memory.h> #include <util/strencodings.h> #include <util/system.h> #include <util/translation.h> #include <wallet/db.h> #include <sqlite3.h> #include <stdint.h> static const char* const DATABASE_FILENAME = "wallet.dat"; static Mutex g_sqlite_mutex; static int g_sqlite_count GUARDED_BY(g_sqlite_mutex) = 0; static void ErrorLogCallback(void* arg, int code, const char* msg) { // From sqlite3_config() documentation for the SQLITE_CONFIG_LOG option: // "The void pointer that is the second argument to SQLITE_CONFIG_LOG is passed through as // the first parameter to the application-defined logger function whenever that function is // invoked." // Assert that this is the case: assert(arg == nullptr); LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg); } SQLiteDatabase::SQLiteDatabase(const fs::path& dir_path, const fs::path& file_path, bool mock) : WalletDatabase(), m_mock(mock), m_dir_path(dir_path.string()), m_file_path(file_path.string()) { { LOCK(g_sqlite_mutex); LogPrintf("Using SQLite Version %s\n", SQLiteDatabaseVersion()); LogPrintf("Using wallet %s\n", m_dir_path); if (++g_sqlite_count == 1) { // Setup logging int ret = sqlite3_config(SQLITE_CONFIG_LOG, ErrorLogCallback, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup error log: %s\n", sqlite3_errstr(ret))); } } int ret = sqlite3_initialize(); // This is a no-op if sqlite3 is already initialized if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to initialize SQLite: %s\n", sqlite3_errstr(ret))); } } try { Open(); } catch (const std::runtime_error&) { // If open fails, cleanup this object and rethrow the exception Cleanup(); throw; } } void SQLiteBatch::SetupSQLStatements() { int res; if (!m_read_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "SELECT value FROM main WHERE key = ?", -1, &m_read_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_insert_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "INSERT INTO main VALUES(?, ?)", -1, &m_insert_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_overwrite_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "INSERT or REPLACE into main values(?, ?)", -1, &m_overwrite_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_delete_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "DELETE FROM main WHERE key = ?", -1, &m_delete_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements: %s\n", sqlite3_errstr(res))); } } if (!m_cursor_stmt) { if ((res = sqlite3_prepare_v2(m_database.m_db, "SELECT key, value FROM main", -1, &m_cursor_stmt, nullptr)) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to setup SQL statements : %s\n", sqlite3_errstr(res))); } } } SQLiteDatabase::~SQLiteDatabase() { Cleanup(); } void SQLiteDatabase::Cleanup() noexcept { Close(); LOCK(g_sqlite_mutex); if (--g_sqlite_count == 0) { int ret = sqlite3_shutdown(); if (ret != SQLITE_OK) { LogPrintf("SQLiteDatabase: Failed to shutdown SQLite: %s\n", sqlite3_errstr(ret)); } } } void SQLiteDatabase::Open() { int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; if (m_mock) { flags |= SQLITE_OPEN_MEMORY; // In memory database for mock db } if (m_db == nullptr) { TryCreateDirectories(m_dir_path); int ret = sqlite3_open_v2(m_file_path.c_str(), &m_db, flags, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to open database: %s\n", sqlite3_errstr(ret))); } } if (sqlite3_db_readonly(m_db, "main") != 0) { throw std::runtime_error("SQLiteDatabase: Database opened in readonly mode but read-write permissions are needed"); } // Acquire an exclusive lock on the database // First change the locking mode to exclusive int ret = sqlite3_exec(m_db, "PRAGMA locking_mode = exclusive", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Unable to change database locking mode to exclusive: %s\n", sqlite3_errstr(ret))); } // Now begin a transaction to acquire the exclusive lock. This lock won't be released until we close because of the exclusive locking mode. ret = sqlite3_exec(m_db, "BEGIN EXCLUSIVE TRANSACTION", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error("SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another bitcoind?\n"); } ret = sqlite3_exec(m_db, "COMMIT", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Unable to end exclusive lock transaction: %s\n", sqlite3_errstr(ret))); } // Enable fullfsync for the platforms that use it ret = sqlite3_exec(m_db, "PRAGMA fullfsync = true", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable fullfsync: %s\n", sqlite3_errstr(ret))); } // Make the table for our key-value pairs // First check that the main table exists sqlite3_stmt* check_main_stmt{nullptr}; ret = sqlite3_prepare_v2(m_db, "SELECT name FROM sqlite_master WHERE type='table' AND name='main'", -1, &check_main_stmt, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to prepare statement to check table existence: %s\n", sqlite3_errstr(ret))); } ret = sqlite3_step(check_main_stmt); if (sqlite3_finalize(check_main_stmt) != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to finalize statement checking table existence: %s\n", sqlite3_errstr(ret))); } bool table_exists; if (ret == SQLITE_DONE) { table_exists = false; } else if (ret == SQLITE_ROW) { table_exists = true; } else { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to execute statement to check table existence: %s\n", sqlite3_errstr(ret))); } // Do the db setup things because the table doesn't exist only when we are creating a new wallet if (!table_exists) { ret = sqlite3_exec(m_db, "CREATE TABLE main(key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL)", nullptr, nullptr, nullptr); if (ret != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to create new database: %s\n", sqlite3_errstr(ret))); } } } bool SQLiteDatabase::Rewrite(const char* skip) { return false; } bool SQLiteDatabase::Backup(const std::string& dest) const { return false; } void SQLiteDatabase::Close() { int res = sqlite3_close(m_db); if (res != SQLITE_OK) { throw std::runtime_error(strprintf("SQLiteDatabase: Failed to close database: %s\n", sqlite3_errstr(res))); } m_db = nullptr; } std::unique_ptr<DatabaseBatch> SQLiteDatabase::MakeBatch(bool flush_on_close) { return nullptr; } SQLiteBatch::SQLiteBatch(SQLiteDatabase& database) : m_database(database) { // Make sure we have a db handle assert(m_database.m_db); SetupSQLStatements(); } void SQLiteBatch::Close() { // If m_db is in a transaction (i.e. not in autocommit mode), then abort the transaction in progress if (m_database.m_db && sqlite3_get_autocommit(m_database.m_db) == 0) { if (TxnAbort()) { LogPrintf("SQLiteBatch: Batch closed unexpectedly without the transaction being explicitly committed or aborted\n"); } else { LogPrintf("SQLiteBatch: Batch closed and failed to abort transaction\n"); } } // Free all of the prepared statements int ret = sqlite3_finalize(m_read_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize read statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_insert_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize insert statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_overwrite_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize overwrite statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_delete_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize delete statement: %s\n", sqlite3_errstr(ret)); } ret = sqlite3_finalize(m_cursor_stmt); if (ret != SQLITE_OK) { LogPrintf("SQLiteBatch: Batch closed but could not finalize cursor statement: %s\n", sqlite3_errstr(ret)); } m_read_stmt = nullptr; m_insert_stmt = nullptr; m_overwrite_stmt = nullptr; m_delete_stmt = nullptr; m_cursor_stmt = nullptr; } bool SQLiteBatch::ReadKey(CDataStream&& key, CDataStream& value) { if (!m_database.m_db) return false; assert(m_read_stmt); // Bind: leftmost parameter in statement is index 1 int res = sqlite3_bind_blob(m_read_stmt, 1, key.data(), key.size(), SQLITE_STATIC); if (res != SQLITE_OK) { LogPrintf("%s: Unable to bind statement: %s\n", __func__, sqlite3_errstr(res)); sqlite3_clear_bindings(m_read_stmt); sqlite3_reset(m_read_stmt); return false; } res = sqlite3_step(m_read_stmt); if (res != SQLITE_ROW) { if (res != SQLITE_DONE) { // SQLITE_DONE means "not found", don't log an error in that case. LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res)); } sqlite3_clear_bindings(m_read_stmt); sqlite3_reset(m_read_stmt); return false; } // Leftmost column in result is index 0 const char* data = reinterpret_cast<const char*>(sqlite3_column_blob(m_read_stmt, 0)); int data_size = sqlite3_column_bytes(m_read_stmt, 0); value.write(data, data_size); sqlite3_clear_bindings(m_read_stmt); sqlite3_reset(m_read_stmt); return true; } bool SQLiteBatch::WriteKey(CDataStream&& key, CDataStream&& value, bool overwrite) { if (!m_database.m_db) return false; assert(m_insert_stmt && m_overwrite_stmt); sqlite3_stmt* stmt; if (overwrite) { stmt = m_overwrite_stmt; } else { stmt = m_insert_stmt; } // Bind: leftmost parameter in statement is index 1 // Insert index 1 is key, 2 is value int res = sqlite3_bind_blob(stmt, 1, key.data(), key.size(), SQLITE_STATIC); if (res != SQLITE_OK) { LogPrintf("%s: Unable to bind key to statement: %s\n", __func__, sqlite3_errstr(res)); sqlite3_clear_bindings(stmt); sqlite3_reset(stmt); return false; } res = sqlite3_bind_blob(stmt, 2, value.data(), value.size(), SQLITE_STATIC); if (res != SQLITE_OK) { LogPrintf("%s: Unable to bind value to statement: %s\n", __func__, sqlite3_errstr(res)); sqlite3_clear_bindings(stmt); sqlite3_reset(stmt); return false; } // Execute res = sqlite3_step(stmt); sqlite3_clear_bindings(stmt); sqlite3_reset(stmt); if (res != SQLITE_DONE) { LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res)); } return res == SQLITE_DONE; } bool SQLiteBatch::EraseKey(CDataStream&& key) { if (!m_database.m_db) return false; assert(m_delete_stmt); // Bind: leftmost parameter in statement is index 1 int res = sqlite3_bind_blob(m_delete_stmt, 1, key.data(), key.size(), SQLITE_STATIC); if (res != SQLITE_OK) { LogPrintf("%s: Unable to bind statement: %s\n", __func__, sqlite3_errstr(res)); sqlite3_clear_bindings(m_delete_stmt); sqlite3_reset(m_delete_stmt); return false; } // Execute res = sqlite3_step(m_delete_stmt); sqlite3_clear_bindings(m_delete_stmt); sqlite3_reset(m_delete_stmt); if (res != SQLITE_DONE) { LogPrintf("%s: Unable to execute statement: %s\n", __func__, sqlite3_errstr(res)); } return res == SQLITE_DONE; } bool SQLiteBatch::HasKey(CDataStream&& key) { if (!m_database.m_db) return false; assert(m_read_stmt); // Bind: leftmost parameter in statement is index 1 bool ret = false; int res = sqlite3_bind_blob(m_read_stmt, 1, key.data(), key.size(), SQLITE_STATIC); if (res == SQLITE_OK) { res = sqlite3_step(m_read_stmt); if (res == SQLITE_ROW) { ret = true; } } sqlite3_clear_bindings(m_read_stmt); sqlite3_reset(m_read_stmt); return ret; } bool SQLiteBatch::StartCursor() { return false; } bool SQLiteBatch::ReadAtCursor(CDataStream& key, CDataStream& value, bool& complete) { return false; } void SQLiteBatch::CloseCursor() { } bool SQLiteBatch::TxnBegin() { return false; } bool SQLiteBatch::TxnCommit() { return false; } bool SQLiteBatch::TxnAbort() { return false; } bool ExistsSQLiteDatabase(const fs::path& path) { return false; } std::unique_ptr<SQLiteDatabase> MakeSQLiteDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error) { return MakeUnique<SQLiteDatabase>(path, path / DATABASE_FILENAME); } std::string SQLiteDatabaseVersion() { return std::string(sqlite3_libversion()); }
Implement SQLiteBatch::ReadKey, WriteKey, EraseKey, and HasKey
Implement SQLiteBatch::ReadKey, WriteKey, EraseKey, and HasKey
C++
mit
Xekyo/bitcoin,rnicoll/dogecoin,MeshCollider/bitcoin,fujicoin/fujicoin,AkioNak/bitcoin,sipsorcery/bitcoin,qtumproject/qtum,mm-s/bitcoin,qtumproject/qtum,litecoin-project/litecoin,prusnak/bitcoin,GroestlCoin/bitcoin,ElementsProject/elements,JeremyRubin/bitcoin,alecalve/bitcoin,yenliangl/bitcoin,rnicoll/bitcoin,yenliangl/bitcoin,jlopp/statoshi,AkioNak/bitcoin,bitcoinknots/bitcoin,mm-s/bitcoin,jambolo/bitcoin,anditto/bitcoin,mm-s/bitcoin,litecoin-project/litecoin,domob1812/bitcoin,mruddy/bitcoin,Sjors/bitcoin,rnicoll/bitcoin,cdecker/bitcoin,MarcoFalke/bitcoin,kallewoof/bitcoin,pstratem/bitcoin,ElementsProject/elements,andreaskern/bitcoin,Sjors/bitcoin,sstone/bitcoin,sipsorcery/bitcoin,fanquake/bitcoin,prusnak/bitcoin,pstratem/bitcoin,jnewbery/bitcoin,n1bor/bitcoin,bitcoin/bitcoin,MarcoFalke/bitcoin,Xekyo/bitcoin,jlopp/statoshi,litecoin-project/litecoin,practicalswift/bitcoin,mruddy/bitcoin,rnicoll/bitcoin,domob1812/namecore,bitcoin/bitcoin,practicalswift/bitcoin,jlopp/statoshi,domob1812/namecore,anditto/bitcoin,fujicoin/fujicoin,kallewoof/bitcoin,bitcoinknots/bitcoin,MeshCollider/bitcoin,ElementsProject/elements,cdecker/bitcoin,namecoin/namecore,Xekyo/bitcoin,mruddy/bitcoin,sstone/bitcoin,achow101/bitcoin,bitcoin/bitcoin,ElementsProject/elements,tecnovert/particl-core,domob1812/bitcoin,GroestlCoin/GroestlCoin,tecnovert/particl-core,MeshCollider/bitcoin,sstone/bitcoin,jambolo/bitcoin,jonasschnelli/bitcoin,andreaskern/bitcoin,jnewbery/bitcoin,Xekyo/bitcoin,anditto/bitcoin,bitcoinsSG/bitcoin,MarcoFalke/bitcoin,EthanHeilman/bitcoin,Sjors/bitcoin,AkioNak/bitcoin,sstone/bitcoin,instagibbs/bitcoin,Sjors/bitcoin,yenliangl/bitcoin,sipsorcery/bitcoin,anditto/bitcoin,GroestlCoin/GroestlCoin,sstone/bitcoin,namecoin/namecore,domob1812/namecore,andreaskern/bitcoin,andreaskern/bitcoin,GroestlCoin/bitcoin,mm-s/bitcoin,EthanHeilman/bitcoin,ajtowns/bitcoin,domob1812/namecore,jonasschnelli/bitcoin,pataquets/namecoin-core,jamesob/bitcoin,jnewbery/bitcoin,pataquets/namecoin-core,fujicoin/fujicoin,domob1812/bitcoin,particl/particl-core,namecoin/namecoin-core,apoelstra/bitcoin,alecalve/bitcoin,JeremyRubin/bitcoin,cdecker/bitcoin,prusnak/bitcoin,MeshCollider/bitcoin,ajtowns/bitcoin,bitcoinknots/bitcoin,ElementsProject/elements,namecoin/namecore,AkioNak/bitcoin,qtumproject/qtum,mm-s/bitcoin,sipsorcery/bitcoin,litecoin-project/litecoin,GroestlCoin/GroestlCoin,fanquake/bitcoin,namecoin/namecoin-core,fujicoin/fujicoin,prusnak/bitcoin,n1bor/bitcoin,fanquake/bitcoin,kallewoof/bitcoin,EthanHeilman/bitcoin,GroestlCoin/bitcoin,practicalswift/bitcoin,jamesob/bitcoin,particl/particl-core,bitcoinsSG/bitcoin,cdecker/bitcoin,jnewbery/bitcoin,rnicoll/bitcoin,tecnovert/particl-core,lateminer/bitcoin,pataquets/namecoin-core,EthanHeilman/bitcoin,yenliangl/bitcoin,lateminer/bitcoin,instagibbs/bitcoin,domob1812/namecore,jamesob/bitcoin,andreaskern/bitcoin,bitcoin/bitcoin,jlopp/statoshi,sstone/bitcoin,alecalve/bitcoin,n1bor/bitcoin,rnicoll/dogecoin,lateminer/bitcoin,lateminer/bitcoin,jlopp/statoshi,achow101/bitcoin,bitcoinsSG/bitcoin,MarcoFalke/bitcoin,jonasschnelli/bitcoin,rnicoll/dogecoin,andreaskern/bitcoin,GroestlCoin/bitcoin,jlopp/statoshi,mm-s/bitcoin,mruddy/bitcoin,bitcoinknots/bitcoin,jamesob/bitcoin,apoelstra/bitcoin,qtumproject/qtum,kallewoof/bitcoin,namecoin/namecore,lateminer/bitcoin,tecnovert/particl-core,EthanHeilman/bitcoin,MarcoFalke/bitcoin,dscotese/bitcoin,achow101/bitcoin,jonasschnelli/bitcoin,rnicoll/dogecoin,bitcoinsSG/bitcoin,JeremyRubin/bitcoin,tecnovert/particl-core,jamesob/bitcoin,practicalswift/bitcoin,jambolo/bitcoin,cdecker/bitcoin,ajtowns/bitcoin,GroestlCoin/bitcoin,instagibbs/bitcoin,dscotese/bitcoin,domob1812/bitcoin,ElementsProject/elements,particl/particl-core,mruddy/bitcoin,fanquake/bitcoin,pstratem/bitcoin,domob1812/namecore,MarcoFalke/bitcoin,Sjors/bitcoin,pstratem/bitcoin,GroestlCoin/GroestlCoin,jambolo/bitcoin,domob1812/bitcoin,GroestlCoin/GroestlCoin,bitcoinknots/bitcoin,Xekyo/bitcoin,n1bor/bitcoin,kallewoof/bitcoin,pataquets/namecoin-core,pataquets/namecoin-core,JeremyRubin/bitcoin,jambolo/bitcoin,litecoin-project/litecoin,namecoin/namecore,practicalswift/bitcoin,JeremyRubin/bitcoin,yenliangl/bitcoin,particl/particl-core,AkioNak/bitcoin,qtumproject/qtum,cdecker/bitcoin,achow101/bitcoin,mruddy/bitcoin,anditto/bitcoin,sipsorcery/bitcoin,bitcoin/bitcoin,apoelstra/bitcoin,apoelstra/bitcoin,kallewoof/bitcoin,alecalve/bitcoin,alecalve/bitcoin,rnicoll/bitcoin,prusnak/bitcoin,dscotese/bitcoin,namecoin/namecoin-core,ajtowns/bitcoin,pstratem/bitcoin,prusnak/bitcoin,MeshCollider/bitcoin,lateminer/bitcoin,namecoin/namecore,bitcoinsSG/bitcoin,bitcoinsSG/bitcoin,n1bor/bitcoin,JeremyRubin/bitcoin,fujicoin/fujicoin,litecoin-project/litecoin,alecalve/bitcoin,qtumproject/qtum,yenliangl/bitcoin,ajtowns/bitcoin,fanquake/bitcoin,namecoin/namecoin-core,MeshCollider/bitcoin,dscotese/bitcoin,GroestlCoin/GroestlCoin,AkioNak/bitcoin,achow101/bitcoin,fanquake/bitcoin,namecoin/namecoin-core,pstratem/bitcoin,instagibbs/bitcoin,qtumproject/qtum,bitcoin/bitcoin,Xekyo/bitcoin,apoelstra/bitcoin,instagibbs/bitcoin,particl/particl-core,pataquets/namecoin-core,tecnovert/particl-core,namecoin/namecoin-core,dscotese/bitcoin,particl/particl-core,anditto/bitcoin,GroestlCoin/bitcoin,apoelstra/bitcoin,jamesob/bitcoin,EthanHeilman/bitcoin,domob1812/bitcoin,rnicoll/dogecoin,sipsorcery/bitcoin,jnewbery/bitcoin,jonasschnelli/bitcoin,n1bor/bitcoin,achow101/bitcoin,ajtowns/bitcoin,rnicoll/bitcoin,instagibbs/bitcoin,practicalswift/bitcoin,dscotese/bitcoin,fujicoin/fujicoin,jambolo/bitcoin
ed8cfad5baf9d7fd7c8cb2178dabaed4eac71eb7
src/basic_clean_server.cpp
src/basic_clean_server.cpp
#include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <roomba_clean_actions/basic_cleanAction.h> #include <roomba_serial/SendButton.h> #include <roomba_serial/SetMode.h> #include <roomba_serial/Sensors.h> #include <ctime> class basic_cleanAction { protected: ros::NodeHandle nh_; ros::ServiceClient client = nh_.serviceClient<roomba_serial::Sensors>("GetSensors"); actionlib::SimpleActionServer<roomba_clean_actions::basic_cleanAction> cleanserv_; std::string action_name_; roomba_clean_actions::basic_cleanFeedback feedback_; roomba_clean_actions::basic_cleanResult result_; ros::Publisher button_pub = nh_.advertise<roomba_serial::SendButton>("BUTTON_OUT", 100); ros::Publisher mode_pub = nh_.advertise<roomba_serial::SetMode>("MODE_CHANGES", 100); public: basic_cleanAction(std::string name) : cleanserv_(nh_, name, boost::bind(&basic_cleanAction::executeCB, this, _1), false), action_name_(name) { cleanserv_.start(); ROS_INFO("Clean server started."); } ~basic_cleanAction(void) { } void executeCB(const roomba_clean_actions::basic_cleanGoalConstPtr &goal) { ROS_DEBUG("Got goal of %d seconds", goal->seconds); ros::Rate r(1); roomba_serial::SendButton dock; dock.buttoncode = 10; roomba_serial::Sensors sensorServer; int distance = 0; float charge; sensorServer.request.request = 0; bool success = true; time_t base = time(NULL); time_t curr = base; roomba_serial::SetMode mode; roomba_serial::SendButton button; mode.modecode = 2; // Safe mode, to start cleaning cycle button.buttoncode = 3; // Max length cycle bool running = false; while(!running) { mode_pub.publish(mode); button_pub.publish(button); while(!client.call(sensorServer)) {r.sleep();} running = (sensorServer.response.current < -150); ROS_DEBUG("Current out of battery is %d mA", sensorServer.response.current); r.sleep(); r.sleep(); r.sleep(); r.sleep(); r.sleep(); } while(curr < base + goal->seconds) { if(cleanserv_.isPreemptRequested() || !ros::ok()) { mode_pub.publish(dock); ROS_INFO("%s: Preempted, now docking", action_name_.c_str()); cleanserv_.setPreempted(); success = false; break; } curr = time(NULL); if(client.call(sensorServer)) { distance = distance + sensorServer.response.distance; charge = (float) (sensorServer.response.charge / sensorServer.response.capacity); } else { ROS_INFO("%s: Didn't get sensor response, sending stale data.", action_name_.c_str()); } feedback_.seconds = (uint16_t) (curr - base); feedback_.millimeters = distance; feedback_.battery_charge = charge; cleanserv_.publishFeedback(feedback_); r.sleep(); } button_pub.publish(dock); bool charging = false; while(!charging) { while(!client.call(sensorServer)) {r.sleep();} charging = (sensorServer.response.chargestate == 2); feedback_.millimeters = distance + sensorServer.response.distance; feedback_.battery_charge = (float) (sensorServer.response.charge / sensorServer.response.capacity); feedback_.seconds = time(NULL) - base; cleanserv_.publishFeedback(feedback_); r.sleep(); } result_.seconds = feedback_.seconds; result_.millimeters = feedback_.millimeters; result_.battery_charge = feedback_.battery_charge; cleanserv_.setSucceeded(result_); } }; int main(int argc, char** argv) { ros::init(argc, argv, "basic_clean"); basic_cleanAction bc(ros::this_node::getName()); ros::spin(); }
#include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <roomba_clean_actions/basic_cleanAction.h> #include <roomba_serial/SendButton.h> #include <roomba_serial/SetMode.h> #include <roomba_serial/Sensors.h> #include <ctime> class basic_cleanAction { protected: ros::NodeHandle nh_; ros::ServiceClient client = nh_.serviceClient<roomba_serial::Sensors>("GetSensors"); actionlib::SimpleActionServer<roomba_clean_actions::basic_cleanAction> cleanserv_; std::string action_name_; roomba_clean_actions::basic_cleanFeedback feedback_; roomba_clean_actions::basic_cleanResult result_; ros::Publisher button_pub = nh_.advertise<roomba_serial::SendButton>("BUTTON_OUT", 100); ros::Publisher mode_pub = nh_.advertise<roomba_serial::SetMode>("MODE_CHANGES", 100); public: basic_cleanAction(std::string name) : cleanserv_(nh_, name, boost::bind(&basic_cleanAction::executeCB, this, _1), false), action_name_(name) { cleanserv_.start(); ROS_INFO("Clean server started."); } ~basic_cleanAction(void) { } void executeCB(const roomba_clean_actions::basic_cleanGoalConstPtr &goal) { ROS_DEBUG("Got goal of %d seconds", goal->seconds); ros::Rate r(1); roomba_serial::SendButton dock; dock.buttoncode = 10; roomba_serial::Sensors sensorServer; int distance = 0; float charge; sensorServer.request.request = 0; bool success = true; time_t base = time(NULL); time_t curr = base; roomba_serial::SetMode mode; roomba_serial::SendButton button; mode.modecode = 2; // Safe mode, to start cleaning cycle button.buttoncode = 3; // Max length cycle bool running = false; while(!running) { mode_pub.publish(mode); button_pub.publish(button); while(!client.call(sensorServer)) {r.sleep();} running = (sensorServer.response.current < -150); ROS_DEBUG("Current out of battery is %d mA", sensorServer.response.current); r.sleep(); r.sleep(); r.sleep(); r.sleep(); r.sleep(); } while(curr < base + goal->seconds) { if(cleanserv_.isPreemptRequested() || !ros::ok()) { mode_pub.publish(dock); ROS_INFO("%s: Preempted, now docking", action_name_.c_str()); cleanserv_.setPreempted(); success = false; break; } curr = time(NULL); if(client.call(sensorServer)) { distance = distance + sensorServer.response.distance; charge = (float) (sensorServer.response.charge / sensorServer.response.capacity); } else { ROS_INFO("%s: Didn't get sensor response, sending stale data.", action_name_.c_str()); } feedback_.seconds = (uint16_t) (curr - base); feedback_.millimeters = distance; feedback_.battery_charge = charge; cleanserv_.publishFeedback(feedback_); r.sleep(); } button_pub.publish(dock); bool charging = false; while(!charging) { while(!client.call(sensorServer)) {r.sleep();} charging = (sensorServer.response.current > 0); feedback_.millimeters = distance + sensorServer.response.distance; feedback_.battery_charge = (float) (sensorServer.response.charge / sensorServer.response.capacity); feedback_.seconds = time(NULL) - base; cleanserv_.publishFeedback(feedback_); r.sleep(); } result_.seconds = feedback_.seconds; result_.millimeters = feedback_.millimeters; result_.battery_charge = feedback_.battery_charge; cleanserv_.setSucceeded(result_); } }; int main(int argc, char** argv) { ros::init(argc, argv, "basic_clean"); basic_cleanAction bc(ros::this_node::getName()); ros::spin(); }
Change completion condition for clean action. It was "charge state == 2", now it is "current > 0".
Change completion condition for clean action. It was "charge state == 2", now it is "current > 0".
C++
mit
danbsmith/roomba-cleaning
a30fbf4834e20eebe8b2534fcdeb67b012b2d6a6
opencv_detector/src/main.cpp
opencv_detector/src/main.cpp
#include "lib/camera/web_camera.h" #include "lib/filter/filter_chain.h" #include "lib/filter/frame_grab.h" #include "lib/filter/gaussian_blur.h" #include "lib/filter/display.h" #include "lib/filter/background_extractor.h" #include "lib/filter/binary_threshold.h" #include "lib/filter/dilate.h" #include "lib/filter/erode.h" #include "lib/filter/blur.h" #include "lib/count_reporter.h" #include "lib/camera/pi_camera.h" #ifdef USE_RASPBERRY_PI #pragma message ("Creating Raspberry PI application") #else #pragma message ("Creating non-Rasberry PI application") #endif const std::string DEVICE_IDENTIFIER("demo"); using namespace TooManyPeeps; using namespace TooManyPeeps::Mqtt; int main() { #ifdef USE_RASPBERRY_PI PiCamera camera; #else WebCamera camera; #endif cv::Mat original; cv::Mat blurred; cv::Mat mog2Processed; cv::Mat detection; cv::Mat otherBlur; FilterChain blobDetect; blobDetect.add(new FrameGrab(original, &camera)); blobDetect.add(new Display(original, "Original")); blobDetect.add(new GaussianBlur(original, blurred, 5)); blobDetect.add(new BackgroundExtractor(blurred, mog2Processed, 100, 16)); blobDetect.add(new Dilate(mog2Processed, detection, 10)); blobDetect.add(new Erode(detection, detection, 5)); blobDetect.add(new Display(detection, "Final Result")); blobDetect.add(new Blur(original, otherBlur, 5)); blobDetect.add(new Display(otherBlur, "Other Blur Result")); CountReporter countReporter(DEVICE_IDENTIFIER); countReporter.in(5); countReporter.out(16); do { blobDetect.execute(); } while (true); return 0; }
#include "lib/camera/web_camera.h" #include "lib/filter/filter_chain.h" #include "lib/filter/frame_grab.h" #include "lib/filter/gaussian_blur.h" #include "lib/filter/display.h" #include "lib/filter/background_extractor.h" #include "lib/filter/binary_threshold.h" #include "lib/filter/dilate.h" #include "lib/filter/erode.h" #include "lib/filter/blur.h" #include "lib/count_reporter.h" #include "lib/camera/pi_camera.h" #include <ctime> #ifdef USE_RASPBERRY_PI #pragma message ("Creating Raspberry PI application") #else #pragma message ("Creating non-Rasberry PI application") #endif const std::string DEVICE_IDENTIFIER("demo"); using namespace TooManyPeeps; using namespace TooManyPeeps::Mqtt; int main() { #ifdef USE_RASPBERRY_PI PiCamera camera; #else WebCamera camera; #endif cv::Mat original; cv::Mat blurred; cv::Mat mog2Processed; cv::Mat detection; cv::Mat otherBlur; FilterChain blobDetect; blobDetect.add(new FrameGrab(original, &camera)); blobDetect.add(new Display(original, "Original")); blobDetect.add(new GaussianBlur(original, blurred, 5)); blobDetect.add(new BackgroundExtractor(blurred, mog2Processed, 100, 16)); blobDetect.add(new Dilate(mog2Processed, detection, 10)); blobDetect.add(new Erode(detection, detection, 5)); blobDetect.add(new Display(detection, "Final Result")); blobDetect.add(new Blur(original, otherBlur, 5)); blobDetect.add(new Display(otherBlur, "Other Blur Result")); CountReporter countReporter(DEVICE_IDENTIFIER); countReporter.in(5); countReporter.out(16); do { double time_=cv::getTickCount(); blobDetect.execute(); double secondsElapsed= double ( cv::getTickCount()-time_ ) /double ( cv::getTickFrequency() ); std::cout << "FPS = " << (1.0 /secondsElapsed ) << std::endl; } while (true); return 0; }
Add fps counter
Add fps counter
C++
mit
99-bugs/toomanypeeps,99-bugs/toomanypeeps,99-bugs/toomanypeeps
a8a80f5bcb31850ff451683dd42bf94ff0e0c68a
kopete/config/avdevice/avdeviceconfig.cpp
kopete/config/avdevice/avdeviceconfig.cpp
/* avdeviceconfig.cpp - Kopete Video Device Configuration Panel Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "avdeviceconfig.h" #include <qcheckbox.h> #include <qlayout.h> #include <qlabel.h> #include <qbuttongroup.h> #include <qspinbox.h> #include <qcombobox.h> #include <qslider.h> //Added by qt3to4: #include <QVBoxLayout> #include <kplugininfo.h> #include <klocale.h> #include <kpushbutton.h> #include <kgenericfactory.h> #include <ktrader.h> #include <kconfig.h> #include <kcombobox.h> #include <qimage.h> #include <qpixmap.h> #include <qtabwidget.h> #include <qgl.h> //#include "videodevice.h" typedef KGenericFactory<AVDeviceConfig, QWidget> KopeteAVDeviceConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_avdeviceconfig, KopeteAVDeviceConfigFactory( "kcm_kopete_avdeviceconfig" ) ) AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QStringList &args) : KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args ) { kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. "; QVBoxLayout *layout = new QVBoxLayout(this); mAVDeviceTabCtl = new QTabWidget(this); layout->addWidget( mAVDeviceTabCtl ); // "Video" TAB ============================================================ mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice(); // mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice(mAVDeviceTabCtl); connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int))); connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int))); connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int))); connect(mPrfsVideoDevice->mBrightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(slotBrightnessSliderChanged(int))); connect(mPrfsVideoDevice->mContrastSlider, SIGNAL(valueChanged(int)), this, SLOT(slotContrastSliderChanged(int))); connect(mPrfsVideoDevice->mSaturationSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSaturationSliderChanged(int))); connect(mPrfsVideoDevice->mWhitenessSlider, SIGNAL(valueChanged(int)), this, SLOT(slotWhitenessSliderChanged(int))); connect(mPrfsVideoDevice->mHueSlider, SIGNAL(valueChanged(int)), this, SLOT(slotHueSliderChanged(int))); connect(mPrfsVideoDevice->mImageAutoBrightnessContrast, SIGNAL(toggled(bool)), this, SLOT(slotImageAutoBrightnessContrastChanged(bool))); connect(mPrfsVideoDevice->mImageAutoColorCorrection, SIGNAL(toggled(bool)), this, SLOT(slotImageAutoColorCorrectionChanged(bool))); connect(mPrfsVideoDevice->mImageAsMirror, SIGNAL(toggled(bool)), this, SLOT(slotImageAsMirrorChanged(bool))); connect(mPrfsVideoDevice->mDeviceDisableMMap, SIGNAL(toggled(bool)), this, SLOT(slotDeviceDisableMMapChanged(bool))); connect(mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver, SIGNAL(toggled(bool)), this, SLOT(slotDeviceWorkaroundBrokenDriverChanged(bool))); // why is this here? // mPrfsVideoDevice->mVideoImageLabel->setPixmap(qpixmap); // mAVDeviceTabCtl->addTab(mPrfsVideoDevice,tr2i18n("&Video",0)); // Problematic. Need to be uncommented after fixing it. mVideoDevicePool = Kopete::AV::VideoDevicePool::self(); mVideoDevicePool->open(); mVideoDevicePool->setSize(320, 240); mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox); mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox); mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox); // setVideoInputParameters(); // mVideoDevicePool->startCapturing(); // mVideoDevicePool->getFrame(); // mVideoDevicePool->getImage(&qimage); // if (qpixmap.fromImage(qimage,Qt::AutoColor) != NULL) // if (qpixmap.fromImage(qimage,Qt::AutoColor) == true) // mPrfsVideoDevice->mVideoImageLabel->setPixmap(qpixmap); connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) ); qtimer.start(0,false); } AVDeviceConfig::~AVDeviceConfig() { mVideoDevicePool->close(); } /*! \fn VideoDeviceConfig::save() */ void AVDeviceConfig::save() { /// @todo implement me kDebug() << "kopete:config (avdevice): save() called. "; mVideoDevicePool->saveConfig(); } /*! \fn VideoDeviceConfig::load() */ void AVDeviceConfig::load() { /// @todo implement me } void AVDeviceConfig::slotSettingsChanged(bool){ emit changed(true); } void AVDeviceConfig::slotValueChanged(int){ emit changed( true ); } void AVDeviceConfig::setVideoInputParameters() { if(mVideoDevicePool->size()) { mPrfsVideoDevice->mBrightnessSlider->setValue((int)(mVideoDevicePool->getBrightness()*65535)); mPrfsVideoDevice->mContrastSlider->setValue((int)(mVideoDevicePool->getContrast()*65535)); mPrfsVideoDevice->mSaturationSlider->setValue((int)(mVideoDevicePool->getSaturation()*65535)); mPrfsVideoDevice->mWhitenessSlider->setValue((int)(mVideoDevicePool->getWhiteness()*65535)); mPrfsVideoDevice->mHueSlider->setValue((int)(mVideoDevicePool->getHue()*65535)); mPrfsVideoDevice->mImageAutoBrightnessContrast->setChecked(mVideoDevicePool->getAutoBrightnessContrast()); mPrfsVideoDevice->mImageAutoColorCorrection->setChecked(mVideoDevicePool->getAutoColorCorrection()); mPrfsVideoDevice->mImageAsMirror->setChecked(mVideoDevicePool->getImageAsMirror()); mPrfsVideoDevice->mDeviceDisableMMap->setChecked(mVideoDevicePool->getDisableMMap()); mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->setChecked(mVideoDevicePool->getWorkaroundBrokenDriver()); } } void AVDeviceConfig::slotDeviceKComboBoxChanged(int){ kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. "; unsigned int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentItem(); kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice; if ((newdevice < mVideoDevicePool->m_videodevice.size())&&(newdevice!=mVideoDevicePool->currentDevice())) { kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. "; mVideoDevicePool->open(newdevice); mVideoDevicePool->setSize(320, 240); mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox); mVideoDevicePool->startCapturing(); setVideoInputParameters(); kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. "; emit changed( true ); } } void AVDeviceConfig::slotInputKComboBoxChanged(int){ unsigned int newinput = mPrfsVideoDevice->mInputKComboBox->currentItem(); if((newinput < mVideoDevicePool->inputs()) && ( newinput !=mVideoDevicePool->currentInput())) { mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentItem()); mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox); setVideoInputParameters(); emit changed( true ); } } // ATTENTION: The 65535.0 value must be used instead of 65535 because the trailing ".0" converts the resulting value to floating point number. // Otherwise the resulting division operation would return 0 or 1 exclusively. void AVDeviceConfig::slotStandardKComboBoxChanged(int){ emit changed( true ); } void AVDeviceConfig::slotBrightnessSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotBrightnessSliderChanged(int) called. " << mPrfsVideoDevice->mBrightnessSlider->value() / 65535.0; mVideoDevicePool->setBrightness( mPrfsVideoDevice->mBrightnessSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotContrastSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotContrastSliderChanged(int) called. " << mPrfsVideoDevice->mContrastSlider->value() / 65535.0; mVideoDevicePool->setContrast( mPrfsVideoDevice->mContrastSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotSaturationSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotSaturationSliderChanged(int) called. " << mPrfsVideoDevice->mSaturationSlider->value() / 65535.0; mVideoDevicePool->setSaturation( mPrfsVideoDevice->mSaturationSlider->value() / 65535.0); emit changed( true ); } void AVDeviceConfig::slotWhitenessSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotWhitenessSliderChanged(int) called. " << mPrfsVideoDevice->mWhitenessSlider->value() / 65535.0; mVideoDevicePool->setWhiteness( mPrfsVideoDevice->mWhitenessSlider->value() / 65535.0); emit changed( true ); } void AVDeviceConfig::slotHueSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotHueSliderChanged(int) called. " << mPrfsVideoDevice->mHueSlider->value() / 65535.0; mVideoDevicePool->setHue( mPrfsVideoDevice->mHueSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotImageAutoBrightnessContrastChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAutoBrightnessContrastChanged(" << mPrfsVideoDevice->mImageAutoBrightnessContrast->isChecked() << ") called. "; mVideoDevicePool->setAutoBrightnessContrast(mPrfsVideoDevice->mImageAutoBrightnessContrast->isChecked()); emit changed( true ); } void AVDeviceConfig::slotImageAutoColorCorrectionChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAutoColorCorrectionChanged(" << mPrfsVideoDevice->mImageAutoColorCorrection->isChecked() << ") called. "; mVideoDevicePool->setAutoColorCorrection(mPrfsVideoDevice->mImageAutoColorCorrection->isChecked()); emit changed( true ); } void AVDeviceConfig::slotImageAsMirrorChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAsMirrorChanged(" << mPrfsVideoDevice->mImageAsMirror->isChecked() << ") called. "; mVideoDevicePool->setImageAsMirror(mPrfsVideoDevice->mImageAsMirror->isChecked()); emit changed( true ); } void AVDeviceConfig::slotDeviceWorkaroundBrokenDriverChanged(bool){ kDebug() << "kopete:config (avdevice): slotDeviceWorkaroundBrokenDriverChanged(" << mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->isChecked() << ") called. "; mVideoDevicePool->setWorkaroundBrokenDriver(mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->isChecked()); emit changed( true ); } void AVDeviceConfig::slotDeviceDisableMMapChanged(bool){ kDebug() << "kopete:config (avdevice): slotDeviceDisableMMapChanged(" << mPrfsVideoDevice->mDeviceDisableMMap->isChecked() << ") called. "; mVideoDevicePool->setDisableMMap(mPrfsVideoDevice->mDeviceDisableMMap->isChecked()); emit changed( true ); } void AVDeviceConfig::slotUpdateImage() { mVideoDevicePool->getFrame(); // mVideoDevicePool->getImage(&qimage); //bitBlt(mPrfsVideoDevice->mVideoImageLabel, 0, 0, &qimage, 0, Qt::CopyROP); // kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated."; }
/* avdeviceconfig.cpp - Kopete Video Device Configuration Panel Copyright (c) 2005-2006 by Cláudio da Silveira Pinheiro <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "avdeviceconfig.h" #include <qcheckbox.h> #include <qlayout.h> #include <qlabel.h> #include <qbuttongroup.h> #include <qspinbox.h> #include <qcombobox.h> #include <qslider.h> //Added by qt3to4: #include <QVBoxLayout> #include <kplugininfo.h> #include <klocale.h> #include <kpushbutton.h> #include <kgenericfactory.h> #include <ktrader.h> #include <kconfig.h> #include <kcombobox.h> #include <qimage.h> #include <qpixmap.h> #include <qtabwidget.h> #include <qgl.h> //#include "videodevice.h" typedef KGenericFactory<AVDeviceConfig, QWidget> KopeteAVDeviceConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_avdeviceconfig, KopeteAVDeviceConfigFactory( "kcm_kopete_avdeviceconfig" ) ) AVDeviceConfig::AVDeviceConfig(QWidget *parent, const QStringList &args) : KCModule( KopeteAVDeviceConfigFactory::componentData(), parent, args ) { kDebug() << "kopete:config (avdevice): KopeteAVDeviceConfigFactory::componentData() called. "; QVBoxLayout *layout = new QVBoxLayout(this); mAVDeviceTabCtl = new QTabWidget(this); layout->addWidget( mAVDeviceTabCtl ); // "Video" TAB ============================================================ QWidget *w = new QWidget(this); mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice(); mPrfsVideoDevice->setupUi(w); mAVDeviceTabCtl->addTab(w, i18n("Video")); // mPrfsVideoDevice = new Ui_AVDeviceConfig_VideoDevice(mAVDeviceTabCtl); connect(mPrfsVideoDevice->mDeviceKComboBox, SIGNAL(activated(int)), this, SLOT(slotDeviceKComboBoxChanged(int))); connect(mPrfsVideoDevice->mInputKComboBox, SIGNAL(activated(int)), this, SLOT(slotInputKComboBoxChanged(int))); connect(mPrfsVideoDevice->mStandardKComboBox, SIGNAL(activated(int)), this, SLOT(slotStandardKComboBoxChanged(int))); connect(mPrfsVideoDevice->mBrightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(slotBrightnessSliderChanged(int))); connect(mPrfsVideoDevice->mContrastSlider, SIGNAL(valueChanged(int)), this, SLOT(slotContrastSliderChanged(int))); connect(mPrfsVideoDevice->mSaturationSlider, SIGNAL(valueChanged(int)), this, SLOT(slotSaturationSliderChanged(int))); connect(mPrfsVideoDevice->mWhitenessSlider, SIGNAL(valueChanged(int)), this, SLOT(slotWhitenessSliderChanged(int))); connect(mPrfsVideoDevice->mHueSlider, SIGNAL(valueChanged(int)), this, SLOT(slotHueSliderChanged(int))); connect(mPrfsVideoDevice->mImageAutoBrightnessContrast, SIGNAL(toggled(bool)), this, SLOT(slotImageAutoBrightnessContrastChanged(bool))); connect(mPrfsVideoDevice->mImageAutoColorCorrection, SIGNAL(toggled(bool)), this, SLOT(slotImageAutoColorCorrectionChanged(bool))); connect(mPrfsVideoDevice->mImageAsMirror, SIGNAL(toggled(bool)), this, SLOT(slotImageAsMirrorChanged(bool))); connect(mPrfsVideoDevice->mDeviceDisableMMap, SIGNAL(toggled(bool)), this, SLOT(slotDeviceDisableMMapChanged(bool))); connect(mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver, SIGNAL(toggled(bool)), this, SLOT(slotDeviceWorkaroundBrokenDriverChanged(bool))); // why is this here? // mPrfsVideoDevice->mVideoImageLabel->setPixmap(qpixmap); // mAVDeviceTabCtl->addTab(mPrfsVideoDevice,tr2i18n("&Video",0)); // Problematic. Need to be uncommented after fixing it. mVideoDevicePool = Kopete::AV::VideoDevicePool::self(); mVideoDevicePool->open(); mVideoDevicePool->setSize(320, 240); mVideoDevicePool->fillDeviceKComboBox(mPrfsVideoDevice->mDeviceKComboBox); mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox); mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox); // setVideoInputParameters(); // mVideoDevicePool->startCapturing(); // mVideoDevicePool->getFrame(); // mVideoDevicePool->getImage(&qimage); // if (qpixmap.fromImage(qimage,Qt::AutoColor) != NULL) // if (qpixmap.fromImage(qimage,Qt::AutoColor) == true) // mPrfsVideoDevice->mVideoImageLabel->setPixmap(qpixmap); connect(&qtimer, SIGNAL(timeout()), this, SLOT(slotUpdateImage()) ); qtimer.start(0,false); } AVDeviceConfig::~AVDeviceConfig() { mVideoDevicePool->close(); } /*! \fn VideoDeviceConfig::save() */ void AVDeviceConfig::save() { /// @todo implement me kDebug() << "kopete:config (avdevice): save() called. "; mVideoDevicePool->saveConfig(); } /*! \fn VideoDeviceConfig::load() */ void AVDeviceConfig::load() { /// @todo implement me } void AVDeviceConfig::slotSettingsChanged(bool){ emit changed(true); } void AVDeviceConfig::slotValueChanged(int){ emit changed( true ); } void AVDeviceConfig::setVideoInputParameters() { if(mVideoDevicePool->size()) { mPrfsVideoDevice->mBrightnessSlider->setValue((int)(mVideoDevicePool->getBrightness()*65535)); mPrfsVideoDevice->mContrastSlider->setValue((int)(mVideoDevicePool->getContrast()*65535)); mPrfsVideoDevice->mSaturationSlider->setValue((int)(mVideoDevicePool->getSaturation()*65535)); mPrfsVideoDevice->mWhitenessSlider->setValue((int)(mVideoDevicePool->getWhiteness()*65535)); mPrfsVideoDevice->mHueSlider->setValue((int)(mVideoDevicePool->getHue()*65535)); mPrfsVideoDevice->mImageAutoBrightnessContrast->setChecked(mVideoDevicePool->getAutoBrightnessContrast()); mPrfsVideoDevice->mImageAutoColorCorrection->setChecked(mVideoDevicePool->getAutoColorCorrection()); mPrfsVideoDevice->mImageAsMirror->setChecked(mVideoDevicePool->getImageAsMirror()); mPrfsVideoDevice->mDeviceDisableMMap->setChecked(mVideoDevicePool->getDisableMMap()); mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->setChecked(mVideoDevicePool->getWorkaroundBrokenDriver()); } } void AVDeviceConfig::slotDeviceKComboBoxChanged(int){ kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. "; unsigned int newdevice = mPrfsVideoDevice->mDeviceKComboBox->currentItem(); kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) Current device: " << mVideoDevicePool->currentDevice() << "New device: " << newdevice; if ((newdevice < mVideoDevicePool->m_videodevice.size())&&(newdevice!=mVideoDevicePool->currentDevice())) { kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) should change device. "; mVideoDevicePool->open(newdevice); mVideoDevicePool->setSize(320, 240); mVideoDevicePool->fillInputKComboBox(mPrfsVideoDevice->mInputKComboBox); mVideoDevicePool->startCapturing(); setVideoInputParameters(); kDebug() << "kopete:config (avdevice): slotDeviceKComboBoxChanged(int) called. "; emit changed( true ); } } void AVDeviceConfig::slotInputKComboBoxChanged(int){ unsigned int newinput = mPrfsVideoDevice->mInputKComboBox->currentItem(); if((newinput < mVideoDevicePool->inputs()) && ( newinput !=mVideoDevicePool->currentInput())) { mVideoDevicePool->selectInput(mPrfsVideoDevice->mInputKComboBox->currentItem()); mVideoDevicePool->fillStandardKComboBox(mPrfsVideoDevice->mStandardKComboBox); setVideoInputParameters(); emit changed( true ); } } // ATTENTION: The 65535.0 value must be used instead of 65535 because the trailing ".0" converts the resulting value to floating point number. // Otherwise the resulting division operation would return 0 or 1 exclusively. void AVDeviceConfig::slotStandardKComboBoxChanged(int){ emit changed( true ); } void AVDeviceConfig::slotBrightnessSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotBrightnessSliderChanged(int) called. " << mPrfsVideoDevice->mBrightnessSlider->value() / 65535.0; mVideoDevicePool->setBrightness( mPrfsVideoDevice->mBrightnessSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotContrastSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotContrastSliderChanged(int) called. " << mPrfsVideoDevice->mContrastSlider->value() / 65535.0; mVideoDevicePool->setContrast( mPrfsVideoDevice->mContrastSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotSaturationSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotSaturationSliderChanged(int) called. " << mPrfsVideoDevice->mSaturationSlider->value() / 65535.0; mVideoDevicePool->setSaturation( mPrfsVideoDevice->mSaturationSlider->value() / 65535.0); emit changed( true ); } void AVDeviceConfig::slotWhitenessSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotWhitenessSliderChanged(int) called. " << mPrfsVideoDevice->mWhitenessSlider->value() / 65535.0; mVideoDevicePool->setWhiteness( mPrfsVideoDevice->mWhitenessSlider->value() / 65535.0); emit changed( true ); } void AVDeviceConfig::slotHueSliderChanged(int){ kDebug() << "kopete:config (avdevice): slotHueSliderChanged(int) called. " << mPrfsVideoDevice->mHueSlider->value() / 65535.0; mVideoDevicePool->setHue( mPrfsVideoDevice->mHueSlider->value() / 65535.0 ); emit changed( true ); } void AVDeviceConfig::slotImageAutoBrightnessContrastChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAutoBrightnessContrastChanged(" << mPrfsVideoDevice->mImageAutoBrightnessContrast->isChecked() << ") called. "; mVideoDevicePool->setAutoBrightnessContrast(mPrfsVideoDevice->mImageAutoBrightnessContrast->isChecked()); emit changed( true ); } void AVDeviceConfig::slotImageAutoColorCorrectionChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAutoColorCorrectionChanged(" << mPrfsVideoDevice->mImageAutoColorCorrection->isChecked() << ") called. "; mVideoDevicePool->setAutoColorCorrection(mPrfsVideoDevice->mImageAutoColorCorrection->isChecked()); emit changed( true ); } void AVDeviceConfig::slotImageAsMirrorChanged(bool){ kDebug() << "kopete:config (avdevice): slotImageAsMirrorChanged(" << mPrfsVideoDevice->mImageAsMirror->isChecked() << ") called. "; mVideoDevicePool->setImageAsMirror(mPrfsVideoDevice->mImageAsMirror->isChecked()); emit changed( true ); } void AVDeviceConfig::slotDeviceWorkaroundBrokenDriverChanged(bool){ kDebug() << "kopete:config (avdevice): slotDeviceWorkaroundBrokenDriverChanged(" << mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->isChecked() << ") called. "; mVideoDevicePool->setWorkaroundBrokenDriver(mPrfsVideoDevice->mDeviceWorkaroundBrokenDriver->isChecked()); emit changed( true ); } void AVDeviceConfig::slotDeviceDisableMMapChanged(bool){ kDebug() << "kopete:config (avdevice): slotDeviceDisableMMapChanged(" << mPrfsVideoDevice->mDeviceDisableMMap->isChecked() << ") called. "; mVideoDevicePool->setDisableMMap(mPrfsVideoDevice->mDeviceDisableMMap->isChecked()); emit changed( true ); } void AVDeviceConfig::slotUpdateImage() { mVideoDevicePool->getFrame(); // mVideoDevicePool->getImage(&qimage); //bitBlt(mPrfsVideoDevice->mVideoImageLabel, 0, 0, &qimage, 0, Qt::CopyROP); // kDebug() << "kopete (avdeviceconfig_videoconfig): Image updated."; }
Add the video preferences to the tab
Add the video preferences to the tab svn path=/trunk/KDE/kdenetwork/kopete/; revision=703949
C++
lgpl-2.1
Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete
5abd34cb8f034ac3290b61fe4852e237a9114543
src/blender-geom-writer.cc
src/blender-geom-writer.cc
// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of gepetto-viewer-corba. // gepetto-viewer-corba is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // gepetto-viewer-corba 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // gepetto-viewer-corba. If not, see <http://www.gnu.org/licenses/>. #include <gepetto/viewer/blender-geom-writer.h> #include <algorithm> #include <sys/stat.h> #include <gepetto/viewer/node.h> #include <gepetto/viewer/group-node.h> #include <gepetto/viewer/leaf-node-arrow.h> #include <gepetto/viewer/leaf-node-box.h> #include <gepetto/viewer/leaf-node-capsule.h> #include <gepetto/viewer/leaf-node-collada.h> #include <gepetto/viewer/leaf-node-cone.h> #include <gepetto/viewer/leaf-node-cylinder.h> #include <gepetto/viewer/leaf-node-face.h> #include <gepetto/viewer/leaf-node-ground.h> #include <gepetto/viewer/leaf-node-light.h> #include <gepetto/viewer/leaf-node-line.h> #include <gepetto/viewer/leaf-node-sphere.h> #include <gepetto/viewer/leaf-node-xyzaxis.h> //#include <gepetto/viewer/node-rod.h> namespace graphics { namespace { const char indent[] = " "; const char end = '\n'; const char group[] = "##"; const char node[] = "#"; const char varMat[] = "material"; const char warning[] = "# Warning: "; template <typename Vector> std::ostream& writeVectorAsList (std::ostream& os, const Vector& v) { os << "( "; for (int i = 0; i < Vector::num_components; ++i) os << v[i] << ", "; os << ")"; return os; } template <> std::ostream& writeVectorAsList<osg::Quat> (std::ostream& os, const osg::Quat& q) { os << "( " << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z() << ", )"; return os; } std::ostream& writeRGB(std::ostream& os, const osgVector4& rgba) { return os << "( " << rgba.r() << ", " << rgba.g() << ", " << rgba.b() << ", )"; } void writeMaterial(std::ostream& os, const std::string& name, const osg::Material* mat, bool diffuse = true, bool ambient = false, bool specular = false) { const osg::Material::Face face = osg::Material::FRONT; os << varMat << " = bpy.data.materials.new(\"" << name << "\")" << end; if (diffuse) writeRGB (os << varMat << ".diffuse_color = ", mat->getDiffuse(face)) << end << varMat << ".diffuse_intensity = " << mat->getDiffuse(face).a() << end; if (ambient) writeRGB (os << varMat << ".ambient_color = ", mat->getAmbient(face)) << end << varMat << ".ambient_intensity = " << mat->getAmbient(face).a() << end; if (specular) writeRGB (os << varMat << ".specular_color = ", mat->getSpecular(face)) << end << varMat << ".specular_intensity = " << mat->getSpecular(face).a() << end; } void writeMaterial(std::ostream& os, const std::string& name, const osgVector4& rgbaDiffuse) { os << varMat << " = bpy.data.materials.new(\"" << name << "\")" << end; writeRGB (os << varMat << ".diffuse_color = ", rgbaDiffuse) << end << varMat << ".diffuse_intensity = " << rgbaDiffuse.a() << end; } template <typename NodeType> void setColor(std::ostream& os, NodeType& node) { writeMaterial(os, node.getID() + "__mat", node.getColor()); os << "bpy.context.object.data.materials.append(" << varMat << ')' << end; } template <> void setColor(std::ostream& os, LeafNodeCollada& node) { osg::Material* mat_ptr = dynamic_cast<osg::Material*> ( node.getOsgNode()->getStateSet()->getAttribute(osg::StateAttribute::MATERIAL)); if (mat_ptr != NULL) { // Color was set by URDF writeMaterial(os, node.getID() + "__mat", mat_ptr, true, false, false); os << "setMaterial (imported_objects, " << varMat << ')' << end; } } } BlenderGeomWriterVisitor::BlenderGeomWriterVisitor (const std::string& filename) : filename_ (filename) { bool isNew = !openFile(); const std::string comment = (isNew ? "" : "# "); out() << comment << "import bpy" << end << end << comment << "## Start convenient functions" << end << comment << "def checkConf():" << end << comment << " if bpy.app.version[0:2] != (2, 75):" << end << comment << " print \"Using blender version\", bpy.app.version" << end << comment << " print \"Developed under version 2.75.0.\"" << end << comment << " return False" << end << comment << " if bpy.context.scene.render.engine != 'CYCLES':" << end << comment << " print \"Cycles renderer is prefered\"" << end << comment << " return False" << end << comment << " return True" << end << comment << end << comment << "taggedObjects = list()" << end << comment << "def tagObjects ():" << end << comment << " global taggedObjects" << end << comment << " taggedObjects = list ()" << end << comment << " for obj in bpy.data.objects:" << end << comment << " taggedObjects.append (obj.name)" << end << comment << "" << end << comment << "def getNonTaggedObjects ():" << end << comment << " global taggedObjects" << end << comment << " return [obj for obj in bpy.data.objects if obj.name not in taggedObjects]" << end << comment << "" << end << comment << "def setParent (children, parent):" << end << comment << " for child in children:" << end << comment << " child.parent = parent" << end << end << comment << "" << end << comment << "def setMaterial (children, mat):" << end << comment << " for child in children:" << end << comment << " child.data.materials.append(mat)" << end << end << comment << "checkConf()" << end << end << comment << "## End of convenient functions" << end; } bool BlenderGeomWriterVisitor::openFile () { struct stat buffer; bool ret = (stat (filename_.c_str(), &buffer) == 0); file_.open (filename_.c_str(), std::ofstream::out | std::ofstream::app); if (!file_.is_open ()) throw std::ios_base::failure ("Unable to open file " + filename_); return ret; } void BlenderGeomWriterVisitor::apply (Node& node) { std::cerr << "This function should not be called. Type of node " << node.getID() << " may be unknown" << std::endl; standardApply(node); } void BlenderGeomWriterVisitor::apply (GroupNode& node) { for (std::size_t i = 0; i < groupStack_.size() + 1; ++i) out() << group; out() << " Group " << node.getID() << end; out() << "bpy.ops.object.empty_add()" << end << "bpy.context.object.name = \"" << node.getID() << '"' << end; // Set parent of this group if (!groupStack_.empty()) out() << "bpy.context.object.parent = bpy.data.objects[\"" << groupStack_.top() << "\"]" << end; groupStack_.push(node.getID()); NodeVisitor::apply(static_cast<Node&>(node)); groupStack_.pop(); for (std::size_t i = 0; i < groupStack_.size() + 1; ++i) out() << group; out() << end; } void BlenderGeomWriterVisitor::apply (LeafNodeArrow& node) { unimplemented("LeafNodeArrow", node); } void BlenderGeomWriterVisitor::apply (LeafNodeBox& node) { out() << "bpy.ops.mesh.primitive_cube_add ()" << end << "bpy.context.object.dimensions = "; writeVectorAsList(out(), node.getHalfAxis()*2) << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCapsule& node) { unimplemented("LeafNodeCapsule", node); } void BlenderGeomWriterVisitor::apply (LeafNodeCollada& node) { out() << "tagObjects()" << end; const std::string& mesh = node.meshFilePath(); std::string ext = mesh.substr(mesh.find_last_of(".")+1,mesh.size()); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if(ext == "obj") { out() << "bpy.ops.import_scene.obj (filepath=\"" << mesh << "\")" << end; } else if (ext == "dae") { out() << "bpy.ops.wm.collada_import (filepath=\"" << mesh << "\")" << end; } else if (ext == "stl") { out() << "bpy.ops.import_mesh.stl (filepath=\"" << mesh << "\")" << end; } else { std::cout << "Extension of file " << mesh << " with name " << node.getID() << " is not known." << end << "You can load the file manually and add it to the empty object called " << node.getID() << end << "To fix the issue, upate" __FILE__ ":" << __LINE__ << std::endl; out() << "# Here goes the content of file " << mesh << end; out() << "# To fix it, upate" __FILE__ ":" << __LINE__ << end; } out () << "imported_objects = getNonTaggedObjects ()" << end << "print(imported_objects)" << end << "bpy.ops.object.empty_add ()" << end << "setParent (imported_objects, bpy.context.object)" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCone& node) { out() << "bpy.ops.mesh.primitive_cone_add (radius1=" << node.getRadius() << ", depth=" << node.getHeight() << ')' << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCylinder& node) { out() << "bpy.ops.mesh.primitive_cylinder_add (radius=" << node.getRadius() << ", depth=" << node.getHeight() << ')' << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeFace& node) { unimplemented("LeafNodeFace", node); } void BlenderGeomWriterVisitor::apply (LeafNodeGround& node) { unimplemented("LeafNodeGround", node); } void BlenderGeomWriterVisitor::apply (LeafNodeLight& node) { unimplemented("LeafNodeLight", node); } void BlenderGeomWriterVisitor::apply (LeafNodeLine& node) { ::osg::Vec3ArrayRefPtr points = node.getPoints(); out() << "points = ["; for (std::size_t i = 0; i < points->size(); ++i) writeVectorAsList(out(), points->at(i)) << ','; out() << ']' << end; if (node.getMode() != GL_LINE_STRIP) { out() << warning << "Only GL_LINE_STRIP is supported." << end; } out() << "curve = bpy.data.curves.new(name=\"" << node.getID() << "__curve\", type='CURVE')" << end << "curve.dimensions = '3D'" << end << "curve.fill_mode = 'FULL'" << end << "curve.bevel_depth = 0.01" << end << "curve.bevel_resolution = 10" << end /// define points that make the line << "polyline = curve.splines.new('POLY')" << end << "polyline.points.add(len(points)-1)" << end << "for i in xrange(len(points)):" << end << " polyline.points[i].co = (points[i])+(1.0,)" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeSphere& node) { out () << "bpy.ops.mesh.primitive_ico_sphere_add (size=" << node.getRadius() << ")" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeXYZAxis& node) { unimplemented("LeafNodeXYZAxis", node); } void BlenderGeomWriterVisitor::standardApply (Node& node) { const std::string& id = node.getID (); // Set name out() << "bpy.context.object.name = \"" << id << "__shape\"" << end << "bpy.context.object.location = "; writeVectorAsList(out(), node.getStaticPosition()) << end; out() << "bpy.context.object.rotation_mode = 'QUATERNION'" << end << "bpy.context.object.rotation_quaternion = "; writeVectorAsList(out(), node.getStaticRotation()) << end; out() << "bpy.ops.object.empty_add ()" << end << "bpy.context.object.name = \"" << id << '"' << end << "bpy.data.objects[\"" << id << "__shape\"].parent = " << "bpy.data.objects[\"" << id << "\"]" << end; // Set parent group if (!groupStack_.empty()) out() << "bpy.context.object.parent = bpy.data.objects[\"" << groupStack_.top() << "\"]" << end; NodeVisitor::apply (node); } void BlenderGeomWriterVisitor::unimplemented(const char* type, Node& node) { std::cout << type << " is not implemented. " << node.getID() << " not added" << std::endl; out() << "bpy.ops.object.empty_add()" << end; standardApply(node); } } // namespace graphics
// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of gepetto-viewer-corba. // gepetto-viewer-corba is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // gepetto-viewer-corba 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // gepetto-viewer-corba. If not, see <http://www.gnu.org/licenses/>. #include <gepetto/viewer/blender-geom-writer.h> #include <algorithm> #include <sys/stat.h> #include <gepetto/viewer/node.h> #include <gepetto/viewer/group-node.h> #include <gepetto/viewer/leaf-node-arrow.h> #include <gepetto/viewer/leaf-node-box.h> #include <gepetto/viewer/leaf-node-capsule.h> #include <gepetto/viewer/leaf-node-collada.h> #include <gepetto/viewer/leaf-node-cone.h> #include <gepetto/viewer/leaf-node-cylinder.h> #include <gepetto/viewer/leaf-node-face.h> #include <gepetto/viewer/leaf-node-ground.h> #include <gepetto/viewer/leaf-node-light.h> #include <gepetto/viewer/leaf-node-line.h> #include <gepetto/viewer/leaf-node-sphere.h> #include <gepetto/viewer/leaf-node-xyzaxis.h> //#include <gepetto/viewer/node-rod.h> namespace graphics { namespace { const char indent[] = " "; const char end = '\n'; const char group[] = "##"; const char node[] = "#"; const char varMat[] = "material"; const char warning[] = "# Warning: "; template <typename Vector> std::ostream& writeVectorAsList (std::ostream& os, const Vector& v) { os << "( "; for (int i = 0; i < Vector::num_components; ++i) os << v[i] << ", "; os << ")"; return os; } template <> std::ostream& writeVectorAsList<osg::Quat> (std::ostream& os, const osg::Quat& q) { os << "( " << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z() << ", )"; return os; } std::ostream& writeRGB(std::ostream& os, const osgVector4& rgba) { return os << "( " << rgba.r() << ", " << rgba.g() << ", " << rgba.b() << ", )"; } void writeMaterial(std::ostream& os, const std::string& name, const osg::Material* mat, bool diffuse = true, bool ambient = false, bool specular = false) { const osg::Material::Face face = osg::Material::FRONT; os << varMat << " = bpy.data.materials.new(\"" << name << "\")" << end; if (diffuse) writeRGB (os << varMat << ".diffuse_color = ", mat->getDiffuse(face)) << end << varMat << ".diffuse_intensity = " << mat->getDiffuse(face).a() << end; if (ambient) writeRGB (os << varMat << ".ambient_color = ", mat->getAmbient(face)) << end << varMat << ".ambient_intensity = " << mat->getAmbient(face).a() << end; if (specular) writeRGB (os << varMat << ".specular_color = ", mat->getSpecular(face)) << end << varMat << ".specular_intensity = " << mat->getSpecular(face).a() << end; } void writeMaterial(std::ostream& os, const std::string& name, const osgVector4& rgbaDiffuse) { os << varMat << " = bpy.data.materials.new(\"" << name << "\")" << end; writeRGB (os << varMat << ".diffuse_color = ", rgbaDiffuse) << end << varMat << ".diffuse_intensity = " << rgbaDiffuse.a() << end; } template <typename NodeType> void setColor(std::ostream& os, NodeType& node) { writeMaterial(os, node.getID() + "__mat", node.getColor()); os << "bpy.context.object.data.materials.append(" << varMat << ')' << end; } template <> void setColor(std::ostream& os, LeafNodeCollada& node) { osg::Material* mat_ptr = dynamic_cast<osg::Material*> ( node.getOsgNode()->getStateSet()->getAttribute(osg::StateAttribute::MATERIAL)); if (mat_ptr != NULL) { // Color was set by URDF writeMaterial(os, node.getID() + "__mat", mat_ptr, true, false, false); os << "setMaterial (imported_objects, " << varMat << ')' << end; } } } BlenderGeomWriterVisitor::BlenderGeomWriterVisitor (const std::string& filename) : filename_ (filename) { bool isNew = !openFile(); const std::string comment = (isNew ? "" : "# "); out() << comment << "import bpy" << end << end << comment << "## Start convenient functions" << end << comment << "def checkConf():" << end << comment << " if bpy.app.version[0:2] != (2, 75):" << end << comment << " print(\"Using blender version \" + str(bpy.app.version))" << end << comment << " print(\"Developed under version 2.75.0.\")" << end << comment << " return False" << end << comment << " if bpy.context.scene.render.engine != 'CYCLES':" << end << comment << " print(\"Cycles renderer is prefered\")" << end << comment << " return False" << end << comment << " return True" << end << comment << end << comment << "taggedObjects = list()" << end << comment << "def tagObjects ():" << end << comment << " global taggedObjects" << end << comment << " taggedObjects = list ()" << end << comment << " for obj in bpy.data.objects:" << end << comment << " taggedObjects.append (obj.name)" << end << comment << "" << end << comment << "def getNonTaggedObjects ():" << end << comment << " global taggedObjects" << end << comment << " return [obj for obj in bpy.data.objects if obj.name not in taggedObjects]" << end << comment << "" << end << comment << "def setParent (children, parent):" << end << comment << " for child in children:" << end << comment << " child.parent = parent" << end << end << comment << "" << end << comment << "def setMaterial (children, mat):" << end << comment << " for child in children:" << end << comment << " child.data.materials.append(mat)" << end << end << comment << "checkConf()" << end << end << comment << "## End of convenient functions" << end; } bool BlenderGeomWriterVisitor::openFile () { struct stat buffer; bool ret = (stat (filename_.c_str(), &buffer) == 0); file_.open (filename_.c_str(), std::ofstream::out | std::ofstream::app); if (!file_.is_open ()) throw std::ios_base::failure ("Unable to open file " + filename_); return ret; } void BlenderGeomWriterVisitor::apply (Node& node) { std::cerr << "This function should not be called. Type of node " << node.getID() << " may be unknown" << std::endl; standardApply(node); } void BlenderGeomWriterVisitor::apply (GroupNode& node) { for (std::size_t i = 0; i < groupStack_.size() + 1; ++i) out() << group; out() << " Group " << node.getID() << end; out() << "bpy.ops.object.empty_add()" << end << "bpy.context.object.name = \"" << node.getID() << '"' << end; // Set parent of this group if (!groupStack_.empty()) out() << "bpy.context.object.parent = bpy.data.objects[\"" << groupStack_.top() << "\"]" << end; groupStack_.push(node.getID()); NodeVisitor::apply(static_cast<Node&>(node)); groupStack_.pop(); for (std::size_t i = 0; i < groupStack_.size() + 1; ++i) out() << group; out() << end; } void BlenderGeomWriterVisitor::apply (LeafNodeArrow& node) { unimplemented("LeafNodeArrow", node); } void BlenderGeomWriterVisitor::apply (LeafNodeBox& node) { out() << "bpy.ops.mesh.primitive_cube_add ()" << end << "bpy.context.object.dimensions = "; writeVectorAsList(out(), node.getHalfAxis()*2) << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCapsule& node) { unimplemented("LeafNodeCapsule", node); } void BlenderGeomWriterVisitor::apply (LeafNodeCollada& node) { out() << "tagObjects()" << end; const std::string& mesh = node.meshFilePath(); std::string ext = mesh.substr(mesh.find_last_of(".")+1,mesh.size()); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if(ext == "obj") { out() << "bpy.ops.import_scene.obj (filepath=\"" << mesh << "\")" << end; } else if (ext == "dae") { out() << "bpy.ops.wm.collada_import (filepath=\"" << mesh << "\")" << end; } else if (ext == "stl") { out() << "bpy.ops.import_mesh.stl (filepath=\"" << mesh << "\")" << end; } else { std::cout << "Extension of file " << mesh << " with name " << node.getID() << " is not known." << end << "You can load the file manually and add it to the empty object called " << node.getID() << end << "To fix the issue, upate" __FILE__ ":" << __LINE__ << std::endl; out() << "# Here goes the content of file " << mesh << end; out() << "# To fix it, upate" __FILE__ ":" << __LINE__ << end; } out () << "imported_objects = getNonTaggedObjects ()" << end << "print(imported_objects)" << end << "bpy.ops.object.empty_add ()" << end << "setParent (imported_objects, bpy.context.object)" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCone& node) { out() << "bpy.ops.mesh.primitive_cone_add (radius1=" << node.getRadius() << ", depth=" << node.getHeight() << ')' << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeCylinder& node) { out() << "bpy.ops.mesh.primitive_cylinder_add (radius=" << node.getRadius() << ", depth=" << node.getHeight() << ')' << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeFace& node) { unimplemented("LeafNodeFace", node); } void BlenderGeomWriterVisitor::apply (LeafNodeGround& node) { unimplemented("LeafNodeGround", node); } void BlenderGeomWriterVisitor::apply (LeafNodeLight& node) { unimplemented("LeafNodeLight", node); } void BlenderGeomWriterVisitor::apply (LeafNodeLine& node) { ::osg::Vec3ArrayRefPtr points = node.getPoints(); out() << "points = ["; for (std::size_t i = 0; i < points->size(); ++i) writeVectorAsList(out(), points->at(i)) << ','; out() << ']' << end; if (node.getMode() != GL_LINE_STRIP) { out() << warning << "Only GL_LINE_STRIP is supported." << end; } out() << "curve = bpy.data.curves.new(name=\"" << node.getID() << "__curve\", type='CURVE')" << end << "curve.dimensions = '3D'" << end << "curve.fill_mode = 'FULL'" << end << "curve.bevel_depth = 0.01" << end << "curve.bevel_resolution = 10" << end /// define points that make the line << "polyline = curve.splines.new('POLY')" << end << "polyline.points.add(len(points)-1)" << end << "for i in xrange(len(points)):" << end << " polyline.points[i].co = (points[i])+(1.0,)" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeSphere& node) { out () << "bpy.ops.mesh.primitive_ico_sphere_add (size=" << node.getRadius() << ")" << end; setColor(out(), node); standardApply(node); } void BlenderGeomWriterVisitor::apply (LeafNodeXYZAxis& node) { unimplemented("LeafNodeXYZAxis", node); } void BlenderGeomWriterVisitor::standardApply (Node& node) { const std::string& id = node.getID (); // Set name out() << "bpy.context.object.name = \"" << id << "__shape\"" << end << "bpy.context.object.location = "; writeVectorAsList(out(), node.getStaticPosition()) << end; out() << "bpy.context.object.rotation_mode = 'QUATERNION'" << end << "bpy.context.object.rotation_quaternion = "; writeVectorAsList(out(), node.getStaticRotation()) << end; out() << "bpy.ops.object.empty_add ()" << end << "bpy.context.object.name = \"" << id << '"' << end << "bpy.data.objects[\"" << id << "__shape\"].parent = " << "bpy.data.objects[\"" << id << "\"]" << end; // Set parent group if (!groupStack_.empty()) out() << "bpy.context.object.parent = bpy.data.objects[\"" << groupStack_.top() << "\"]" << end; NodeVisitor::apply (node); } void BlenderGeomWriterVisitor::unimplemented(const char* type, Node& node) { std::cout << type << " is not implemented. " << node.getID() << " not added" << std::endl; out() << "bpy.ops.object.empty_add()" << end; standardApply(node); } } // namespace graphics
Fix generation of script to import models into blender
Fix generation of script to import models into blender
C++
bsd-3-clause
olivier-stasse/gepetto-viewer
3f895e98cc642a25585d2f03f9bed170e66cd1ee
engine/thread/Thread.hpp
engine/thread/Thread.hpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_UTILS_THREAD_HPP #define OUZEL_UTILS_THREAD_HPP #include <system_error> #include <thread> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <pthread.h> #endif namespace ouzel::thread { class Thread final { public: Thread() noexcept = default; Thread(const Thread&) = delete; Thread(Thread&& other) noexcept: t(std::move(other.t)) {} Thread(const std::thread&) = delete; Thread(std::thread&& other) noexcept: t(std::move(other)) {} Thread& operator=(const Thread&) = delete; Thread& operator=(Thread&& other) noexcept { t = std::move(other.t); return *this; } Thread& operator=(const std::thread&) = delete; Thread& operator=(std::thread&& other) noexcept { t = std::move(other); return *this; } template <typename Callable, typename... Args> explicit Thread(Callable&& f, Args&&... args): t(std::forward<Callable>(f), std::forward<Args>(args)...) { } ~Thread() { if (t.joinable()) t.join(); } auto isJoinable() const noexcept { return t.joinable(); } auto getId() const noexcept { return t.get_id(); } auto getNativeHandle() { return t.native_handle(); } void join() { t.join(); } void setPriority(float priority, bool realtime) { #if defined(_MSC_VER) static_cast<void>(realtime); static constexpr int priorities[] = { THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)])) throw std::system_error(GetLastError(), std::system_category(), "Failed to set thread name"); #else if (priority < 0.0F) priority = 0.0F; const int policy = realtime ? SCHED_RR : SCHED_OTHER; const int minPriority = sched_get_priority_min(policy); if (minPriority == -1) throw std::system_error(errno, std::system_category(), "Failed to get thread min priority"); const int maxPriority = sched_get_priority_max(policy); if (maxPriority == -1) throw std::system_error(errno, std::system_category(), "Failed to get thread max priority"); sched_param param; param.sched_priority = static_cast<int>(priority * static_cast<float>(maxPriority - minPriority)) + minPriority; const int error = pthread_setschedparam(t.native_handle(), policy, &param); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread priority"); #endif } private: std::thread t; }; inline void setCurrentThreadName(const std::string& name) { #if defined(_MSC_VER) constexpr DWORD MS_VC_EXCEPTION = 0x406D1388; # pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; # pragma pack(pop) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = static_cast<DWORD>(-1); info.dwFlags = 0; const DWORD numberOfArguments = sizeof(info) / sizeof(ULONG_PTR); ULONG_PTR arguments[numberOfArguments]; std::memcpy(arguments, &info, sizeof(info)); __try { RaiseException(MS_VC_EXCEPTION, 0, numberOfArguments, arguments); } __except (EXCEPTION_EXECUTE_HANDLER) { } #else # ifdef __APPLE__ const int error = pthread_setname_np(name.c_str()); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread name"); # elif defined(__linux__) const int error = pthread_setname_np(pthread_self(), name.c_str()); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread name"); # endif #endif } } #endif // OUZEL_UTILS_THREAD_HPP
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_UTILS_THREAD_HPP #define OUZEL_UTILS_THREAD_HPP #include <system_error> #include <thread> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__unix__) || defined(__APPLE__) # include <pthread.h> #endif #include "../utils/Utils.hpp" namespace ouzel::thread { class Thread final { public: Thread() noexcept = default; Thread(const Thread&) = delete; Thread(Thread&& other) noexcept: t(std::move(other.t)) {} Thread(const std::thread&) = delete; Thread(std::thread&& other) noexcept: t(std::move(other)) {} Thread& operator=(const Thread&) = delete; Thread& operator=(Thread&& other) noexcept { t = std::move(other.t); return *this; } Thread& operator=(const std::thread&) = delete; Thread& operator=(std::thread&& other) noexcept { t = std::move(other); return *this; } template <typename Callable, typename... Args> explicit Thread(Callable&& f, Args&&... args): t(std::forward<Callable>(f), std::forward<Args>(args)...) { } ~Thread() { if (t.joinable()) t.join(); } auto isJoinable() const noexcept { return t.joinable(); } auto getId() const noexcept { return t.get_id(); } auto getNativeHandle() { return t.native_handle(); } void join() { t.join(); } void setPriority(float priority, bool realtime) { #if defined(_MSC_VER) static_cast<void>(realtime); static constexpr int priorities[] = { THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; if (!SetThreadPriority(t.native_handle(), priorities[static_cast<std::size_t>((priority + 1.0F) * 6.0F / 2.0F)])) throw std::system_error(GetLastError(), std::system_category(), "Failed to set thread name"); #else if (priority < 0.0F) priority = 0.0F; const int policy = realtime ? SCHED_RR : SCHED_OTHER; const int minPriority = sched_get_priority_min(policy); if (minPriority == -1) throw std::system_error(errno, std::system_category(), "Failed to get thread min priority"); const int maxPriority = sched_get_priority_max(policy); if (maxPriority == -1) throw std::system_error(errno, std::system_category(), "Failed to get thread max priority"); sched_param param; param.sched_priority = static_cast<int>(priority * static_cast<float>(maxPriority - minPriority)) + minPriority; const int error = pthread_setschedparam(t.native_handle(), policy, &param); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread priority"); #endif } private: std::thread t; }; inline void setCurrentThreadName(const std::string& name) { #if defined(_MSC_VER) constexpr DWORD MS_VC_EXCEPTION = 0x406D1388; # pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; # pragma pack(pop) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = static_cast<DWORD>(-1); info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), bitCast<ULONG_PTR*>(&info)); } __except (EXCEPTION_EXECUTE_HANDLER) { } #else # ifdef __APPLE__ const int error = pthread_setname_np(name.c_str()); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread name"); # elif defined(__linux__) const int error = pthread_setname_np(pthread_self(), name.c_str()); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to set thread name"); # endif #endif } } #endif // OUZEL_UTILS_THREAD_HPP
Use bitCast instead of memcpy
Use bitCast instead of memcpy
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
9d08962f6fb6580f5315bf9a69cb485647838b92
waveFrontLoader.cpp
waveFrontLoader.cpp
#include "waveFrontLoader.h" waveFrontLoader::waveFrontLoader() { indexCount = 0; } void waveFrontLoader::loadFile(const char *fileName) { ifstream file; char line[255]; //open file in openframeworks data folder file.open(ofToDataPath(fileName).c_str()); if (file.is_open()) { while (file.getline(line,255)) { parseLine(line); } } } void waveFrontLoader::parseLine(char *line) { //If empty, don't do anything with it if(!strlen(line)) { return; } //get line type identifier from char string char *lineType = strtok(strdup(line), " "); //parse line depending on type if (!strcmp(lineType, "v")) // Vertices { parseVertex(line); } else if (!strcmp(lineType, "vn")) // Normals { parseNormal(line); } else if (!strcmp(lineType, "f")) // Indices (Faces) { parseFace(line); } } void waveFrontLoader::parseVertex(char *line) { float x; float y; float z; vertices.push_back(ofVec3f(x,y,z)); //get coordinates from vertex line and assign sscanf(line, "v %f %f %f", &vertices.back().x, &vertices.back().y, &vertices.back().z); } void waveFrontLoader::parseNormal(char *line) { float x; float y; float z; normals.push_back(ofVec3f(x,y,z)); //get coordinates from normal line and assign sscanf(line, "vn %f %f %f", &normals.back().x, &normals.back().y, &normals.back().z); } void waveFrontLoader::parseFace(char *line) { //var to hold and discard un-needed texture data int discard; indices.push_back(Index()); //get vertex and normal indices, discard texture data for now if(sscanf(line, "f %d//%d %d//%d %d//%d", &indices.back().v1, &indices.back().vn1, &indices.back().v2, &indices.back().vn2, &indices.back().v3, &indices.back().vn3) <= 1) { sscanf(line, "f %d/%d/%d %d/%d/%d %d/%d/%d", &indices.back().v1, &discard, &indices.back().vn1, &indices.back().v2, &discard, &indices.back().vn2, &indices.back().v3, &discard, &indices.back().vn3); } } ofMesh waveFrontLoader::generateMesh() { for (std::vector<Index>::iterator i = indices.begin(); i != indices.end(); ++i) { //check if the vertex and normal location exists already addFace(&vertices[(i->v1) - 1], &normals[(i->vn1) - 1]); addFace(&vertices[(i->v2) - 1], &normals[(i->vn2) - 1]); addFace(&vertices[(i->v3) - 1], &normals[(i->vn3) - 1]); } return mesh; } void waveFrontLoader::addFace(ofVec3f *vertex, ofVec3f *normal) { //temp vars int vertIndex; int normIndex; //check if this vertex exists already std::map<int,ofVec3f>::iterator faceIt; for (faceIt = faceVertices.begin(); faceIt != faceVertices.end(); ++faceIt) { if (faceIt->second == *vertex) { vertIndex = faceIt->first; } } //check if this normal exists already std::map<int,ofVec3f>::iterator normIt; for (normIt = faceNormals.begin(); normIt != faceNormals.end(); ++normIt) { if (normIt->second == *normal) { normIndex = normIt->first; } } //if a vertex and normal exist at this position, use those aready created //otherwise, add new if (vertIndex == normIndex) { mesh.addIndex(vertIndex); } else { int currentIndex = indexCount++; //add vertex mesh.addVertex(*vertex); faceVertices[currentIndex] = *vertex; //add normal mesh.addNormal(*normal); faceNormals[currentIndex] = *normal; //add index mesh.addIndex(currentIndex); } } waveFrontLoader::~waveFrontLoader() { // }
#include "waveFrontLoader.h" waveFrontLoader::waveFrontLoader() { indexCount = 0; faceCount = 0; materialColorCount = 0; materialCount = 0; materialBool = false; } void waveFrontLoader::loadFile(const char *fileName) { //if we're using a material file, load it if (materialBool == true) { ifstream matFile; char matLine[255]; char materialFile[255]; strncpy(materialFile, fileName, sizeof(materialFile)); strncat(materialFile, ".mtl", sizeof(materialFile) - strlen(materialFile) - 1); //open file in openframeworks data folder matFile.open(ofToDataPath(materialFile).c_str()); if (matFile.is_open()) { while (matFile.getline(matLine, 255)) { parseMaterial(matLine); } } matFile.close(); } //get filename and open corresponding .obj file ifstream objFile; char line[255]; char objectFile[255]; strncpy(objectFile, fileName, sizeof(objectFile)); strncat(objectFile, ".obj", sizeof(objectFile) - strlen(objectFile) - 1); //open file in openframeworks data folder objFile.open(ofToDataPath(objectFile).c_str()); if (objFile.is_open()) { while (objFile.getline(line,255)) { parseLine(line); } } objFile.close(); } void waveFrontLoader::loadMaterial(bool load) { if (load == true) { materialBool = true; } else { materialBool = false; } } void waveFrontLoader::parseLine(char *line) { //If empty, don't do anything with it if(!strlen(line)) { return; } //get line type identifier from char string char *lineType = strtok(strdup(line), " "); //parse line depending on type if (!strcmp(lineType, "usemtl")) // Use Material { parseMaterialLocation(line); } else if (!strcmp(lineType, "v")) // Vertices { parseVertex(line); } else if (!strcmp(lineType, "vn")) // Normals { parseNormal(line); } else if (!strcmp(lineType, "f")) // Indices (Faces) { parseFace(line); } } void waveFrontLoader::parseVertex(char *line) { float x; float y; float z; vertices.push_back(ofVec3f(x,y,z)); //get coordinates from vertex line and assign sscanf(line, "v %f %f %f", &vertices.back().x, &vertices.back().y, &vertices.back().z); } void waveFrontLoader::parseNormal(char *line) { float x; float y; float z; normals.push_back(ofVec3f(x,y,z)); //get coordinates from normal line and assign sscanf(line, "vn %f %f %f", &normals.back().x, &normals.back().y, &normals.back().z); } void waveFrontLoader::parseFace(char *line) { //var to hold and discard un-needed texture data int discard; faceCount++; indices.push_back(Index()); //get vertex and normal indices, discard texture data for now if(sscanf(line, "f %d//%d %d//%d %d//%d", &indices.back().v1, &indices.back().vn1, &indices.back().v2, &indices.back().vn2, &indices.back().v3, &indices.back().vn3) <= 1) { sscanf(line, "f %d/%d/%d %d/%d/%d %d/%d/%d", &indices.back().v1, &discard, &indices.back().vn1, &indices.back().v2, &discard, &indices.back().vn2, &indices.back().v3, &discard, &indices.back().vn3); } } void waveFrontLoader::parseMaterialLocation(char *line) { materialCount++; char materialName[255]; sscanf(line, "usemtl %s", materialName); materialLocations[faceCount] = materialName; } void waveFrontLoader::parseMaterial(char *line) { //If empty, don't do anything with it if(!strlen(line)) { return; } //get line type identifier from char string char *lineType = strtok(strdup(line), " "); if (!strcmp(lineType, "newmtl")) // Material Name { sscanf(line, "newmtl %s", tempMatName); materialColorCount++; } else if (!strcmp(lineType, "Ka")) // Ambient Color { sscanf(line, "Ka %f %f %f", &tempColor.ambientColor.r, &tempColor.ambientColor.g, &tempColor.ambientColor.b); } else if (!strcmp(lineType, "Kd")) // Diffuse Color { sscanf(line, "Kd %f %f %f", &tempColor.diffuseColor.r, &tempColor.diffuseColor.g, &tempColor.diffuseColor.b); } else if (!strcmp(lineType, "Ks")) // Specular Color { sscanf(line, "Ks %f %f %f", &tempColor.specularColor.r, &tempColor.specularColor.g, &tempColor.specularColor.b); } else if (!strcmp(lineType, "d")) // Alpha { sscanf(line, "d %f", &tempColor.alpha); } else if (!strcmp(lineType, "illum")) // End of material signifier { //it's the end of this material, so add to material map, and reset vars materialColors[tempMatName] = tempColor; tempColor = emptyColor; } } ofMesh waveFrontLoader::generateMesh() { int materialCount = materialColors.size(); int localIndexCount = 0; ofColor vertColor; ofColor defaultColor = ofColor(0.0, 255.0, 0.0); for (std::vector<Index>::iterator i = indices.begin(); i != indices.end(); ++i) { if (materialLocations[localIndexCount] != "") { vertColor = mapColor(materialColors[materialLocations[localIndexCount]].diffuseColor); } //draw triangles addFace(&vertices[(i->v1) - 1], &normals[(i->vn1) - 1], &vertColor); addFace(&vertices[(i->v2) - 1], &normals[(i->vn2) - 1], &vertColor); addFace(&vertices[(i->v3) - 1], &normals[(i->vn3) - 1], &vertColor); localIndexCount++; } return mesh; } void waveFrontLoader::addFace(ofVec3f *vertex, ofVec3f *normal, ofColor *color) { //temp vars int vertIndex; int normIndex; //check if this vertex exists already std::map<int,ofVec3f>::iterator faceIt; for (faceIt = faceVertices.begin(); faceIt != faceVertices.end(); ++faceIt) { if (faceIt->second == *vertex) { vertIndex = faceIt->first; } } //check if this normal exists already std::map<int,ofVec3f>::iterator normIt; for (normIt = faceNormals.begin(); normIt != faceNormals.end(); ++normIt) { if (normIt->second == *normal) { normIndex = normIt->first; } } //if a vertex and normal exist at this position, use those aready created //otherwise, add new if (vertIndex == normIndex) { mesh.addIndex(vertIndex); } else { int currentIndex = indexCount++; //add vertex mesh.addVertex(*vertex); faceVertices[currentIndex] = *vertex; //add color mesh.addColor(*color); //add normal mesh.addNormal(*normal); faceNormals[currentIndex] = *normal; //add index mesh.addIndex(currentIndex); } } ofColor waveFrontLoader::mapColor(colorRGB vertexColor) { float red = ofMap(vertexColor.r, 0.0, 1.0, 0.0, 255.0); float green = ofMap(vertexColor.g, 0.0, 1.0, 0.0, 255.0); float blue = ofMap(vertexColor.b, 0.0, 1.0, 0.0, 255.0); ofColor newColor = ofColor(red, green, blue); return newColor; } waveFrontLoader::~waveFrontLoader() { // }
Update waveFrontLoader.cpp
Update waveFrontLoader.cpp added ability to parse and use .mtl files
C++
mit
section14/openframeworks-WaveFront-obj-loader
c563fca438b6039c187d55ce54c6c7944960daf3
lib/Target/ARM/ARMMachineFunctionInfo.cpp
lib/Target/ARM/ARMMachineFunctionInfo.cpp
//===-- ARMMachineFunctionInfo.cpp - ARM machine function info ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ARMMachineFunctionInfo.h" using namespace llvm; void ARMFunctionInfo::anchor() {} ARMFunctionInfo::ARMFunctionInfo(MachineFunction &MF) : isThumb(MF.getSubtarget<ARMSubtarget>().isThumb()), hasThumb2(MF.getSubtarget<ARMSubtarget>().hasThumb2()), StByValParamsPadding(0), ArgRegsSaveSize(0), HasStackFrame(false), RestoreSPFromFP(false), LRSpilledForFarJump(false), FramePtrSpillOffset(0), GPRCS1Offset(0), GPRCS2Offset(0), DPRCSOffset(0), GPRCS1Size(0), GPRCS2Size(0), DPRCSSize(0), PICLabelUId(0), VarArgsFrameIndex(0), HasITBlocks(false), ArgumentStackSize(0), IsSplitCSR(false), PromotedGlobalsIncrease(0) {}
//===-- ARMMachineFunctionInfo.cpp - ARM machine function info ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ARMMachineFunctionInfo.h" using namespace llvm; void ARMFunctionInfo::anchor() {} ARMFunctionInfo::ARMFunctionInfo(MachineFunction &MF) : isThumb(MF.getSubtarget<ARMSubtarget>().isThumb()), hasThumb2(MF.getSubtarget<ARMSubtarget>().hasThumb2()), StByValParamsPadding(0), ArgRegsSaveSize(0), ReturnRegsCount(0), HasStackFrame(false), RestoreSPFromFP(false), LRSpilledForFarJump(false), FramePtrSpillOffset(0), GPRCS1Offset(0), GPRCS2Offset(0), DPRCSOffset(0), GPRCS1Size(0), GPRCS2Size(0), DPRCSSize(0), PICLabelUId(0), VarArgsFrameIndex(0), HasITBlocks(false), ArgumentStackSize(0), IsSplitCSR(false), PromotedGlobalsIncrease(0) {}
Add an initializer of ARMFunctionInfo::ReturnRegsCount in the explicit ctor.
ARMMachineFunctionInfo.cpp: Add an initializer of ARMFunctionInfo::ReturnRegsCount in the explicit ctor. It caused crash since r283867. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@283909 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm
9240ba213833bbbcef5c43d5f014dde9ec8264f1
generator/road_access_generator.cpp
generator/road_access_generator.cpp
#include "generator/road_access_generator.hpp" #include "generator/routing_helpers.hpp" #include "routing/road_access.hpp" #include "routing/road_access_serialization.hpp" #include "indexer/classificator.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/features_vector.hpp" #include "coding/file_container.hpp" #include "coding/file_writer.hpp" #include "base/geo_object_id.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include <initializer_list> #include "defines.hpp" #include <algorithm> #include <utility> using namespace routing; using namespace std; namespace { char constexpr kDelim[] = " \t\r\n"; using TagMapping = routing::RoadAccessTagProcessor::TagMapping; TagMapping const kMotorCarTagMapping = { {OsmElement::Tag("motorcar", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motorcar", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motorcar", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motorcar", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kMotorVehicleTagMapping = { {OsmElement::Tag("motor_vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motor_vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motor_vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motor_vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kVehicleTagMapping = { {OsmElement::Tag("vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kCarBarriersTagMapping = { {OsmElement::Tag("barrier", "block"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "bollard"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "chain"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "jersey_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "lift_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "log"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "motorcycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "swing_gate"), RoadAccess::Type::Private}, }; TagMapping const kPedestrianTagMapping = { {OsmElement::Tag("foot", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("foot", "no"), RoadAccess::Type::No}, {OsmElement::Tag("foot", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("foot", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleTagMapping = { {OsmElement::Tag("bicycle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("bicycle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("bicycle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("bicycle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleBarriersTagMapping = { {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "turnstile"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "kissing_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, }; // Allow everything to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. TagMapping const kTransitTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Yes}, }; TagMapping const kDefaultTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::No}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Destination}, }; bool ParseRoadAccess(string const & roadAccessPath, map<base::GeoObjectId, uint32_t> const & osmIdToFeatureId, FeaturesVector const & featuresVector, RoadAccessCollector::RoadAccessByVehicleType & roadAccessByVehicleType) { ifstream stream(roadAccessPath); if (!stream) { LOG(LWARNING, ("Could not open", roadAccessPath)); return false; } vector<uint32_t> privateRoads; map<uint32_t, RoadAccess::Type> featureType[static_cast<size_t>(VehicleType::Count)]; map<RoadPoint, RoadAccess::Type> pointType[static_cast<size_t>(VehicleType::Count)]; auto addFeature = [&](uint32_t featureId, VehicleType vehicleType, RoadAccess::Type roadAccessType, uint64_t osmId) { auto & m = featureType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(featureId, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for OSM way", osmId, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; auto addPoint = [&](RoadPoint const & point, VehicleType vehicleType, RoadAccess::Type roadAccessType) { auto & m = pointType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(point, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for road point", point, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; string line; for (uint32_t lineNo = 1;; ++lineNo) { if (!getline(stream, line)) break; strings::SimpleTokenizer iter(line, kDelim); if (!iter) { LOG(LERROR, ("Error when parsing road access: empty line", lineNo)); return false; } VehicleType vehicleType; FromString(*iter, vehicleType); ++iter; if (!iter) { LOG(LERROR, ("Error when parsing road access: no road access type at line", lineNo, "Line contents:", line)); return false; } RoadAccess::Type roadAccessType; FromString(*iter, roadAccessType); ++iter; uint64_t osmId; if (!iter || !strings::to_uint64(*iter, osmId)) { LOG(LERROR, ("Error when parsing road access: bad osm id at line", lineNo, "Line contents:", line)); return false; } ++iter; uint32_t pointIdx; if (!iter || !strings::to_uint(*iter, pointIdx)) { LOG(LERROR, ("Error when parsing road access: bad pointIdx at line", lineNo, "Line contents:", line)); return false; } ++iter; auto const it = osmIdToFeatureId.find(base::MakeOsmWay(osmId)); // Even though this osm element has a tag that is interesting for us, // we have not created a feature from it. Possible reasons: // no primary tag, unsupported type, etc. if (it == osmIdToFeatureId.cend()) continue; uint32_t const featureId = it->second; if (pointIdx == 0) addFeature(featureId, vehicleType, roadAccessType, osmId); else addPoint(RoadPoint(featureId, pointIdx - 1), vehicleType, roadAccessType); } for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) roadAccessByVehicleType[i].SetAccessTypes(move(featureType[i]), move(pointType[i])); return true; } // If |elem| has access tag from |mapping|, returns corresponding RoadAccess::Type. // Tags in |mapping| should be mutually exclusive. Caller is responsible for that. If there are // multiple access tags from |mapping| in |elem|, returns RoadAccess::Type for any of them. // Returns RoadAccess::Type::Count if |elem| has no access tags from |mapping|. RoadAccess::Type GetAccessTypeFromMapping(OsmElement const & elem, TagMapping const * mapping) { for (auto const & tag : elem.m_tags) { auto const it = mapping->find(tag); if (it != mapping->cend()) return it->second; } return RoadAccess::Type::Count; } } // namespace namespace routing { // RoadAccessTagProcessor -------------------------------------------------------------------------- RoadAccessTagProcessor::RoadAccessTagProcessor(VehicleType vehicleType) : m_vehicleType(vehicleType) { switch (vehicleType) { case VehicleType::Car: m_tagMappings.push_back(&kMotorCarTagMapping); m_tagMappings.push_back(&kMotorVehicleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {vehicle = ...}, {access = ...} etc. m_tagMappings.push_back(&kCarBarriersTagMapping); break; case VehicleType::Pedestrian: m_tagMappings.push_back(&kPedestrianTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); break; case VehicleType::Bicycle: m_tagMappings.push_back(&kBicycleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {bicycle = ...}, {access = ...} etc. m_tagMappings.push_back(&kBicycleBarriersTagMapping); break; case VehicleType::Transit: // Use kTransitTagMapping to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. m_tagMappings.push_back(&kTransitTagMapping); break; case VehicleType::Count: CHECK(false, ("Bad vehicle type")); break; } } void RoadAccessTagProcessor::Process(OsmElement const & elem, ofstream & oss) { // We will proccess all nodes before ways because of o5m format: // all nodes are first, then all ways, then all relations. if (elem.type == OsmElement::EntityType::Node) { RoadAccess::Type accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) m_barriers[elem.id] = accessType; return; } if (elem.type != OsmElement::EntityType::Way) return; // All feature tags. auto const accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) oss << ToString(m_vehicleType) << " " << ToString(accessType) << " " << elem.id << " " << 0 /* wildcard segment Idx */ << endl; // Barrier tags. for (size_t pointIdx = 0; pointIdx < elem.m_nds.size(); ++pointIdx) { auto const it = m_barriers.find(elem.m_nds[pointIdx]); if (it == m_barriers.cend()) continue; // idx == 0 used as wildcard segment Idx, for nodes we store |pointIdx + 1| instead of |pointIdx|. oss << ToString(m_vehicleType) << " " << ToString(it->second) << " " << elem.id << " " << pointIdx + 1 << endl; } } RoadAccess::Type RoadAccessTagProcessor::GetAccessType(OsmElement const & elem) const { for (auto const tagMapping : m_tagMappings) { auto const accessType = GetAccessTypeFromMapping(elem, tagMapping); if (accessType != RoadAccess::Type::Count) return accessType; } return RoadAccess::Type::Yes; } // RoadAccessWriter ------------------------------------------------------------ RoadAccessWriter::RoadAccessWriter() { for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) m_tagProcessors.emplace_back(static_cast<VehicleType>(i)); } void RoadAccessWriter::Open(string const & filePath) { LOG(LINFO, ("Saving information about barriers and road access classes in osm id terms to", filePath)); m_stream.open(filePath, ofstream::out); if (!IsOpened()) LOG(LINFO, ("Cannot open file", filePath)); } void RoadAccessWriter::Process(OsmElement const & elem) { if (!IsOpened()) { LOG(LWARNING, ("Tried to write to a closed barriers writer")); return; } for (auto & p : m_tagProcessors) p.Process(elem, m_stream); } bool RoadAccessWriter::IsOpened() const { return m_stream && m_stream.is_open(); } // RoadAccessCollector ---------------------------------------------------------- RoadAccessCollector::RoadAccessCollector(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { map<base::GeoObjectId, uint32_t> osmIdToFeatureId; if (!ParseOsmIdToFeatureIdMapping(osmIdsToFeatureIdsPath, osmIdToFeatureId)) { LOG(LWARNING, ("An error happened while parsing feature id to osm ids mapping from file:", osmIdsToFeatureIdsPath)); m_valid = false; return; } FeaturesVectorTest featuresVector(dataFilePath); RoadAccessCollector::RoadAccessByVehicleType roadAccessByVehicleType; if (!ParseRoadAccess(roadAccessPath, osmIdToFeatureId, featuresVector.GetVector(), roadAccessByVehicleType)) { LOG(LWARNING, ("An error happened while parsing road access from file:", roadAccessPath)); m_valid = false; return; } m_valid = true; m_roadAccessByVehicleType.swap(roadAccessByVehicleType); } // Functions ------------------------------------------------------------------ void BuildRoadAccessInfo(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { LOG(LINFO, ("Generating road access info for", dataFilePath)); RoadAccessCollector collector(dataFilePath, roadAccessPath, osmIdsToFeatureIdsPath); if (!collector.IsValid()) { LOG(LWARNING, ("Unable to parse road access in osm terms")); return; } FilesContainerW cont(dataFilePath, FileWriter::OP_WRITE_EXISTING); FileWriter writer = cont.GetWriter(ROAD_ACCESS_FILE_TAG); RoadAccessSerializer::Serialize(writer, collector.GetRoadAccessAllTypes()); } } // namespace routing
#include "generator/road_access_generator.hpp" #include "generator/routing_helpers.hpp" #include "routing/road_access.hpp" #include "routing/road_access_serialization.hpp" #include "indexer/classificator.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/features_vector.hpp" #include "coding/file_container.hpp" #include "coding/file_writer.hpp" #include "base/geo_object_id.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include <initializer_list> #include "defines.hpp" #include <algorithm> #include <utility> using namespace routing; using namespace std; namespace { char constexpr kDelim[] = " \t\r\n"; using TagMapping = routing::RoadAccessTagProcessor::TagMapping; TagMapping const kMotorCarTagMapping = { {OsmElement::Tag("motorcar", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motorcar", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("motorcar", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motorcar", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motorcar", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kMotorVehicleTagMapping = { {OsmElement::Tag("motor_vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motor_vehicle", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("motor_vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motor_vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motor_vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kVehicleTagMapping = { {OsmElement::Tag("vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("vehicle", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kCarBarriersTagMapping = { {OsmElement::Tag("barrier", "block"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "bollard"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "chain"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "jersey_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "lift_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "log"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "motorcycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "swing_gate"), RoadAccess::Type::Private}, }; TagMapping const kPedestrianTagMapping = { {OsmElement::Tag("foot", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("foot", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("foot", "no"), RoadAccess::Type::No}, {OsmElement::Tag("foot", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("foot", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleTagMapping = { {OsmElement::Tag("bicycle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("bicycle", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("bicycle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("bicycle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("bicycle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleBarriersTagMapping = { {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "turnstile"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "kissing_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, }; // Allow everything to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. TagMapping const kTransitTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Yes}, }; TagMapping const kDefaultTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "permissive"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::No}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Destination}, }; bool ParseRoadAccess(string const & roadAccessPath, map<base::GeoObjectId, uint32_t> const & osmIdToFeatureId, FeaturesVector const & featuresVector, RoadAccessCollector::RoadAccessByVehicleType & roadAccessByVehicleType) { ifstream stream(roadAccessPath); if (!stream) { LOG(LWARNING, ("Could not open", roadAccessPath)); return false; } vector<uint32_t> privateRoads; map<uint32_t, RoadAccess::Type> featureType[static_cast<size_t>(VehicleType::Count)]; map<RoadPoint, RoadAccess::Type> pointType[static_cast<size_t>(VehicleType::Count)]; auto addFeature = [&](uint32_t featureId, VehicleType vehicleType, RoadAccess::Type roadAccessType, uint64_t osmId) { auto & m = featureType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(featureId, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for OSM way", osmId, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; auto addPoint = [&](RoadPoint const & point, VehicleType vehicleType, RoadAccess::Type roadAccessType) { auto & m = pointType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(point, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for road point", point, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; string line; for (uint32_t lineNo = 1;; ++lineNo) { if (!getline(stream, line)) break; strings::SimpleTokenizer iter(line, kDelim); if (!iter) { LOG(LERROR, ("Error when parsing road access: empty line", lineNo)); return false; } VehicleType vehicleType; FromString(*iter, vehicleType); ++iter; if (!iter) { LOG(LERROR, ("Error when parsing road access: no road access type at line", lineNo, "Line contents:", line)); return false; } RoadAccess::Type roadAccessType; FromString(*iter, roadAccessType); ++iter; uint64_t osmId; if (!iter || !strings::to_uint64(*iter, osmId)) { LOG(LERROR, ("Error when parsing road access: bad osm id at line", lineNo, "Line contents:", line)); return false; } ++iter; uint32_t pointIdx; if (!iter || !strings::to_uint(*iter, pointIdx)) { LOG(LERROR, ("Error when parsing road access: bad pointIdx at line", lineNo, "Line contents:", line)); return false; } ++iter; auto const it = osmIdToFeatureId.find(base::MakeOsmWay(osmId)); // Even though this osm element has a tag that is interesting for us, // we have not created a feature from it. Possible reasons: // no primary tag, unsupported type, etc. if (it == osmIdToFeatureId.cend()) continue; uint32_t const featureId = it->second; if (pointIdx == 0) addFeature(featureId, vehicleType, roadAccessType, osmId); else addPoint(RoadPoint(featureId, pointIdx - 1), vehicleType, roadAccessType); } for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) roadAccessByVehicleType[i].SetAccessTypes(move(featureType[i]), move(pointType[i])); return true; } // If |elem| has access tag from |mapping|, returns corresponding RoadAccess::Type. // Tags in |mapping| should be mutually exclusive. Caller is responsible for that. If there are // multiple access tags from |mapping| in |elem|, returns RoadAccess::Type for any of them. // Returns RoadAccess::Type::Count if |elem| has no access tags from |mapping|. RoadAccess::Type GetAccessTypeFromMapping(OsmElement const & elem, TagMapping const * mapping) { for (auto const & tag : elem.m_tags) { auto const it = mapping->find(tag); if (it != mapping->cend()) return it->second; } return RoadAccess::Type::Count; } } // namespace namespace routing { // RoadAccessTagProcessor -------------------------------------------------------------------------- RoadAccessTagProcessor::RoadAccessTagProcessor(VehicleType vehicleType) : m_vehicleType(vehicleType) { switch (vehicleType) { case VehicleType::Car: m_tagMappings.push_back(&kMotorCarTagMapping); m_tagMappings.push_back(&kMotorVehicleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {vehicle = ...}, {access = ...} etc. m_tagMappings.push_back(&kCarBarriersTagMapping); break; case VehicleType::Pedestrian: m_tagMappings.push_back(&kPedestrianTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); break; case VehicleType::Bicycle: m_tagMappings.push_back(&kBicycleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {bicycle = ...}, {access = ...} etc. m_tagMappings.push_back(&kBicycleBarriersTagMapping); break; case VehicleType::Transit: // Use kTransitTagMapping to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. m_tagMappings.push_back(&kTransitTagMapping); break; case VehicleType::Count: CHECK(false, ("Bad vehicle type")); break; } } void RoadAccessTagProcessor::Process(OsmElement const & elem, ofstream & oss) { // We will proccess all nodes before ways because of o5m format: // all nodes are first, then all ways, then all relations. if (elem.type == OsmElement::EntityType::Node) { RoadAccess::Type accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) m_barriers[elem.id] = accessType; return; } if (elem.type != OsmElement::EntityType::Way) return; // All feature tags. auto const accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) oss << ToString(m_vehicleType) << " " << ToString(accessType) << " " << elem.id << " " << 0 /* wildcard segment Idx */ << endl; // Barrier tags. for (size_t pointIdx = 0; pointIdx < elem.m_nds.size(); ++pointIdx) { auto const it = m_barriers.find(elem.m_nds[pointIdx]); if (it == m_barriers.cend()) continue; // idx == 0 used as wildcard segment Idx, for nodes we store |pointIdx + 1| instead of |pointIdx|. oss << ToString(m_vehicleType) << " " << ToString(it->second) << " " << elem.id << " " << pointIdx + 1 << endl; } } RoadAccess::Type RoadAccessTagProcessor::GetAccessType(OsmElement const & elem) const { for (auto const tagMapping : m_tagMappings) { auto const accessType = GetAccessTypeFromMapping(elem, tagMapping); if (accessType != RoadAccess::Type::Count) return accessType; } return RoadAccess::Type::Yes; } // RoadAccessWriter ------------------------------------------------------------ RoadAccessWriter::RoadAccessWriter() { for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) m_tagProcessors.emplace_back(static_cast<VehicleType>(i)); } void RoadAccessWriter::Open(string const & filePath) { LOG(LINFO, ("Saving information about barriers and road access classes in osm id terms to", filePath)); m_stream.open(filePath, ofstream::out); if (!IsOpened()) LOG(LINFO, ("Cannot open file", filePath)); } void RoadAccessWriter::Process(OsmElement const & elem) { if (!IsOpened()) { LOG(LWARNING, ("Tried to write to a closed barriers writer")); return; } for (auto & p : m_tagProcessors) p.Process(elem, m_stream); } bool RoadAccessWriter::IsOpened() const { return m_stream && m_stream.is_open(); } // RoadAccessCollector ---------------------------------------------------------- RoadAccessCollector::RoadAccessCollector(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { map<base::GeoObjectId, uint32_t> osmIdToFeatureId; if (!ParseOsmIdToFeatureIdMapping(osmIdsToFeatureIdsPath, osmIdToFeatureId)) { LOG(LWARNING, ("An error happened while parsing feature id to osm ids mapping from file:", osmIdsToFeatureIdsPath)); m_valid = false; return; } FeaturesVectorTest featuresVector(dataFilePath); RoadAccessCollector::RoadAccessByVehicleType roadAccessByVehicleType; if (!ParseRoadAccess(roadAccessPath, osmIdToFeatureId, featuresVector.GetVector(), roadAccessByVehicleType)) { LOG(LWARNING, ("An error happened while parsing road access from file:", roadAccessPath)); m_valid = false; return; } m_valid = true; m_roadAccessByVehicleType.swap(roadAccessByVehicleType); } // Functions ------------------------------------------------------------------ void BuildRoadAccessInfo(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { LOG(LINFO, ("Generating road access info for", dataFilePath)); RoadAccessCollector collector(dataFilePath, roadAccessPath, osmIdsToFeatureIdsPath); if (!collector.IsValid()) { LOG(LWARNING, ("Unable to parse road access in osm terms")); return; } FilesContainerW cont(dataFilePath, FileWriter::OP_WRITE_EXISTING); FileWriter writer = cont.GetWriter(ROAD_ACCESS_FILE_TAG); RoadAccessSerializer::Serialize(writer, collector.GetRoadAccessAllTypes()); } } // namespace routing
Allow road access for access=permissive
[routing][generator] Allow road access for access=permissive
C++
apache-2.0
matsprea/omim,rokuz/omim,bykoianko/omim,rokuz/omim,darina/omim,mapsme/omim,milchakov/omim,mpimenov/omim,ygorshenin/omim,rokuz/omim,milchakov/omim,rokuz/omim,mpimenov/omim,mpimenov/omim,matsprea/omim,alexzatsepin/omim,milchakov/omim,alexzatsepin/omim,mpimenov/omim,rokuz/omim,bykoianko/omim,VladiMihaylenko/omim,bykoianko/omim,mapsme/omim,mpimenov/omim,VladiMihaylenko/omim,ygorshenin/omim,mpimenov/omim,alexzatsepin/omim,bykoianko/omim,VladiMihaylenko/omim,rokuz/omim,VladiMihaylenko/omim,darina/omim,darina/omim,ygorshenin/omim,bykoianko/omim,milchakov/omim,mapsme/omim,milchakov/omim,mapsme/omim,darina/omim,VladiMihaylenko/omim,darina/omim,ygorshenin/omim,milchakov/omim,rokuz/omim,matsprea/omim,milchakov/omim,mapsme/omim,darina/omim,matsprea/omim,alexzatsepin/omim,VladiMihaylenko/omim,mapsme/omim,milchakov/omim,VladiMihaylenko/omim,rokuz/omim,matsprea/omim,mapsme/omim,bykoianko/omim,milchakov/omim,mpimenov/omim,ygorshenin/omim,alexzatsepin/omim,VladiMihaylenko/omim,ygorshenin/omim,ygorshenin/omim,mpimenov/omim,ygorshenin/omim,rokuz/omim,bykoianko/omim,VladiMihaylenko/omim,alexzatsepin/omim,mpimenov/omim,alexzatsepin/omim,alexzatsepin/omim,matsprea/omim,rokuz/omim,milchakov/omim,mapsme/omim,VladiMihaylenko/omim,alexzatsepin/omim,VladiMihaylenko/omim,rokuz/omim,ygorshenin/omim,ygorshenin/omim,darina/omim,bykoianko/omim,bykoianko/omim,ygorshenin/omim,milchakov/omim,matsprea/omim,ygorshenin/omim,matsprea/omim,mpimenov/omim,darina/omim,VladiMihaylenko/omim,mapsme/omim,rokuz/omim,darina/omim,mapsme/omim,mpimenov/omim,milchakov/omim,mapsme/omim,bykoianko/omim,alexzatsepin/omim,darina/omim,darina/omim,mpimenov/omim,milchakov/omim,alexzatsepin/omim,mapsme/omim,bykoianko/omim,alexzatsepin/omim,alexzatsepin/omim,matsprea/omim,bykoianko/omim,bykoianko/omim,matsprea/omim,rokuz/omim,VladiMihaylenko/omim,mapsme/omim,darina/omim,darina/omim,mpimenov/omim
b1de553f78e5a83e3684e9ff1603a298ce84738b
apps/evmc/memcache_client_pool.cc
apps/evmc/memcache_client_pool.cc
#include "memcache_client_pool.h" #include "vbucket_config.h" #include "evpp/event_loop_thread_pool.h" #include "likely.h" namespace evmc { #define GET_FILTER_KEY_POS(name, key) \ name = key.find(key_filter_[0]); \ if (name == std::string::npos) { \ name = key.size(); \ } #define SET_SERVERID(vbucket,command) \ MultiModeVbucketConfig* vbconf = vbucket_config(); \ uint16_t server_id = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); \ command->set_server_id(server_id); \ MemcacheClientPool::~MemcacheClientPool() { } void MemcacheClientPool::Stop(bool wait_thread_exit) { loop_pool_.Stop(wait_thread_exit); MemcacheClientBase::Stop(); } bool MemcacheClientPool::Start() { bool ok = loop_pool_.Start(true); if (UNLIKELY(!ok)) { LOG_ERROR << "loop pool start failed"; return false; } if (!MemcacheClientBase::Start(true)) { loop_pool_.Stop(true); LOG_ERROR << "vbucket init failed"; return false; } auto server_list = vbucket_config()->server_list(); // 须先构造memc_client_map_数组,再各个元素取地址,否则地址不稳定,可能崩溃 for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) { memc_client_map_.emplace_back(MemcClientMap()); evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i); for (size_t svr = 0; svr < server_list.size(); ++svr) { auto & client_map = memc_client_map_.back(); BuilderMemClient(loop, server_list[svr], client_map, timeout_ms_); } } for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) { evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i); loop->set_context(evpp::Any(&memc_client_map_[i])); } return ok; } void MemcacheClientPool::Set(evpp::EventLoop* caller_loop, const std::string& key, const std::string& value, uint32_t flags, uint32_t expire, SetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<SetCommand>(caller_loop, vbucket, key, value, flags, expire, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::Remove(evpp::EventLoop* caller_loop, const std::string& key, RemoveCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<RemoveCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::Get(evpp::EventLoop* caller_loop, const std::string& key, GetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<GetCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::PrefixGet(evpp::EventLoop* caller_loop, const std::string& key, PrefixGetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<PrefixGetCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::RunBackGround(const std::function<void(void)>& fun) { auto loop = loop_pool_.GetNextLoopWithHash(rand()); loop->RunInLoop(fun); } void MemcacheClientPool::MultiGet(evpp::EventLoop* caller_loop, std::vector<std::string>& keys, MultiGetCallback& callback) { if (UNLIKELY(keys.size() <= 0)) { MultiGetResult result; caller_loop->RunInLoop(std::bind(callback, std::move(result))); return; } const std::size_t size = keys.size(); std::map<uint16_t, IdInfo> serverid_keys; MultiModeVbucketConfig* vbconf = vbucket_config(); uint16_t vbucket = 0; uint16_t server_id = 0; MultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<MultiGetResult, MultiGetCallback> > (callback); auto& result = handler->get_result(); std::size_t pos = 0; std::vector<int> serverid_table(vbconf->server_list().size(), -1); for (size_t i = 0; i < size; ++i) { auto &key = keys[i]; GET_FILTER_KEY_POS(pos, key) vbucket = vbconf->GetVbucketByKey(key.c_str(), pos); server_id = vbconf->SelectServerFirstId(vbucket); if(serverid_table[server_id] == -1) { serverid_table[server_id] = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); } server_id = serverid_table[server_id]; auto& item = serverid_keys[server_id]; item.keys.emplace_back(key); item.vbuckets.emplace_back(vbucket); result.emplace(std::move(key), std::move(GetResult())); } handler->set_serverid_keys(serverid_keys); auto& serverid_keys_d = handler->get_serverid_keys(); for(auto& it : serverid_keys_d) { server_id = it.first; CommandPtr command = std::make_shared<MultiGetCommand>(caller_loop, server_id, handler); command->set_server_id(server_id); LaunchCommand(command); } } void MemcacheClientPool::PrefixMultiGet(evpp::EventLoop* caller_loop, std::vector<std::string>& keys, PrefixMultiGetCallback callback) { if (UNLIKELY(keys.size() <= 0)) { PrefixMultiGetResult result; caller_loop->RunInLoop(std::bind(callback, std::move(result))); return; } MultiModeVbucketConfig* vbconf = vbucket_config(); const std::size_t size = keys.size(); std::map<uint16_t, IdInfo> serverid_keys; std::vector<int> serverid_table(vbconf->server_list().size(), -1); uint16_t vbucket = 0; uint16_t server_id = 0; PrefixMultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<PrefixMultiGetResult, PrefixMultiGetCallback> >(callback); auto& result = handler->get_result(); std::size_t pos = 0; for (size_t i = 0; i < size; ++i) { auto &key = keys[i]; GET_FILTER_KEY_POS(pos, key) vbucket = vbconf->GetVbucketByKey(key.c_str(), pos); server_id = vbconf->SelectServerFirstId(vbucket); if(serverid_table[server_id] == -1) { serverid_table[server_id] = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); } server_id = serverid_table[server_id]; auto& item = serverid_keys[server_id]; item.keys.emplace_back(key); item.vbuckets.emplace_back(vbucket); result.emplace(std::move(key), std::make_shared<PrefixGetResult>()); } handler->set_serverid_keys(serverid_keys); auto & serverid_keys_d = handler->get_serverid_keys(); for(auto& it : serverid_keys_d) { server_id = it.first; CommandPtr command = std::make_shared<PrefixMultiGetCommand>(caller_loop, server_id, handler); command->set_server_id(server_id); LaunchCommand(command); } } void MemcacheClientPool::LaunchCommand(CommandPtr& command) { //const int thread = next_thread_++; auto loop = loop_pool_.GetNextLoopWithHash(rand()); loop->RunInLoop( std::bind(&MemcacheClientPool::DoLaunchCommand, this, loop, command)); } void MemcacheClientPool::DoLaunchCommand(evpp::EventLoop * loop, CommandPtr command) { MultiModeVbucketConfig* vbconf = vbucket_config(); uint16_t server_id = command->server_id(); if (UNLIKELY(!command->ShouldRetry())) { //重试 需要重新算serverid uint16_t vbucket = command->vbucket_id(); server_id = vbconf->SelectServerId(vbucket, command->server_id()); if (UNLIKELY(server_id == BAD_SERVER_ID)) { LOG_ERROR << "bad server id"; command->OnError(ERR_CODE_DISCONNECT); return; } //command->set_server_id(server_id); } std::string server_addr = vbconf->GetServerAddrById(server_id); MemcClientMap* client_map = GetMemcClientMap(loop); if (UNLIKELY(client_map == NULL)) { command->OnError(ERR_CODE_DISCONNECT); LOG_INFO << "DoLaunchCommand thread pool empty"; return; } auto it = client_map->find(server_addr); if (UNLIKELY(it == client_map->end())) { BuilderMemClient(loop, server_addr, *client_map, timeout_ms_); auto client = client_map->find(server_addr); client->second->PushWaitingCommand(command); return; } if (LIKELY(it->second->conn() && it->second->conn()->IsConnected())) { it->second->PushRunningCommand(command); command->Launch(it->second); return; } if (!it->second->conn() || it->second->conn()->status() == evpp::TCPConn::kConnecting) { it->second->PushWaitingCommand(command); } else { if (command->ShouldRetry()) { LOG_INFO << "OnClientConnection disconnect retry"; LaunchCommand(command); } else { command->OnError(ERR_CODE_DISCONNECT); } } } }
#include "memcache_client_pool.h" #include "vbucket_config.h" #include "evpp/event_loop_thread_pool.h" #include "likely.h" namespace evmc { #define GET_FILTER_KEY_POS(name, key) \ name = key.find(key_filter_[0]); \ if (name == std::string::npos) { \ name = key.size(); \ } #define SET_SERVERID(vbucket,command) \ MultiModeVbucketConfig* vbconf = vbucket_config(); \ uint16_t server_id = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); \ command->set_server_id(server_id); \ MemcacheClientPool::~MemcacheClientPool() { } void MemcacheClientPool::Stop(bool wait_thread_exit) { loop_pool_.Stop(wait_thread_exit); MemcacheClientBase::Stop(); } bool MemcacheClientPool::Start() { bool ok = loop_pool_.Start(true); if (UNLIKELY(!ok)) { LOG_ERROR << "loop pool start failed"; return false; } if (!MemcacheClientBase::Start(true)) { loop_pool_.Stop(true); LOG_ERROR << "vbucket init failed"; return false; } auto server_list = vbucket_config()->server_list(); // 须先构造memc_client_map_数组,再各个元素取地址,否则地址不稳定,可能崩溃 for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) { memc_client_map_.emplace_back(MemcClientMap()); evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i); for (size_t svr = 0; svr < server_list.size(); ++svr) { auto & client_map = memc_client_map_.back(); BuilderMemClient(loop, server_list[svr], client_map, timeout_ms_); } } for (uint32_t i = 0; i < loop_pool_.thread_num(); ++i) { evpp::EventLoop* loop = loop_pool_.GetNextLoopWithHash(i); loop->set_context(evpp::Any(&memc_client_map_[i])); } return ok; } void MemcacheClientPool::Set(evpp::EventLoop* caller_loop, const std::string& key, const std::string& value, uint32_t flags, uint32_t expire, SetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<SetCommand>(caller_loop, vbucket, key, value, flags, expire, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::Remove(evpp::EventLoop* caller_loop, const std::string& key, RemoveCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<RemoveCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::Get(evpp::EventLoop* caller_loop, const std::string& key, GetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<GetCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::PrefixGet(evpp::EventLoop* caller_loop, const std::string& key, PrefixGetCallback callback) { std::size_t pos = 0; GET_FILTER_KEY_POS(pos, key) const uint16_t vbucket = vbucket_config()->GetVbucketByKey(key.c_str(), pos); CommandPtr command = std::make_shared<PrefixGetCommand>(caller_loop, vbucket, key, callback); SET_SERVERID(vbucket, command) LaunchCommand(command); } void MemcacheClientPool::RunBackGround(const std::function<void(void)>& fun) { auto loop = loop_pool_.GetNextLoopWithHash(rand()); loop->RunInLoop(fun); } void MemcacheClientPool::MultiGet(evpp::EventLoop* caller_loop, std::vector<std::string>& keys, MultiGetCallback& callback) { if (UNLIKELY(keys.size() <= 0)) { MultiGetResult result; caller_loop->RunInLoop(std::bind(callback, std::move(result))); return; } const std::size_t size = keys.size(); std::map<uint16_t, IdInfo> serverid_keys; MultiModeVbucketConfig* vbconf = vbucket_config(); uint16_t vbucket = 0; uint16_t server_id = 0; MultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<MultiGetResult, MultiGetCallback> > (callback); auto& result = handler->get_result(); std::size_t pos = 0; std::vector<int> serverid_table(vbconf->server_list().size(), -1); for (size_t i = 0; i < size; ++i) { auto &key = keys[i]; GET_FILTER_KEY_POS(pos, key) vbucket = vbconf->GetVbucketByKey(key.c_str(), pos); server_id = vbconf->SelectServerFirstId(vbucket); if(serverid_table[server_id] == -1) { serverid_table[server_id] = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); } server_id = serverid_table[server_id]; auto& item = serverid_keys[server_id]; item.keys.emplace_back(key); item.vbuckets.emplace_back(vbucket); result.emplace(std::move(key), std::move(GetResult())); } handler->set_serverid_keys(serverid_keys); auto& serverid_keys_d = handler->get_serverid_keys(); for(auto& it : serverid_keys_d) { server_id = it.first; CommandPtr command = std::make_shared<MultiGetCommand>(caller_loop, server_id, handler); command->set_server_id(server_id); LaunchCommand(command); } } void MemcacheClientPool::PrefixMultiGet(evpp::EventLoop* caller_loop, std::vector<std::string>& keys, PrefixMultiGetCallback callback) { if (UNLIKELY(keys.size() <= 0)) { PrefixMultiGetResult result; caller_loop->RunInLoop(std::bind(callback, std::move(result))); return; } MultiModeVbucketConfig* vbconf = vbucket_config(); const std::size_t size = keys.size(); std::map<uint16_t, IdInfo> serverid_keys; std::vector<int> serverid_table(vbconf->server_list().size(), -1); uint16_t vbucket = 0; uint16_t server_id = 0; PrefixMultiKeyGetHandlerPtr handler = std::make_shared<MultiKeyHandler<PrefixMultiGetResult, PrefixMultiGetCallback> >(callback); auto& result = handler->get_result(); std::size_t pos = 0; for (size_t i = 0; i < size; ++i) { auto &key = keys[i]; GET_FILTER_KEY_POS(pos, key) vbucket = vbconf->GetVbucketByKey(key.c_str(), pos); server_id = vbconf->SelectServerFirstId(vbucket); if(serverid_table[server_id] == -1) { serverid_table[server_id] = vbconf->SelectServerId(vbucket, BAD_SERVER_ID); } server_id = serverid_table[server_id]; auto& item = serverid_keys[server_id]; item.keys.emplace_back(key); item.vbuckets.emplace_back(vbucket); result.emplace(std::move(key), std::make_shared<PrefixGetResult>()); } handler->set_serverid_keys(serverid_keys); auto & serverid_keys_d = handler->get_serverid_keys(); for(auto& it : serverid_keys_d) { server_id = it.first; CommandPtr command = std::make_shared<PrefixMultiGetCommand>(caller_loop, server_id, handler); command->set_server_id(server_id); LaunchCommand(command); } } void MemcacheClientPool::LaunchCommand(CommandPtr& command) { //const int thread = next_thread_++; auto loop = loop_pool_.GetNextLoopWithHash(rand()); loop->RunInLoop( std::bind(&MemcacheClientPool::DoLaunchCommand, this, loop, command)); } void MemcacheClientPool::DoLaunchCommand(evpp::EventLoop * loop, CommandPtr command) { MultiModeVbucketConfig* vbconf = vbucket_config(); uint16_t server_id = command->server_id(); if (UNLIKELY(!command->ShouldRetry())) { //重试 需要重新算serverid uint16_t vbucket = command->vbucket_id(); server_id = vbconf->SelectServerId(vbucket, command->server_id()); if (UNLIKELY(server_id == BAD_SERVER_ID)) { LOG_ERROR << "bad server id"; command->OnError(ERR_CODE_DISCONNECT); return; } //command->set_server_id(server_id); } std::string server_addr = vbconf->GetServerAddrById(server_id); MemcClientMap* client_map = GetMemcClientMap(loop); if (UNLIKELY(client_map == NULL)) { command->OnError(ERR_CODE_DISCONNECT); LOG_INFO << "DoLaunchCommand thread pool empty"; return; } auto it = client_map->find(server_addr); if (UNLIKELY(it == client_map->end())) { BuilderMemClient(loop, server_addr, *client_map, timeout_ms_); auto client = client_map->find(server_addr); client->second->PushWaitingCommand(command); return; } if (LIKELY(it->second->conn() && it->second->conn()->IsConnected())) { it->second->PushRunningCommand(command); command->Launch(it->second); return; } if (!it->second->conn() || it->second->conn()->status() == evpp::TCPConn::kConnecting) { it->second->PushWaitingCommand(command); } else { if (command->ShouldRetry()) { LOG_INFO << "OnClientConnection disconnect retry"; command->set_server_id(command->server_id()); LaunchCommand(command); } else { command->OnError(ERR_CODE_DISCONNECT); } } } }
fix retry bug
fix retry bug
C++
bsd-3-clause
Qihoo360/evpp,Qihoo360/evpp,Qihoo360/evpp,Qihoo360/evpp,Qihoo360/evpp
a6b7c523b2f088aeddcd19c47bbdb03c3de17d00
gm/texturedomaineffect.cpp
gm/texturedomaineffect.cpp
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This test only works with the GPU backend. #include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/effects/SkGradientShader.h" #include "include/private/GrTypesPriv.h" #include "include/private/SkTArray.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrRenderTargetContextPriv.h" #include "src/gpu/GrSamplerState.h" #include "src/gpu/GrTextureProxy.h" #include "tools/gpu/TestOps.h" #include <memory> #include <utility> namespace skiagm { /** * This GM directly exercises GrTextureEffect::MakeTexelSubset. */ class TextureDomainEffect : public GpuGM { public: TextureDomainEffect(GrSamplerState::Filter filter) : fFilter(filter) { this->setBGColor(0xFFFFFFFF); } protected: SkString onShortName() override { SkString name("texture_domain_effect"); if (fFilter == GrSamplerState::Filter::kBilerp) { name.append("_bilerp"); } else if (fFilter == GrSamplerState::Filter::kMipMap) { name.append("_mipmap"); } return name; } SkISize onISize() override { const SkScalar canvasWidth = kDrawPad + 2 * ((kTargetWidth + 2 * kDrawPad) * GrSamplerState::kWrapModeCount + kTestPad * GrSamplerState::kWrapModeCount); return SkISize::Make(SkScalarCeilToInt(canvasWidth), 800); } void onOnceBeforeDraw() override { fBitmap.allocN32Pixels(kTargetWidth, kTargetHeight); SkCanvas canvas(fBitmap); canvas.clear(0x00000000); SkPaint paint; SkColor colors1[] = { SK_ColorCYAN, SK_ColorLTGRAY, SK_ColorGRAY }; paint.setShader(SkGradientShader::MakeSweep(65.f, 75.f, colors1, nullptr, SK_ARRAY_COUNT(colors1))); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); SkColor colors2[] = { SK_ColorMAGENTA, SK_ColorLTGRAY, SK_ColorYELLOW }; paint.setShader(SkGradientShader::MakeSweep(45.f, 55.f, colors2, nullptr, SK_ARRAY_COUNT(colors2))); paint.setBlendMode(SkBlendMode::kDarken); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); SkColor colors3[] = { SK_ColorBLUE, SK_ColorLTGRAY, SK_ColorGREEN }; paint.setShader(SkGradientShader::MakeSweep(25.f, 35.f, colors3, nullptr, SK_ARRAY_COUNT(colors3))); paint.setBlendMode(SkBlendMode::kLighten); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); } DrawResult onDraw(GrContext* context, GrRenderTargetContext* renderTargetContext, SkCanvas* canvas, SkString* errorMsg) override { GrProxyProvider* proxyProvider = context->priv().proxyProvider(); sk_sp<GrTextureProxy> proxy; GrMipMapped mipMapped = fFilter == GrSamplerState::Filter::kMipMap && context->priv().caps()->mipMapSupport() ? GrMipMapped::kYes : GrMipMapped::kNo; proxy = proxyProvider->createProxyFromBitmap(fBitmap, mipMapped); if (!proxy) { *errorMsg = "Failed to create proxy."; return DrawResult::kFail; } SkTArray<SkMatrix> textureMatrices; textureMatrices.push_back() = SkMatrix::I(); textureMatrices.push_back() = SkMatrix::MakeScale(1.5f, 0.85f); textureMatrices.push_back(); textureMatrices.back().setRotate(45.f, proxy->width() / 2.f, proxy->height() / 2.f); const SkIRect texelDomains[] = { fBitmap.bounds(), SkIRect::MakeXYWH(fBitmap.width() / 4 - 1, fBitmap.height() / 4 - 1, fBitmap.width() / 2 + 2, fBitmap.height() / 2 + 2), }; sk_sp<GrTextureProxy> subsetProxies[SK_ARRAY_COUNT(texelDomains)]; for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) { SkBitmap subset; fBitmap.extractSubset(&subset, texelDomains[d]); auto mm = fFilter == GrSamplerState::Filter::kMipMap ? GrMipMapped::kYes : GrMipMapped::kNo; subsetProxies[d] = proxyProvider->createProxyFromBitmap(subset, mm); } SkRect localRect = SkRect::Make(fBitmap.bounds()).makeOutset(kDrawPad, kDrawPad); SkScalar y = kDrawPad + kTestPad; for (int tm = 0; tm < textureMatrices.count(); ++tm) { for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) { SkScalar x = kDrawPad + kTestPad; for (int m = 0; m < GrSamplerState::kWrapModeCount; ++m) { auto wm = static_cast<GrSamplerState::WrapMode>(m); if (fFilter != GrSamplerState::Filter::kNearest && (wm == GrSamplerState::WrapMode::kRepeat || wm == GrSamplerState::WrapMode::kMirrorRepeat)) { // [Mirror] Repeat mode doesn't produce correct results with bilerp // filtering continue; } GrSamplerState sampler(wm, fFilter); const auto& caps = *context->priv().caps(); auto fp1 = GrTextureEffect::MakeTexelSubset(proxy, fBitmap.alphaType(), textureMatrices[tm], sampler, texelDomains[d], caps); if (!fp1) { continue; } auto drawRect = localRect.makeOffset(x, y); // Throw a translate in the local matrix just to test having something other // than identity. Compensate with an offset local rect. static constexpr SkVector kT = {-100, 300}; if (auto op = sk_gpu_test::test_ops::MakeRect(context, std::move(fp1), drawRect, localRect.makeOffset(kT), SkMatrix::MakeTrans(-kT))) { renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); } x += localRect.width() + kTestPad; SkMatrix subsetTextureMatrix = SkMatrix::Concat( SkMatrix::MakeTrans(-texelDomains[d].topLeft()), textureMatrices[tm]); // Now draw with a subsetted proxy using fixed function texture sampling rather // than a texture subset as a comparison. drawRect = localRect.makeOffset(x, y); auto fp2 = GrTextureEffect::Make(subsetProxies[d], fBitmap.alphaType(), subsetTextureMatrix, GrSamplerState(wm, fFilter), caps); if (auto op = sk_gpu_test::test_ops::MakeRect(context, std::move(fp2), drawRect, localRect)) { renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); } x += localRect.width() + kTestPad; } y += localRect.height() + kTestPad; } } return DrawResult::kOk; } private: static constexpr SkScalar kDrawPad = 10.f; static constexpr SkScalar kTestPad = 10.f; static constexpr int kTargetWidth = 100; static constexpr int kTargetHeight = 100; SkBitmap fBitmap; GrSamplerState::Filter fFilter; typedef GM INHERITED; }; DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kNearest);) DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kBilerp);) DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kMipMap);) }
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This test only works with the GPU backend. #include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/effects/SkGradientShader.h" #include "include/private/GrTypesPriv.h" #include "include/private/SkTArray.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrProxyProvider.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrRenderTargetContextPriv.h" #include "src/gpu/GrSamplerState.h" #include "src/gpu/GrTextureProxy.h" #include "tools/gpu/TestOps.h" #include <memory> #include <utility> namespace skiagm { /** * This GM directly exercises GrTextureEffect::MakeTexelSubset. */ class TextureDomainEffect : public GpuGM { public: TextureDomainEffect(GrSamplerState::Filter filter) : fFilter(filter) { this->setBGColor(0xFFFFFFFF); } protected: SkString onShortName() override { SkString name("texture_domain_effect"); if (fFilter == GrSamplerState::Filter::kBilerp) { name.append("_bilerp"); } else if (fFilter == GrSamplerState::Filter::kMipMap) { name.append("_mipmap"); } return name; } SkISize onISize() override { const SkScalar canvasWidth = kDrawPad + 2 * ((kTargetWidth + 2 * kDrawPad) * GrSamplerState::kWrapModeCount + kTestPad * GrSamplerState::kWrapModeCount); return SkISize::Make(SkScalarCeilToInt(canvasWidth), 800); } void onOnceBeforeDraw() override { fBitmap.allocN32Pixels(kTargetWidth, kTargetHeight); SkCanvas canvas(fBitmap); canvas.clear(0x00000000); SkPaint paint; SkColor colors1[] = { SK_ColorCYAN, SK_ColorLTGRAY, SK_ColorGRAY }; paint.setShader(SkGradientShader::MakeSweep(65.f, 75.f, colors1, nullptr, SK_ARRAY_COUNT(colors1))); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); SkColor colors2[] = { SK_ColorMAGENTA, SK_ColorLTGRAY, SK_ColorYELLOW }; paint.setShader(SkGradientShader::MakeSweep(45.f, 55.f, colors2, nullptr, SK_ARRAY_COUNT(colors2))); paint.setBlendMode(SkBlendMode::kDarken); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); SkColor colors3[] = { SK_ColorBLUE, SK_ColorLTGRAY, SK_ColorGREEN }; paint.setShader(SkGradientShader::MakeSweep(25.f, 35.f, colors3, nullptr, SK_ARRAY_COUNT(colors3))); paint.setBlendMode(SkBlendMode::kLighten); canvas.drawOval(SkRect::MakeXYWH(-5.f, -5.f, kTargetWidth + 10.f, kTargetHeight + 10.f), paint); } DrawResult onDraw(GrContext* context, GrRenderTargetContext* renderTargetContext, SkCanvas* canvas, SkString* errorMsg) override { GrProxyProvider* proxyProvider = context->priv().proxyProvider(); sk_sp<GrTextureProxy> proxy; GrMipMapped mipMapped = fFilter == GrSamplerState::Filter::kMipMap && context->priv().caps()->mipMapSupport() ? GrMipMapped::kYes : GrMipMapped::kNo; proxy = proxyProvider->createProxyFromBitmap(fBitmap, mipMapped); if (!proxy) { *errorMsg = "Failed to create proxy."; return DrawResult::kFail; } SkTArray<SkMatrix> textureMatrices; textureMatrices.push_back() = SkMatrix::I(); textureMatrices.push_back() = SkMatrix::MakeScale(1.5f, 0.85f); textureMatrices.push_back(); textureMatrices.back().setRotate(45.f, proxy->width() / 2.f, proxy->height() / 2.f); const SkIRect texelDomains[] = { fBitmap.bounds(), SkIRect::MakeXYWH(fBitmap.width() / 4 - 1, fBitmap.height() / 4 - 1, fBitmap.width() / 2 + 2, fBitmap.height() / 2 + 2), }; SkRect localRect = SkRect::Make(fBitmap.bounds()).makeOutset(kDrawPad, kDrawPad); SkScalar y = kDrawPad + kTestPad; for (int tm = 0; tm < textureMatrices.count(); ++tm) { for (size_t d = 0; d < SK_ARRAY_COUNT(texelDomains); ++d) { SkScalar x = kDrawPad + kTestPad; for (int m = 0; m < GrSamplerState::kWrapModeCount; ++m) { auto wm = static_cast<GrSamplerState::WrapMode>(m); if (fFilter != GrSamplerState::Filter::kNearest && (wm == GrSamplerState::WrapMode::kRepeat || wm == GrSamplerState::WrapMode::kMirrorRepeat)) { // [Mirror] Repeat mode doesn't produce correct results with bilerp // filtering continue; } GrSamplerState sampler(wm, fFilter); const auto& caps = *context->priv().caps(); auto fp1 = GrTextureEffect::MakeTexelSubset(proxy, fBitmap.alphaType(), textureMatrices[tm], sampler, texelDomains[d], caps); if (!fp1) { continue; } auto fp2 = fp1->clone(); SkASSERT(fp2); auto drawRect = localRect.makeOffset(x, y); if (auto op = sk_gpu_test::test_ops::MakeRect( context, std::move(fp1), drawRect, localRect)) { renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); } x += localRect.width() + kTestPad; // Draw again with a translated local rect and compensating translate matrix. drawRect = localRect.makeOffset(x, y); static constexpr SkVector kT = {-100, 300}; if (auto op = sk_gpu_test::test_ops::MakeRect(context, std::move(fp2), drawRect, localRect.makeOffset(kT), SkMatrix::MakeTrans(-kT))) { renderTargetContext->priv().testingOnly_addDrawOp(std::move(op)); } x += localRect.width() + kTestPad; } y += localRect.height() + kTestPad; } } return DrawResult::kOk; } private: static constexpr SkScalar kDrawPad = 10.f; static constexpr SkScalar kTestPad = 10.f; static constexpr int kTargetWidth = 100; static constexpr int kTargetHeight = 100; SkBitmap fBitmap; GrSamplerState::Filter fFilter; typedef GM INHERITED; }; DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kNearest);) DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kBilerp);) DEF_GM(return new TextureDomainEffect(GrSamplerState::Filter::kMipMap);) }
Revert "Use bitmap subset for comparison in texture_domain_effect GMs."
Revert "Use bitmap subset for comparison in texture_domain_effect GMs." This reverts commit 6377f1c1f9a44d5a6b4a7a53840d82885a8ff2ff. Reason for revert: doesn't work with ES2 w/out NPOT extension Original change's description: > Use bitmap subset for comparison in texture_domain_effect GMs. > > This used to do 2 texel subset draws. The second draw tested a > non-identity local matrix. Now the first draw exercises local matrix and > the second draws with a proxy that represents just the bitmap subset to > give a better basis for comparison. > > Change-Id: Ia41330598626c8cc656fd1ca2e289c8184847807 > Reviewed-on: https://skia-review.googlesource.com/c/skia/+/266616 > Reviewed-by: Michael Ludwig <[email protected]> > Commit-Queue: Brian Salomon <[email protected]> [email protected],[email protected] Change-Id: I08464aab72b157909664d64452db25f22d40bde3 No-Presubmit: true No-Tree-Checks: true No-Try: true Reviewed-on: https://skia-review.googlesource.com/c/skia/+/266677 Reviewed-by: Brian Salomon <[email protected]> Commit-Queue: Brian Salomon <[email protected]>
C++
bsd-3-clause
google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,google/skia
3d2c84e33db68c523b9acb6f9aefd0ea6c2289a0
Library/Sources/Stroika/Foundation/Containers/LRUCache.inl
Library/Sources/Stroika/Foundation/Containers/LRUCache.inl
/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #ifndef _Stroika_Foundation_Containers_LRUCache_inl_ #define _Stroika_Foundation_Containers_LRUCache_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" #include "Common.h" namespace Stroika { namespace Foundation { namespace Containers { // class LRUCacheDefaultTraits<ELEMENT,TRAITS> template <typename ELEMENT, typename KEY> inline LRUCacheDefaultTraits<ELEMENT,KEY>::KeyType LRUCacheDefaultTraits<ELEMENT,KEY>::ExtractKey (const ElementType& e) { return e; } template <typename ELEMENT, typename KEY> inline size_t LRUCacheDefaultTraits<ELEMENT,KEY>::Hash (const KeyType& e) { return 0; } template <typename ELEMENT, typename KEY> inline void LRUCacheDefaultTraits<ELEMENT,KEY>::Clear (ElementType* element) { (*element) = ElementType (); } template <typename ELEMENT, typename KEY> inline bool LRUCacheDefaultTraits<ELEMENT,KEY>::Equal (const KeyType& lhs, const KeyType& rhs) { return lhs == rhs; } // class LRUCache<ELEMENT,TRAITS>::CacheElement template <typename ELEMENT, typename TRAITS> inline LRUCache<ELEMENT,TRAITS>::CacheElement::CacheElement () : fNext (nullptr) , fPrev (nullptr) , fElement () { } // class LRUCache<ELEMENT,TRAITS>::CacheIterator template <typename ELEMENT, typename TRAITS> inline LRUCache<ELEMENT,TRAITS>::CacheIterator::CacheIterator (CacheElement* c) : fCur (c) { } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator& LRUCache<ELEMENT,TRAITS>::CacheIterator::operator++ () { RequireNotNull (fCur); fCur = fCur->fNext; return *this; } template <typename ELEMENT, typename TRAITS> inline ELEMENT& LRUCache<ELEMENT,TRAITS>::CacheIterator::operator* () { RequireNotNull (fCur); return fCur->fElement; } template <typename ELEMENT, typename TRAITS> inline bool LRUCache<ELEMENT,TRAITS>::CacheIterator::operator== (CacheIterator rhs) { return fCur == rhs.fCur; } template <typename ELEMENT, typename TRAITS> inline bool LRUCache<ELEMENT,TRAITS>::CacheIterator::operator!= (CacheIterator rhs) { return fCur != rhs.fCur; } // class LRUCache<ELEMENT,TRAITS> template <typename ELEMENT, typename TRAITS> LRUCache<ELEMENT,TRAITS>::LRUCache (size_t maxCacheSize) : fCachedElts_BUF_ () , fCachedElts_First_ (nullptr) , fCachedElts_fLast_ (nullptr) #if qKeepLRUCacheStats , fCachedCollected_Hits (0) , fCachedCollected_Misses (0) #endif { SetMaxCacheSize (maxCacheSize); } template <typename ELEMENT, typename TRAITS> inline size_t LRUCache<ELEMENT,TRAITS>::GetMaxCacheSize () const { return fCachedElts_BUF_.size (); } template <typename ELEMENT, typename TRAITS> void LRUCache<ELEMENT,TRAITS>::SetMaxCacheSize (size_t maxCacheSize) { Require (maxCacheSize >= 1); if (maxCacheSize != fCachedElts_BUF_.size ()) { fCachedElts_BUF_.resize (maxCacheSize); // Initially link LRU together. fCachedElts_First_ = Containers::Start (fCachedElts_BUF_); fCachedElts_fLast_ = fCachedElts_First_ + maxCacheSize-1; fCachedElts_BUF_[0].fPrev = nullptr; for (size_t i = 0; i < maxCacheSize-1; ++i) { fCachedElts_BUF_[i].fNext = fCachedElts_First_ + (i+1); fCachedElts_BUF_[i+1].fPrev = fCachedElts_First_ + (i); } fCachedElts_BUF_[maxCacheSize-1].fNext = nullptr; } } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator LRUCache<ELEMENT,TRAITS>::begin () { return fCachedElts_First_; } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator LRUCache<ELEMENT,TRAITS>::end () { return nullptr; } template <typename ELEMENT, typename TRAITS> inline void LRUCache<ELEMENT,TRAITS>::ShuffleToHead_ (CacheElement* b) { AssertNotNull (b); if (b == fCachedElts_First_) { Assert (b->fPrev == nullptr); return; // already at head } CacheElement* prev = b->fPrev; AssertNotNull (prev); // don't call this if already at head // patch following and preceeding blocks to point to each other prev->fNext = b->fNext; if (b->fNext == nullptr) { Assert (b == fCachedElts_fLast_); fCachedElts_fLast_ = b->fPrev; } else { b->fNext->fPrev = prev; } // Now patch us into the head of the list CacheElement* oldFirst = fCachedElts_First_; AssertNotNull (oldFirst); b->fNext = oldFirst; oldFirst->fPrev = b; b->fPrev = nullptr; fCachedElts_First_ = b; Ensure (fCachedElts_fLast_ != nullptr and fCachedElts_fLast_->fNext == nullptr); Ensure (fCachedElts_First_ != nullptr and fCachedElts_First_ == b and fCachedElts_First_->fPrev == nullptr and fCachedElts_First_->fNext != nullptr); } template <typename ELEMENT, typename TRAITS> inline void LRUCache<ELEMENT,TRAITS>::ClearCache () { for (CacheElement* cur = fCachedElts_First_; cur != nullptr; cur = cur->fNext) { TRAITS::Clear (&cur->fElement); } } template <typename ELEMENT, typename TRAITS> /* @METHOD: LRUCache<ELEMENT>::LookupElement @DESCRIPTION: <p>Check and see if the given element is in the cache. Return that element if its tehre, and nullptr otherwise. Note that this routine re-orders the cache so that the most recently looked up element is first, and because of this re-ordering, its illegal to do a Lookup while a @'LRUCache<ELEMENT>::CacheIterator' exists for this LRUCache.</p> */ inline ELEMENT* LRUCache<ELEMENT,TRAITS>::LookupElement (const KeyType& item) { for (CacheElement* cur = fCachedElts_First_; cur != nullptr; cur = cur->fNext) { if (TRAITS::Equal (TRAITS::ExtractKey (cur->fElement), item)) { ShuffleToHead_ (cur); #if qKeepLRUCacheStats fCachedCollected_Hits++; #endif return &fCachedElts_First_->fElement; } } #if qKeepLRUCacheStats fCachedCollected_Misses++; #endif return nullptr; } template <typename ELEMENT, typename TRAITS> /* @METHOD: LRUCache<ELEMENT>::AddNew @DESCRIPTION: <p>Create a new LRUCache element (potentially bumping some old element out of the cache). This new element will be considered most recently used. Note that this routine re-orders the cache so that the most recently looked up element is first, and because of this re-ordering, its illegal to do a Lookup while a @'LRUCache<ELEMENT>::CacheIterator' exists for this LRUCache.</p> */ inline ELEMENT* LRUCache<ELEMENT,TRAITS>::AddNew () { ShuffleToHead_ (fCachedElts_fLast_); return &fCachedElts_First_->fElement; } } } } #endif /*_Stroika_Foundation_Containers_LRUCache_inl_*/
/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #ifndef _Stroika_Foundation_Containers_LRUCache_inl_ #define _Stroika_Foundation_Containers_LRUCache_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" #include "Common.h" namespace Stroika { namespace Foundation { namespace Containers { // class LRUCacheDefaultTraits<ELEMENT,TRAITS> template <typename ELEMENT, typename KEY> inline typename LRUCacheDefaultTraits<ELEMENT,KEY>::KeyType LRUCacheDefaultTraits<ELEMENT,KEY>::ExtractKey (const ElementType& e) { return e; } template <typename ELEMENT, typename KEY> inline size_t LRUCacheDefaultTraits<ELEMENT,KEY>::Hash (const KeyType& e) { return 0; } template <typename ELEMENT, typename KEY> inline void LRUCacheDefaultTraits<ELEMENT,KEY>::Clear (ElementType* element) { (*element) = ElementType (); } template <typename ELEMENT, typename KEY> inline bool LRUCacheDefaultTraits<ELEMENT,KEY>::Equal (const KeyType& lhs, const KeyType& rhs) { return lhs == rhs; } // class LRUCache<ELEMENT,TRAITS>::CacheElement template <typename ELEMENT, typename TRAITS> inline LRUCache<ELEMENT,TRAITS>::CacheElement::CacheElement () : fNext (nullptr) , fPrev (nullptr) , fElement () { } // class LRUCache<ELEMENT,TRAITS>::CacheIterator template <typename ELEMENT, typename TRAITS> inline LRUCache<ELEMENT,TRAITS>::CacheIterator::CacheIterator (CacheElement* c) : fCur (c) { } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator& LRUCache<ELEMENT,TRAITS>::CacheIterator::operator++ () { RequireNotNull (fCur); fCur = fCur->fNext; return *this; } template <typename ELEMENT, typename TRAITS> inline ELEMENT& LRUCache<ELEMENT,TRAITS>::CacheIterator::operator* () { RequireNotNull (fCur); return fCur->fElement; } template <typename ELEMENT, typename TRAITS> inline bool LRUCache<ELEMENT,TRAITS>::CacheIterator::operator== (CacheIterator rhs) { return fCur == rhs.fCur; } template <typename ELEMENT, typename TRAITS> inline bool LRUCache<ELEMENT,TRAITS>::CacheIterator::operator!= (CacheIterator rhs) { return fCur != rhs.fCur; } // class LRUCache<ELEMENT,TRAITS> template <typename ELEMENT, typename TRAITS> LRUCache<ELEMENT,TRAITS>::LRUCache (size_t maxCacheSize) : fCachedElts_BUF_ () , fCachedElts_First_ (nullptr) , fCachedElts_fLast_ (nullptr) #if qKeepLRUCacheStats , fCachedCollected_Hits (0) , fCachedCollected_Misses (0) #endif { SetMaxCacheSize (maxCacheSize); } template <typename ELEMENT, typename TRAITS> inline size_t LRUCache<ELEMENT,TRAITS>::GetMaxCacheSize () const { return fCachedElts_BUF_.size (); } template <typename ELEMENT, typename TRAITS> void LRUCache<ELEMENT,TRAITS>::SetMaxCacheSize (size_t maxCacheSize) { Require (maxCacheSize >= 1); if (maxCacheSize != fCachedElts_BUF_.size ()) { fCachedElts_BUF_.resize (maxCacheSize); // Initially link LRU together. fCachedElts_First_ = Containers::Start (fCachedElts_BUF_); fCachedElts_fLast_ = fCachedElts_First_ + maxCacheSize-1; fCachedElts_BUF_[0].fPrev = nullptr; for (size_t i = 0; i < maxCacheSize-1; ++i) { fCachedElts_BUF_[i].fNext = fCachedElts_First_ + (i+1); fCachedElts_BUF_[i+1].fPrev = fCachedElts_First_ + (i); } fCachedElts_BUF_[maxCacheSize-1].fNext = nullptr; } } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator LRUCache<ELEMENT,TRAITS>::begin () { return fCachedElts_First_; } template <typename ELEMENT, typename TRAITS> inline typename LRUCache<ELEMENT,TRAITS>::CacheIterator LRUCache<ELEMENT,TRAITS>::end () { return nullptr; } template <typename ELEMENT, typename TRAITS> inline void LRUCache<ELEMENT,TRAITS>::ShuffleToHead_ (CacheElement* b) { AssertNotNull (b); if (b == fCachedElts_First_) { Assert (b->fPrev == nullptr); return; // already at head } CacheElement* prev = b->fPrev; AssertNotNull (prev); // don't call this if already at head // patch following and preceeding blocks to point to each other prev->fNext = b->fNext; if (b->fNext == nullptr) { Assert (b == fCachedElts_fLast_); fCachedElts_fLast_ = b->fPrev; } else { b->fNext->fPrev = prev; } // Now patch us into the head of the list CacheElement* oldFirst = fCachedElts_First_; AssertNotNull (oldFirst); b->fNext = oldFirst; oldFirst->fPrev = b; b->fPrev = nullptr; fCachedElts_First_ = b; Ensure (fCachedElts_fLast_ != nullptr and fCachedElts_fLast_->fNext == nullptr); Ensure (fCachedElts_First_ != nullptr and fCachedElts_First_ == b and fCachedElts_First_->fPrev == nullptr and fCachedElts_First_->fNext != nullptr); } template <typename ELEMENT, typename TRAITS> inline void LRUCache<ELEMENT,TRAITS>::ClearCache () { for (CacheElement* cur = fCachedElts_First_; cur != nullptr; cur = cur->fNext) { TRAITS::Clear (&cur->fElement); } } template <typename ELEMENT, typename TRAITS> /* @METHOD: LRUCache<ELEMENT>::LookupElement @DESCRIPTION: <p>Check and see if the given element is in the cache. Return that element if its tehre, and nullptr otherwise. Note that this routine re-orders the cache so that the most recently looked up element is first, and because of this re-ordering, its illegal to do a Lookup while a @'LRUCache<ELEMENT>::CacheIterator' exists for this LRUCache.</p> */ inline ELEMENT* LRUCache<ELEMENT,TRAITS>::LookupElement (const KeyType& item) { for (CacheElement* cur = fCachedElts_First_; cur != nullptr; cur = cur->fNext) { if (TRAITS::Equal (TRAITS::ExtractKey (cur->fElement), item)) { ShuffleToHead_ (cur); #if qKeepLRUCacheStats fCachedCollected_Hits++; #endif return &fCachedElts_First_->fElement; } } #if qKeepLRUCacheStats fCachedCollected_Misses++; #endif return nullptr; } template <typename ELEMENT, typename TRAITS> /* @METHOD: LRUCache<ELEMENT>::AddNew @DESCRIPTION: <p>Create a new LRUCache element (potentially bumping some old element out of the cache). This new element will be considered most recently used. Note that this routine re-orders the cache so that the most recently looked up element is first, and because of this re-ordering, its illegal to do a Lookup while a @'LRUCache<ELEMENT>::CacheIterator' exists for this LRUCache.</p> */ inline ELEMENT* LRUCache<ELEMENT,TRAITS>::AddNew () { ShuffleToHead_ (fCachedElts_fLast_); return &fCachedElts_First_->fElement; } } } } #endif /*_Stroika_Foundation_Containers_LRUCache_inl_*/
fix small bug un LRUCache code
fix small bug un LRUCache code
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
37ee856dec65f6e346f8a9a677902ed0b9f0949b
lib/graph.hpp
lib/graph.hpp
// This file contains definitions of basic types: Vertex, Distance, Arc, and Graph. // Graph can be read from file in DIMACS or METIS format. // // Copyright (c) savrus, 2014 #pragma once #include <vector> #include <utility> #include <algorithm> #include <limits> #include <cassert> #include <stdio.h> #include <ctype.h> #include <string.h> #include <errno.h> // Types for vertices and distances to avoid typing 'int' for almost every variable typedef int Vertex; typedef int Distance; static const Vertex none = -1; static const Distance infty = std::numeric_limits<Distance>::max(); // Arc class struct Arc { Vertex head:30; // head vertex ID bool forward:1; // true if this is an outgoing arc bool reverse:1; // true if this is an incoming arc Distance length; // arc length Arc(Vertex h, Distance l, bool f, bool r) : head(h), forward(f), reverse(r), length(l) {} Arc() {} }; // Directed graph class class Graph { long long n; // Number of vertices long long m; // Number of arcs std::vector<Arc> arcs; // Compressed adjacency lists std::vector< std::vector<Arc*> > a_begin; // Index of first outgoing/incoming arc std::vector< std::vector<Arc*> > a_end; // Index of last outgoing/incoming arc + 1 std::vector< std::pair<Vertex, Arc> > tmp_arcs; // Temporary list of arcs // Compare arcs by head struct cmp_by_head { bool operator() (const std::pair<Vertex,Arc> &xx, const std::pair<Vertex,Arc> &yy) { const Arc &x = xx.second, &y = yy.second; if (xx.first != yy.first) return xx.first < yy.first; if (x.head != y.head) return x.head < y.head; return x.length < y.length; } }; // Compare arcs by direction struct cmp_by_direction { bool operator() (const std::pair<Vertex,Arc> &xx, const std::pair<Vertex,Arc> &yy) { const Arc &x = xx.second, &y = yy.second; if (xx.first != yy.first) return xx.first < yy.first; if (x.reverse != y.reverse) return x.reverse == true; if (x.forward != y.forward) return x.forward == false; if (x.head != y.head) return x.head < y.head; return x.length < y.length; } }; // Construct adjacency lists from the temporary list of arcs void init_arcs() { std::vector< std::pair<int, Arc> > &a = tmp_arcs; size_t i; // Remove redundant arcs std::sort(a.begin(), a.end(), cmp_by_direction()); i = 0; for (size_t j = 1; j < a.size(); ++j) { Arc &ai = a[i].second, &aj = a[j].second; if (a[i].first == a[j].first && ai.head == aj.head && ai.forward == aj.forward && ai.reverse == aj.reverse) continue; if (++i < j) a[i] = a[j]; } a.resize(i+1); // Merge forward and reverse arcs into one bidirectional arc std::sort(a.begin(), a.end(), cmp_by_head()); i = 0; for (size_t j = 1; j < a.size(); ++j) { Arc &ai = a[i].second, &aj = a[j].second; if (a[i].first == a[j].first && ai.head == aj.head && ai.length == aj.length) { ai.forward |= aj.forward; ai.reverse |= aj.reverse; continue; } if (++i < j) a[i] = a[j]; } a.resize(i+1); // Order arcs by direction and determine adjacency lists std::sort(a.begin(), a.end(), cmp_by_direction()); arcs.resize(a.size()); a_begin[0].resize(n); a_begin[1].resize(n); a_end[0].resize(n); a_end[1].resize(n); for (size_t j = 0; j < a.size(); ++j) { arcs[j] = a[j].second; if (j == 0 || a[j].first != a[j-1].first) { if (arcs[j].reverse) a_begin[0][a[j].first] = &arcs[j]; if (arcs[j].forward) a_begin[1][a[j].first] = &arcs[j]; } if (j+1 == a.size() || a[j].first != a[j+1].first) { if (arcs[j].reverse) a_end[0][a[j].first] = &arcs[j] + 1; if (arcs[j].forward) a_end[1][a[j].first] = &arcs[j] + 1; } if (j > 0 && a[j].first == a[j-1].first) { if (arcs[j].reverse != arcs[j-1].reverse) a_end[0][a[j].first] = &arcs[j]; if (arcs[j].forward != arcs[j-1].forward) a_begin[1][a[j].first] = &arcs[j]; } } a.clear(); } // Add arc to the temporary list of arcs bool add_tmp_arc(Vertex u, Vertex v, Distance w, bool undirected) { if (u < 0 || v < 0 || u >= n || v >= n) return false; tmp_arcs.push_back(std::make_pair(u, Arc(v, w, true, undirected))); tmp_arcs.push_back(std::make_pair(v, Arc(u, w, undirected, true))); m += 1 + undirected; return true; } // Read graph from file in DIMACS format // p sp n m - header: n vertices, m edges // c bla-bla - comment line // a u v w - arc (u,v) with length w bool read_dimacs(FILE *file, bool undirected = false) { char buf[512], c; long long u,v,w,m; bool inited = false; while (fgets(buf, sizeof(buf), file) != NULL) { if (buf[strlen(buf)-1] != '\n') { if (buf[0] != 'c') return false; while ((c = fgetc(file)) != '\n' && c != EOF); } else if (buf[0] == 'p') { if (inited) return false; inited = true; if (sscanf(buf, "p sp %lld %lld", &n, &m) != 2) return false; } else if (buf[0] == 'a') { if (sscanf(buf, "a %lld %lld %lld", &u, &v, &w) != 3) return false; if (!add_tmp_arc(u-1, v-1, w, undirected)) return false; } else if (buf[0] == 'c') continue; else return false; } finilize(); return true; } // Read graph from file in METIS format // n m [fmt] [ncon] - header: fmt = ijk: i - s (vertex size) is present, // j - w (vertex weights) are present, // k - l (edge lengths) are present, // ncon - number of vertex weights. All defaults are 1. // ... // s w_1 .. w_ncon v_1 l_1 ... - line for a vertex: size (if i), vertex weights (if j), edges with lengths (if k) bool read_metis(FILE *file, bool undirected = false) { int c, i = 0, fmt = 0, ncon = 0, skip = 0; long long elem = 0; Vertex v = 0, head; bool newline = true, inelem = false; do { c = fgetc(file); if (newline && c == '%') { while (c != '\n' && c != EOF) c = fgetc(file); } else if (isdigit(c)) { inelem = true; elem = elem*10 + c - '0'; } else if (isspace(c) || c == EOF) { if (inelem) { if (v == 0) { if (i == 0) n = elem; else if (i == 1) /* m = elem */; else if (i == 2) { if ((elem % 10 > 1) || ((elem/10) % 10 > 1) || elem > 111) return false; fmt = elem; skip = (fmt >= 100) + (fmt % 100 >= 10); } else if (i == 3) { if (fmt % 100 < 10) return false; ncon = elem; skip = (fmt >= 100) + ncon; } else return false; } else if (i >= skip) { if (fmt % 10 == 1) { if ((i-skip) % 2 == 0) head = elem-1; else if (!add_tmp_arc(v-1, head, elem, undirected)) return false; } else if (!add_tmp_arc(v-1, elem-1, 1, undirected)) return false; } ++i; elem = 0; inelem = false; } if (c == '\n' || (!newline && c == EOF)) { if (v > 0 && (i < skip || (fmt % 10 == 1 && (i-skip) % 2 == 1))) return false; ++v; i = 0; newline = true; } } else return false; } while (c != EOF); finilize(); return true; } public: Graph() : n(0), m(0), a_begin(2), a_end(2) {} Vertex get_n() const { return n; } // Get number of vertices size_t get_m() const { return m; } // Get number of arcs typedef Arc* arc_iterator; // Adjacency list iterator type // Get adjacency list iterator bounds arc_iterator begin(Vertex v, bool forward = true) const { return a_begin[forward][v]; } arc_iterator end(Vertex v, bool forward = true) const { return a_end[forward][v]; } // Get vertex degree size_t get_degree(Vertex v, bool forward) const { return end(v, forward) - begin(v, forward); } size_t get_degree(Vertex v) const { return get_degree(v, true) + get_degree(v, false); } // Read graph from file (if the file format is supported) bool read(char *filename, bool undirected = false) { FILE *file; if ((file = fopen(filename, "r")) == NULL) return false; if (read_dimacs(file, undirected)) { fclose(file); return true; } rewind(file); if (read_metis(file, undirected)) { fclose(file); return true; } fclose(file); return false; } // Graph construction interface // User should set n, add some arcs, and call finilize() // Set the number of vertices void set_n(Vertex nn) { n = nn; }; // Add (u,v) arc (with (v,u) arc if undirected) to the temporary list of arcs void add_arc(Vertex u, Vertex v, Distance w, bool undirected = false) { bool r = add_tmp_arc(u, v, w, undirected); assert(r); } // Construct adjacency lists from the temporary list of arcs void finilize() { init_arcs(); } };
// This file contains definitions of basic types: Vertex, Distance, Arc, and Graph. // Graph can be read from file in DIMACS or METIS format. // // Copyright (c) savrus, 2014 #pragma once #include <vector> #include <utility> #include <algorithm> #include <limits> #include <cassert> #include <stdio.h> #include <ctype.h> #include <string.h> #include <errno.h> // Types for vertices and distances to avoid typing 'int' for almost every variable typedef int Vertex; typedef int Distance; static const Vertex none = -1; static const Distance infty = std::numeric_limits<Distance>::max(); // Arc class struct Arc { Vertex head:30; // head vertex ID bool forward:1; // true if this is an outgoing arc bool reverse:1; // true if this is an incoming arc Distance length; // arc length Arc(Vertex h, Distance l, bool f, bool r) : head(h), forward(f), reverse(r), length(l) {} Arc() {} }; // Directed graph class class Graph { long long n; // Number of vertices long long m; // Number of arcs std::vector<Arc> arcs; // Compressed adjacency lists std::vector< std::vector<Arc*> > a_begin; // Index of first outgoing/incoming arc std::vector< std::vector<Arc*> > a_end; // Index of last outgoing/incoming arc + 1 std::vector< std::pair<Vertex, Arc> > tmp_arcs; // Temporary list of arcs // Compare arcs by head struct cmp_by_head { bool operator() (const std::pair<Vertex,Arc> &xx, const std::pair<Vertex,Arc> &yy) { const Arc &x = xx.second, &y = yy.second; if (xx.first != yy.first) return xx.first < yy.first; if (x.head != y.head) return x.head < y.head; return x.length < y.length; } }; // Compare arcs by direction struct cmp_by_direction { bool operator() (const std::pair<Vertex,Arc> &xx, const std::pair<Vertex,Arc> &yy) { const Arc &x = xx.second, &y = yy.second; if (xx.first != yy.first) return xx.first < yy.first; if (x.reverse != y.reverse) return x.reverse == true; if (x.forward != y.forward) return x.forward == false; if (x.head != y.head) return x.head < y.head; return x.length < y.length; } }; // Construct adjacency lists from the temporary list of arcs void init_arcs() { std::vector< std::pair<int, Arc> > &a = tmp_arcs; size_t i; // Remove redundant arcs std::sort(a.begin(), a.end(), cmp_by_direction()); i = 0; for (size_t j = 1; j < a.size(); ++j) { Arc &ai = a[i].second, &aj = a[j].second; if (a[i].first == a[j].first && ai.head == aj.head && ai.forward == aj.forward && ai.reverse == aj.reverse) continue; if (++i < j) a[i] = a[j]; } a.resize(i+1); // Merge forward and reverse arcs into one bidirectional arc std::sort(a.begin(), a.end(), cmp_by_head()); i = 0; for (size_t j = 1; j < a.size(); ++j) { Arc &ai = a[i].second, &aj = a[j].second; if (a[i].first == a[j].first && ai.head == aj.head && ai.length == aj.length) { ai.forward |= aj.forward; ai.reverse |= aj.reverse; continue; } if (++i < j) a[i] = a[j]; } a.resize(i+1); // Order arcs by direction and determine adjacency lists std::sort(a.begin(), a.end(), cmp_by_direction()); arcs.resize(a.size()); a_begin[0].resize(n); a_begin[1].resize(n); a_end[0].resize(n); a_end[1].resize(n); for (size_t j = 0; j < a.size(); ++j) { arcs[j] = a[j].second; if (j == 0 || a[j].first != a[j-1].first) { if (arcs[j].reverse) a_begin[0][a[j].first] = &arcs[j]; if (arcs[j].forward) a_begin[1][a[j].first] = &arcs[j]; } if (j+1 == a.size() || a[j].first != a[j+1].first) { if (arcs[j].reverse) a_end[0][a[j].first] = &arcs[j] + 1; if (arcs[j].forward) a_end[1][a[j].first] = &arcs[j] + 1; } if (j > 0 && a[j].first == a[j-1].first) { if (arcs[j].reverse != arcs[j-1].reverse) a_end[0][a[j].first] = &arcs[j]; if (arcs[j].forward != arcs[j-1].forward) a_begin[1][a[j].first] = &arcs[j]; } } a.clear(); } // Add arc to the temporary list of arcs bool add_tmp_arc(Vertex u, Vertex v, Distance w, bool undirected) { if (u < 0 || v < 0 || u >= n || v >= n) return false; tmp_arcs.push_back(std::make_pair(u, Arc(v, w, true, undirected))); tmp_arcs.push_back(std::make_pair(v, Arc(u, w, undirected, true))); m += 1 + undirected; return true; } // Read graph from file in DIMACS format // p sp n m - header: n vertices, m edges // c bla-bla - comment line // a u v w - arc (u,v) with length w bool read_dimacs(FILE *file, bool undirected = false) { char buf[512], c; long long u,v,w,m; bool inited = false; while (fgets(buf, sizeof(buf), file) != NULL) { if (buf[strlen(buf)-1] != '\n') { if (buf[0] != 'c') return false; while ((c = fgetc(file)) != '\n' && c != EOF); } else if (buf[0] == 'p') { if (inited) return false; inited = true; if (sscanf(buf, "p sp %lld %lld", &n, &m) != 2) return false; } else if (buf[0] == 'a') { if (sscanf(buf, "a %lld %lld %lld", &u, &v, &w) != 3) return false; if (!add_tmp_arc(u-1, v-1, w, undirected)) return false; } else if (buf[0] == 'c') continue; else return false; } finilize(); return true; } // Write file in DIMACS format void write_dimacs(FILE *file) { long long m; for (Vertex v = 0; v < n; ++v) m += get_degree(v, true); fprintf(file, "p sp %lld %lld\n", n, m); for (Vertex v = 0; v < n; ++v) { for (arc_iterator a = begin(v), e = end(v); a < e; ++a) { long long u = v, w = a->head, l = a->length; fprintf(file, "a %lld %lld %lld\n", u+1, w+1, l); } } } // Read graph from file in METIS format // n m [fmt] [ncon] - header: fmt = ijk: i - s (vertex size) is present, // j - w (vertex weights) are present, // k - l (edge lengths) are present, // ncon - number of vertex weights. All defaults are 1. // ... // s w_1 .. w_ncon v_1 l_1 ... - line for a vertex: size (if i), vertex weights (if j), edges with lengths (if k) bool read_metis(FILE *file, bool undirected = false) { int c, i = 0, fmt = 0, ncon = 0, skip = 0; long long elem = 0; Vertex v = 0, head; bool newline = true, inelem = false; do { c = fgetc(file); if (newline && c == '%') { while (c != '\n' && c != EOF) c = fgetc(file); } else if (isdigit(c)) { inelem = true; elem = elem*10 + c - '0'; } else if (isspace(c) || c == EOF) { if (inelem) { if (v == 0) { if (i == 0) n = elem; else if (i == 1) /* m = elem */; else if (i == 2) { if ((elem % 10 > 1) || ((elem/10) % 10 > 1) || elem > 111) return false; fmt = elem; skip = (fmt >= 100) + (fmt % 100 >= 10); } else if (i == 3) { if (fmt % 100 < 10) return false; ncon = elem; skip = (fmt >= 100) + ncon; } else return false; } else if (i >= skip) { if (fmt % 10 == 1) { if ((i-skip) % 2 == 0) head = elem-1; else if (!add_tmp_arc(v-1, head, elem, undirected)) return false; } else if (!add_tmp_arc(v-1, elem-1, 1, undirected)) return false; } ++i; elem = 0; inelem = false; } if (c == '\n' || (!newline && c == EOF)) { if (v > 0 && (i < skip || (fmt % 10 == 1 && (i-skip) % 2 == 1))) return false; ++v; i = 0; newline = true; } } else return false; } while (c != EOF); finilize(); return true; } public: Graph() : n(0), m(0), a_begin(2), a_end(2) {} Vertex get_n() const { return n; } // Get number of vertices size_t get_m() const { return m; } // Get number of arcs typedef Arc* arc_iterator; // Adjacency list iterator type // Get adjacency list iterator bounds arc_iterator begin(Vertex v, bool forward = true) const { return a_begin[forward][v]; } arc_iterator end(Vertex v, bool forward = true) const { return a_end[forward][v]; } // Get vertex degree size_t get_degree(Vertex v, bool forward) const { return end(v, forward) - begin(v, forward); } size_t get_degree(Vertex v) const { return get_degree(v, true) + get_degree(v, false); } // Read graph from file (if the file format is supported) bool read(char *filename, bool undirected = false) { FILE *file; if ((file = fopen(filename, "r")) == NULL) return false; if (read_dimacs(file, undirected)) { fclose(file); return true; } rewind(file); if (read_metis(file, undirected)) { fclose(file); return true; } fclose(file); return false; } // Write graph to file bool write(char *filename) { FILE *file; if ((file = fopen(filename, "w")) == NULL) return false; write_dimacs(file); return ferror(file) ? (fclose(file) && false) : !fclose(file); } // Graph construction interface // User should set n, add some arcs, and call finilize() // Set the number of vertices void set_n(Vertex nn) { n = nn; }; // Add (u,v) arc (with (v,u) arc if undirected) to the temporary list of arcs void add_arc(Vertex u, Vertex v, Distance w, bool undirected = false) { bool r = add_tmp_arc(u, v, w, undirected); assert(r); } // Construct adjacency lists from the temporary list of arcs void finilize() { init_arcs(); } };
Add Graph::write interface to write grap to file
Add Graph::write interface to write grap to file Graph::write() writes graph to a file in DIMACS format. There is an interface to create graph inside a program, one may want to write the result to a file.
C++
mit
savrus/hl
ba3df40c5daadb59ffa9a5c667388dd3acf0568b
data_structures/linked_list/problems/convert_sorted_to_bst/cpp/solution.cpp
data_structures/linked_list/problems/convert_sorted_to_bst/cpp/solution.cpp
/* * Problem description: Given a singly linked list where elements are sorted in ascending order, convert * it to a height balanced BST. * Solution time complexity: O(n log n) * Comments: Given solution is non-destructive to the list it's called upon. */ /** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: a tree node */ TreeNode *sortedListToBST(ListNode *head) { return sortedListToBST(head, nullptr); } private: /** * @param head: The first node of linked list. * @param end: The end node (exclusive) or a nullptr. * @return: a tree node which is the middle node of the list. */ ListNode *findMiddle(ListNode *head, ListNode *end) { if (head == nullptr || head == end) { return nullptr; } auto slow = head; auto fast = head; /* The test for fast or fast->next being a nullptr * is currently redundant. However, we keep it here * for safety - in case the function is called on * two nodes belonging to different lists. */ while ((fast != nullptr && fast->next != nullptr) && (fast != end && fast->next != end)) { slow = slow->next; fast = fast->next->next; } return slow; } /** * @param head: The first node of linked list. * @param end: The end node (exclusive) or a nullptr. * @return: a tree node */ TreeNode *sortedListToBST(ListNode *head, ListNode *end) { if (head == nullptr || head == end) { return nullptr; } auto mid = findMiddle(head, end); auto root = new TreeNode{ mid->val }; root->left = sortedListToBST(head, mid); root->right = sortedListToBST(mid->next, end); return root; } };
/* * Problem description: Given a singly linked list where elements are sorted in ascending order, convert * it to a height balanced BST. * Solution time complexity: O(n log n) * Comments: Given solution is non-destructive to the list it's called upon. See the comments * in the code for additional details. */ /** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: a tree node */ TreeNode *sortedListToBST(ListNode *head) { return sortedListToBST(head, nullptr); } private: /** * @param head: The first node of linked list. * @param end: The end node (exclusive) or a nullptr. * @return: a tree node which is the middle node of the list. */ ListNode *findMiddle(ListNode *head, ListNode *end) { if (head == nullptr || head == end) { return nullptr; } auto slow = head; auto fast = head; /* The test for fast or fast->next being a nullptr * is currently redundant. However, we keep it here * for safety - in case the function is called on * two nodes belonging to different lists. */ while ((fast != nullptr && fast->next != nullptr) && (fast != end && fast->next != end)) { slow = slow->next; fast = fast->next->next; } return slow; } /** * @param head: The first node of linked list. * @param end: The end node (exclusive) or a nullptr. * @return: a tree node */ TreeNode *sortedListToBST(ListNode *head, ListNode *end) { if (head == nullptr || head == end) { return nullptr; } auto mid = findMiddle(head, end); auto root = new TreeNode{ mid->val }; root->left = sortedListToBST(head, mid); root->right = sortedListToBST(mid->next, end); return root; } };
Update solution.cpp
Update solution.cpp
C++
mit
lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms
636cafef941a6eee6adb9c3c704f4c5aac1686cd
example/cifar10/main.cpp
example/cifar10/main.cpp
#define NEU_CONVOLUTION_LAYER_USE_VECTORIZED_KERNEL #include <iostream> #include <boost/timer.hpp> #include <boost/program_options.hpp> #include <neu/vector_io.hpp> #include <neu/layers_algorithm.hpp> #include <neu/kernel.hpp> //#include <neu/learning_rate_gen/subtract_delta_weight.hpp> //#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp> //#include <neu/learning_rate_gen/weight_decay.hpp> #include <neu/learning_rate_gen/weight_decay_and_momentum.hpp> #include <neu/activation_func/sigmoid.hpp> #include <neu/activation_func/rectifier.hpp> #include <neu/activation_func/identity.hpp> #include <neu/activation_func/softmax_loss.hpp> #include <neu/activation_layer.hpp> #include <neu/convolution_layer.hpp> #include <neu/max_pooling_layer.hpp> #include <neu/average_pooling_layer.hpp> #include <neu/fully_connected_layer.hpp> #include <neu/layer.hpp> #include <neu/load_data_set/load_cifar10.hpp> #include <neu/data_set.hpp> int main(int argc, char** argv) { std::cout << "hello world" << std::endl; constexpr auto label_num = 10u; constexpr auto data_num_per_label = 10u; constexpr auto input_dim = 32u*32u*3u; constexpr auto batch_size = label_num * data_num_per_label; //std::random_device rd; std::mt19937 rand(rd()); std::mt19937 rand(3); std::cout << "INFO: fixed random engine" << std::endl; auto data = neu::load_cifar10("../../../data/cifar-10-batches-bin/"); for(auto& labeled : data) { for(auto& d : labeled) { std::transform(d.begin(), d.end(), d.begin(), [](auto e){ return (e-127.); }); } } auto ds = neu::make_data_set(label_num, data_num_per_label, input_dim, data, rand); auto conv1_param = neu::convolution_layer_parameter() .input_width(32).input_channel_num(3).output_channel_num(32) .filter_width(5).stride(1).pad(2).batch_size(batch_size); auto pool1_param = neu::make_max_pooling_layer_parameter(conv1_param) .filter_width(3).stride(2).pad(1); auto relu1_param = neu::make_activation_layer_parameter(pool1_param); auto conv2_param = neu::make_convolution_layer_parameter(pool1_param) .output_channel_num(32).filter_width(5).stride(1).pad(2); auto relu2_param = neu::make_activation_layer_parameter(conv2_param); auto pool2_param = neu::make_average_pooling_layer_parameter(conv2_param) .filter_width(3).stride(2).pad(1); auto conv3_param = neu::make_convolution_layer_parameter(pool2_param) .output_channel_num(64).filter_width(5).stride(1).pad(2); auto relu3_param = neu::make_activation_layer_parameter(conv3_param); auto pool3_param = neu::make_average_pooling_layer_parameter(conv3_param) .filter_width(3).stride(2).pad(1); auto fc1_param = neu::make_fully_connected_layer_parameter(pool3_param) .output_dim(64); auto fc2_param = neu::make_fully_connected_layer_parameter(fc1_param) .output_dim(label_num); auto softmax_loss_param = neu::make_activation_layer_parameter(fc2_param); auto conv1_g = [&rand, dist=std::normal_distribution<>(0.f, 0.0001f)] () mutable { return dist(rand); }; auto conv23_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)] () mutable { return dist(rand); }; auto fc12_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)] () mutable { return dist(rand); }; auto constant_g = [](){ return 0.f; }; neu::scalar base_lr = 0.001; neu::scalar momentum = 0.9; //neu::scalar weight_decay = 0.004; neu::scalar weight_decay = 0.0; auto conv1 = neu::make_convolution_layer(conv1_param, conv1_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv1_param.weight_dim(), conv1_param.bias_dim())); auto pool1 = neu::make_max_pooling_layer(pool1_param); auto relu1 = neu::make_activation_layer<neu::rectifier>(relu1_param); auto conv2 = neu::make_convolution_layer(conv2_param, conv23_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv2_param.weight_dim(), conv2_param.bias_dim())); auto relu2 = neu::make_activation_layer<neu::rectifier>(relu2_param); auto pool2 = neu::make_uniform_average_pooling_layer(pool2_param); auto conv3 = neu::make_convolution_layer(conv3_param, conv23_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv3_param.weight_dim(), conv3_param.bias_dim())); auto relu3 = neu::make_activation_layer<neu::rectifier>(relu3_param); auto pool3 = neu::make_uniform_average_pooling_layer(pool3_param); auto fc1 = neu::make_fully_connected_layer(fc1_param, fc12_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, fc1_param.weight_dim(), fc1_param.bias_dim())); auto fc2 = neu::make_fully_connected_layer(fc2_param, fc12_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, fc2_param.weight_dim(), fc2_param.bias_dim())); std::cout << "fc2 output dim directly: " << fc2.get_next_input().size() << std::endl; auto softmax_loss = neu::make_activation_layer<neu::softmax_loss>(softmax_loss_param); auto layers = std::vector<neu::layer>{ std::ref(conv1), pool1, relu1, std::ref(conv2), relu2, pool2, std::ref(conv3), relu3, pool3, std::ref(fc1), std::ref(fc2), softmax_loss }; std::ofstream mse_log("mean_square_error.txt"); std::ofstream cel_log("cross_entropy_loss.txt"); std::ofstream log("log.txt"); make_next_batch(ds); boost::timer timer; boost::timer update_timer; for(auto i = 0u; i < 5000u; ++i) { timer.restart(); auto batch = ds.get_batch(); const auto input = batch.train_data; const auto teach = batch.teach_data; auto make_next_batch_future = ds.async_make_next_batch(); std::cout << "forward..." << std::endl; neu::layers_forward(layers, input); std::cout << "forward finished " << timer.elapsed() << std::endl; auto output = layers.back().get_next_input(); auto error = neu::calc_last_layer_delta(output, teach); std::cout << "backward..." << std::endl; timer.restart(); neu::layers_backward(layers, error); std::cout << "backward finished" << timer.elapsed() << std::endl; std::cout << "update..." << std::endl; timer.restart(); neu::layers_update(layers); std::cout << "update finished" << timer.elapsed() << std::endl; std::cout << "calc error..." << std::endl; timer.restart(); auto mse = neu::mean_square_error(error); std::cout << i << ":mean square error: " << mse << std::endl; mse_log << i << "\t" << mse << std::endl; auto cel = neu::cross_entropy_loss(output, teach); cel_log << i << "\t" << cel << std::endl; std::cout << "cross entropy loss: " << cel << std::endl; std::cout << "error calculation finished" << timer.elapsed() << std::endl; make_next_batch_future.wait(); } }
#define NEU_CONVOLUTION_LAYER_USE_VECTORIZED_KERNEL #include <iostream> #include <boost/timer.hpp> #include <boost/program_options.hpp> #include <neu/vector_io.hpp> #include <neu/layers_algorithm.hpp> #include <neu/kernel.hpp> //#include <neu/learning_rate_gen/subtract_delta_weight.hpp> //#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp> //#include <neu/learning_rate_gen/weight_decay.hpp> #include <neu/learning_rate_gen/weight_decay_and_momentum.hpp> #include <neu/activation_func/sigmoid.hpp> #include <neu/activation_func/rectifier.hpp> #include <neu/activation_func/identity.hpp> #include <neu/activation_func/softmax_loss.hpp> #include <neu/activation_layer.hpp> #include <neu/convolution_layer.hpp> #include <neu/max_pooling_layer.hpp> #include <neu/average_pooling_layer.hpp> #include <neu/fully_connected_layer.hpp> #include <neu/layer.hpp> #include <neu/load_data_set/load_cifar10.hpp> #include <neu/data_set.hpp> int main(int argc, char** argv) { namespace po = boost::program_options; constexpr auto label_num = 10u; constexpr auto input_dim = 32u*32u*3u; constexpr auto test_data_num_per_label = 1000; int data_num_per_label; int iteration_limit; neu::scalar base_lr; neu::scalar momentum; //neu::scalar weight_decay = 0.004; neu::scalar weight_decay; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("data_num_per_label", po::value<int>(&data_num_per_label)->default_value(10), "set number of data per label for Batch SGD") ("iteration_limit", po::value<int>(&iteration_limit)->default_value(5000), "set training iteration limit") ("base_lr", po::value<neu::scalar>(&base_lr)->default_value(0.001), "set base learning rate") ("momentum", po::value<neu::scalar>(&momentum)->default_value(0.9), "set momentum rate") ("weight_decay", po::value<neu::scalar>(&weight_decay)->default_value(0.), "set weight decay rate") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); auto batch_size = label_num * data_num_per_label; if (vm.count("help")) { std::cout << desc << "\n"; return 1; } std::cout << "data_num_per_label was set to " << data_num_per_label << "."; std::cout << "(so batch_size was set to 10*" << data_num_per_label << "=" << batch_size << ".)\n"; std::cout << "iteration_limit was set to " << iteration_limit << ".\n"; std::cout << "base_lr was set to " << base_lr << ".\n"; std::cout << "momentum was set to " << momentum << ".\n"; std::cout << "weight_decay was set to " << weight_decay << ".\n"; //std::random_device rd; std::mt19937 rand(rd()); std::mt19937 rand(3); std::cout << "INFO: fixed random engine" << std::endl; auto data = neu::load_cifar10("../../../data/cifar-10-batches-bin/"); for(auto& labeled : data) { for(auto& d : labeled) { std::transform(d.begin(), d.end(), d.begin(), [](auto e){ return (e-127.); }); } } auto ds = neu::make_data_set(label_num, data_num_per_label, input_dim, data, rand); auto conv1_param = neu::convolution_layer_parameter() .input_width(32).input_channel_num(3).output_channel_num(32) .filter_width(5).stride(1).pad(2).batch_size(batch_size); auto pool1_param = neu::make_max_pooling_layer_parameter(conv1_param) .filter_width(3).stride(2).pad(1); auto relu1_param = neu::make_activation_layer_parameter(pool1_param); auto conv2_param = neu::make_convolution_layer_parameter(pool1_param) .output_channel_num(32).filter_width(5).stride(1).pad(2); auto relu2_param = neu::make_activation_layer_parameter(conv2_param); auto pool2_param = neu::make_average_pooling_layer_parameter(conv2_param) .filter_width(3).stride(2).pad(1); auto conv3_param = neu::make_convolution_layer_parameter(pool2_param) .output_channel_num(64).filter_width(5).stride(1).pad(2); auto relu3_param = neu::make_activation_layer_parameter(conv3_param); auto pool3_param = neu::make_average_pooling_layer_parameter(conv3_param) .filter_width(3).stride(2).pad(1); auto fc1_param = neu::make_fully_connected_layer_parameter(pool3_param) .output_dim(64); auto fc2_param = neu::make_fully_connected_layer_parameter(fc1_param) .output_dim(label_num); auto softmax_loss_param = neu::make_activation_layer_parameter(fc2_param); auto conv1_g = [&rand, dist=std::normal_distribution<>(0.f, 0.0001f)] () mutable { return dist(rand); }; auto conv23_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)] () mutable { return dist(rand); }; auto fc12_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)] () mutable { return dist(rand); }; auto constant_g = [](){ return 0.f; }; neu::scalar base_lr = 0.001; neu::scalar momentum = 0.9; //neu::scalar weight_decay = 0.004; neu::scalar weight_decay = 0.0; auto conv1 = neu::make_convolution_layer(conv1_param, conv1_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv1_param.weight_dim(), conv1_param.bias_dim())); auto pool1 = neu::make_max_pooling_layer(pool1_param); auto relu1 = neu::make_activation_layer<neu::rectifier>(relu1_param); auto conv2 = neu::make_convolution_layer(conv2_param, conv23_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv2_param.weight_dim(), conv2_param.bias_dim())); auto relu2 = neu::make_activation_layer<neu::rectifier>(relu2_param); auto pool2 = neu::make_uniform_average_pooling_layer(pool2_param); auto conv3 = neu::make_convolution_layer(conv3_param, conv23_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, conv3_param.weight_dim(), conv3_param.bias_dim())); auto relu3 = neu::make_activation_layer<neu::rectifier>(relu3_param); auto pool3 = neu::make_uniform_average_pooling_layer(pool3_param); auto fc1 = neu::make_fully_connected_layer(fc1_param, fc12_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, fc1_param.weight_dim(), fc1_param.bias_dim())); auto fc2 = neu::make_fully_connected_layer(fc2_param, fc12_g, constant_g, neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay, fc2_param.weight_dim(), fc2_param.bias_dim())); std::cout << "fc2 output dim directly: " << fc2.get_next_input().size() << std::endl; auto softmax_loss = neu::make_activation_layer<neu::softmax_loss>(softmax_loss_param); auto layers = std::vector<neu::layer>{ std::ref(conv1), pool1, relu1, std::ref(conv2), relu2, pool2, std::ref(conv3), relu3, pool3, std::ref(fc1), std::ref(fc2), softmax_loss }; std::ofstream mse_log("mean_square_error.txt"); std::ofstream cel_log("cross_entropy_loss.txt"); std::ofstream log("log.txt"); make_next_batch(ds); boost::timer timer; boost::timer update_timer; for(auto i = 0u; i < 5000u; ++i) { timer.restart(); auto batch = ds.get_batch(); const auto input = batch.train_data; const auto teach = batch.teach_data; auto make_next_batch_future = ds.async_make_next_batch(); std::cout << "forward..." << std::endl; neu::layers_forward(layers, input); std::cout << "forward finished " << timer.elapsed() << std::endl; auto output = layers.back().get_next_input(); auto error = neu::calc_last_layer_delta(output, teach); std::cout << "backward..." << std::endl; timer.restart(); neu::layers_backward(layers, error); std::cout << "backward finished" << timer.elapsed() << std::endl; std::cout << "update..." << std::endl; timer.restart(); neu::layers_update(layers); std::cout << "update finished" << timer.elapsed() << std::endl; std::cout << "calc error..." << std::endl; timer.restart(); auto mse = neu::mean_square_error(error); std::cout << i << ":mean square error: " << mse << std::endl; mse_log << i << "\t" << mse << std::endl; auto cel = neu::cross_entropy_loss(output, teach); cel_log << i << "\t" << cel << std::endl; std::cout << "cross entropy loss: " << cel << std::endl; std::cout << "error calculation finished" << timer.elapsed() << std::endl; make_next_batch_future.wait(); } }
add program option codes
add program option codes
C++
mit
okdshin/Neu,okdshin/Neu
655a90e38ae9869050d356f99dd90692c7636b10
plugins/single_plugins/expo.cpp
plugins/single_plugins/expo.cpp
#include <core.hpp> #include <opengl.hpp> void trigger_scale_change(int scX, int scY) { SignalListenerData sigData; sigData.push_back(&scX); sigData.push_back(&scY); core->trigger_signal("screen-scale-changed", sigData); } class Expo : public Plugin { private: KeyBinding toggle; ButtonBinding press, move; int max_steps; Hook hook, move_hook; bool active; Key toggleKey; int target_vx, target_vy; /* maximal viewports are 32, so these are enough for making it */ GLuint fbuffs[32][32], textures[32][32]; public: void updateConfiguration() { max_steps = getSteps(options["duration"]->data.ival); toggleKey = *options["activate"]->data.key; if (toggleKey.key == 0) return; using namespace std::placeholders; toggle.key = toggleKey.key; toggle.mod = toggleKey.mod; toggle.action = std::bind(std::mem_fn(&Expo::Toggle), this, _1); core->add_key(&toggle, true); auto move_button = *options["activate"]->data.but; if (move_button.button != 0) { move.action = std::bind(std::mem_fn(&Expo::on_move), this, _1); move.type = BindingTypePress; move.mod = move_button.mod; move.button = move_button.button; move.mod = WLC_BIT_MOD_ALT; move.button = BTN_LEFT; core->add_but(&move, false); std::cout << "move id is " << move.id << std::endl; } press.action = std::bind(std::mem_fn(&Expo::on_press), this, _1); press.type = BindingTypePress; press.mod = 0; press.button = BTN_LEFT; core->add_but(&press, false); hook.action = std::bind(std::mem_fn(&Expo::zoom), this); core->add_hook(&hook); } void init() { options.insert(newIntOption("duration", 1000)); options.insert(newKeyOption("activate", Key{0, 0})); options.insert(newButtonOption("move", Button{0, 0})); core->add_signal("screen-scale-changed"); active = false; std::memset(fbuffs, -1, sizeof(fbuffs)); std::memset(textures, -1, sizeof(textures)); } void initOwnership() { owner->name = "expo"; owner->compatAll = false; } struct tup { float begin, end; }; struct { int steps = 0; tup scale_x, scale_y, off_x, off_y; } zoom_target; struct { float scale_x, scale_y, off_x, off_y; } render_params; void Toggle(Context ctx) { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(vx, vy, core->get_current_viewport()); float center_w = vw / 2.f; float center_h = vh / 2.f; if (!active) { if (!core->activate_owner(owner)) return; owner->grab(); core->set_renderer(0, std::bind(std::mem_fn(&Expo::render), this)); move.enable(); press.enable(); target_vx = vx; target_vy = vy; zoom_target.steps = 0; zoom_target.scale_x = {1, 1.f / vw}; zoom_target.scale_y = {1, 1.f / vh}; zoom_target.off_x = {0, ((vx - center_w) * 2.f + 1.f) / vw}; zoom_target.off_y = {0, ((center_h - vy) * 2.f - 1.f) / vh}; } else { move.disable(); press.disable(); core->switch_workspace(std::make_tuple(target_vx, target_vy)); zoom_target.steps = 0; zoom_target.scale_x = {1.f / vw, 1}; zoom_target.scale_y = {1.f / vh, 1}; zoom_target.off_x = {((target_vx - center_w) * 2.f + 1.f) / vw, 0}; zoom_target.off_y = {((center_h - target_vy) * 2.f - 1.f) / vh, 0}; } active = !active; hook.enable(); } #define GetProgress(start,end,curstep,steps) ((float(end)*(curstep)+float(start) \ *((steps)-(curstep)))/(steps)) void zoom() { if(zoom_target.steps == max_steps) { hook.disable(); if (!active) { core->deactivate_owner(owner); core->set_redraw_everything(false); core->reset_renderer(); move.disable(); trigger_scale_change(1, 1); } else { GetTuple(vw, vh, core->get_viewport_grid_size()); trigger_scale_change(vw, vh); } render_params.scale_x = zoom_target.scale_x.end; render_params.scale_y = zoom_target.scale_y.end; render_params.off_x = zoom_target.off_x.end; render_params.off_y = zoom_target.off_y.end; } else { render_params.scale_x = GetProgress(zoom_target.scale_x.begin, zoom_target.scale_x.end, zoom_target.steps, max_steps); render_params.scale_y = GetProgress(zoom_target.scale_y.begin, zoom_target.scale_y.end, zoom_target.steps, max_steps); render_params.off_x = GetProgress(zoom_target.off_x.begin, zoom_target.off_x.end, zoom_target.steps, max_steps); render_params.off_y = GetProgress(zoom_target.off_y.begin, zoom_target.off_y.end, zoom_target.steps, max_steps); ++zoom_target.steps; } } void render() { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(vx, vy, core->get_current_viewport()); GetTuple(w, h, core->getScreenSize()); auto matrix = glm::translate(glm::mat4(), glm::vec3(render_params.off_x, render_params.off_y, 0)); matrix = glm::scale(matrix, glm::vec3(render_params.scale_x, render_params.scale_y, 1)); OpenGL::useDefaultProgram(); //OpenGL::set_transform(matrix); for(int i = 0; i < vw; i++) { for(int j = 0; j < vh; j++) { core->texture_from_viewport(std::make_tuple(i, j), fbuffs[i][j], textures[i][j]); wlc_geometry g = { .origin = {(i - vx) * w, (j - vy) * h}, .size = {(uint32_t) w, (uint32_t) h}}; OpenGL::renderTransformedTexture(textures[i][j], g, matrix, TEXTURE_TRANSFORM_INVERT_Y); } } } void on_press(Context ctx) { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(sw, sh, core->getScreenSize()); std::cout << "pressed " << std::endl; int vpw = sw / vw; int vph = sh / vh; target_vx = ctx.xev.xbutton.x_root / vpw; target_vy = ctx.xev.xbutton.y_root / vph; Toggle(ctx); } void on_move(Context ctx) { auto v = find_view_at_point(ctx.xev.xbutton.x_root, ctx.xev.xbutton.y_root); if (!v) return; SignalListenerData data; data.push_back(&v); wlc_point p = {ctx.xev.xbutton.x_root, ctx.xev.xbutton.y_root}; data.push_back(&p); core->trigger_signal("move-request", data); } View find_view_at_point(int px, int py) { GetTuple(w, h, core->getScreenSize()); GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(cvx, cvy, core->get_current_viewport()); int vpw = w / vw; int vph = h / vh; int vx = px / vpw; int vy = py / vph; int x = px % vpw; int y = py % vph; int realx = (vx - cvx) * w + x * vw; int realy = (vy - cvy) * h + y * vh; return core->get_view_at_point(realx, realy); } }; extern "C" { Plugin *newInstance() { return new Expo(); } }
#include <core.hpp> #include <opengl.hpp> void trigger_scale_change(int scX, int scY) { SignalListenerData sigData; sigData.push_back(&scX); sigData.push_back(&scY); core->trigger_signal("screen-scale-changed", sigData); } class Expo : public Plugin { private: KeyBinding toggle; ButtonBinding press, move; SignalListener viewport_changed; int max_steps; Hook hook, move_hook; bool active; Key toggleKey; int target_vx, target_vy; /* maximal viewports are 32, so these are enough for making it */ GLuint fbuffs[32][32], textures[32][32]; public: void updateConfiguration() { max_steps = getSteps(options["duration"]->data.ival); toggleKey = *options["activate"]->data.key; if (toggleKey.key == 0) return; using namespace std::placeholders; toggle.key = toggleKey.key; toggle.mod = toggleKey.mod; toggle.action = std::bind(std::mem_fn(&Expo::Toggle), this, _1); core->add_key(&toggle, true); auto move_button = *options["activate"]->data.but; if (move_button.button != 0) { move.action = std::bind(std::mem_fn(&Expo::on_move), this, _1); move.type = BindingTypePress; move.mod = move_button.mod; move.button = move_button.button; move.mod = WLC_BIT_MOD_ALT; move.button = BTN_LEFT; core->add_but(&move, false); std::cout << "move id is " << move.id << std::endl; } press.action = std::bind(std::mem_fn(&Expo::on_press), this, _1); press.type = BindingTypePress; press.mod = 0; press.button = BTN_LEFT; core->add_but(&press, false); hook.action = std::bind(std::mem_fn(&Expo::zoom), this); core->add_hook(&hook); } void init() { options.insert(newIntOption("duration", 1000)); options.insert(newKeyOption("activate", Key{0, 0})); options.insert(newButtonOption("move", Button{0, 0})); core->add_signal("screen-scale-changed"); active = false; std::memset(fbuffs, -1, sizeof(fbuffs)); std::memset(textures, -1, sizeof(textures)); using namespace std::placeholders; viewport_changed.action = std::bind(std::mem_fn(&Expo::on_viewport_changed), this, _1); core->connect_signal("viewport-change-notify", &viewport_changed); } void initOwnership() { owner->name = "expo"; owner->compatAll = false; } struct tup { float begin, end; }; struct { int steps = 0; tup scale_x, scale_y, off_x, off_y; } zoom_target; struct { float scale_x, scale_y, off_x, off_y; } render_params; void Toggle(Context ctx) { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(vx, vy, core->get_current_viewport()); float center_w = vw / 2.f; float center_h = vh / 2.f; if (!active) { if (!core->activate_owner(owner)) return; owner->grab(); core->set_renderer(0, std::bind(std::mem_fn(&Expo::render), this)); move.enable(); press.enable(); target_vx = vx; target_vy = vy; zoom_target.steps = 0; zoom_target.scale_x = {1, 1.f / vw}; zoom_target.scale_y = {1, 1.f / vh}; zoom_target.off_x = {0, ((vx - center_w) * 2.f + 1.f) / vw}; zoom_target.off_y = {0, ((center_h - vy) * 2.f - 1.f) / vh}; } else { move.disable(); press.disable(); core->switch_workspace(std::make_tuple(target_vx, target_vy)); zoom_target.steps = 0; zoom_target.scale_x = {1.f / vw, 1}; zoom_target.scale_y = {1.f / vh, 1}; zoom_target.off_x = {((target_vx - center_w) * 2.f + 1.f) / vw, 0}; zoom_target.off_y = {((center_h - target_vy) * 2.f - 1.f) / vh, 0}; } active = !active; hook.enable(); } #define GetProgress(start,end,curstep,steps) ((float(end)*(curstep)+float(start) \ *((steps)-(curstep)))/(steps)) void zoom() { if(zoom_target.steps == max_steps) { hook.disable(); if (!active) { core->deactivate_owner(owner); core->set_redraw_everything(false); core->reset_renderer(); move.disable(); trigger_scale_change(1, 1); } else { GetTuple(vw, vh, core->get_viewport_grid_size()); trigger_scale_change(vw, vh); } render_params.scale_x = zoom_target.scale_x.end; render_params.scale_y = zoom_target.scale_y.end; render_params.off_x = zoom_target.off_x.end; render_params.off_y = zoom_target.off_y.end; } else { render_params.scale_x = GetProgress(zoom_target.scale_x.begin, zoom_target.scale_x.end, zoom_target.steps, max_steps); render_params.scale_y = GetProgress(zoom_target.scale_y.begin, zoom_target.scale_y.end, zoom_target.steps, max_steps); render_params.off_x = GetProgress(zoom_target.off_x.begin, zoom_target.off_x.end, zoom_target.steps, max_steps); render_params.off_y = GetProgress(zoom_target.off_y.begin, zoom_target.off_y.end, zoom_target.steps, max_steps); ++zoom_target.steps; } } void render() { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(vx, vy, core->get_current_viewport()); GetTuple(w, h, core->getScreenSize()); auto matrix = glm::translate(glm::mat4(), glm::vec3(render_params.off_x, render_params.off_y, 0)); matrix = glm::scale(matrix, glm::vec3(render_params.scale_x, render_params.scale_y, 1)); OpenGL::useDefaultProgram(); //OpenGL::set_transform(matrix); for(int i = 0; i < vw; i++) { for(int j = 0; j < vh; j++) { core->texture_from_viewport(std::make_tuple(i, j), fbuffs[i][j], textures[i][j]); wlc_geometry g = { .origin = {(i - vx) * w, (j - vy) * h}, .size = {(uint32_t) w, (uint32_t) h}}; OpenGL::renderTransformedTexture(textures[i][j], g, matrix, TEXTURE_TRANSFORM_INVERT_Y); } } } void on_press(Context ctx) { GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(sw, sh, core->getScreenSize()); std::cout << "pressed " << std::endl; int vpw = sw / vw; int vph = sh / vh; target_vx = ctx.xev.xbutton.x_root / vpw; target_vy = ctx.xev.xbutton.y_root / vph; Toggle(ctx); } void on_move(Context ctx) { auto v = find_view_at_point(ctx.xev.xbutton.x_root, ctx.xev.xbutton.y_root); if (!v) return; SignalListenerData data; data.push_back(&v); wlc_point p = {ctx.xev.xbutton.x_root, ctx.xev.xbutton.y_root}; data.push_back(&p); core->trigger_signal("move-request", data); } View find_view_at_point(int px, int py) { GetTuple(w, h, core->getScreenSize()); GetTuple(vw, vh, core->get_viewport_grid_size()); GetTuple(cvx, cvy, core->get_current_viewport()); int vpw = w / vw; int vph = h / vh; int vx = px / vpw; int vy = py / vph; int x = px % vpw; int y = py % vph; int realx = (vx - cvx) * w + x * vw; int realy = (vy - cvy) * h + y * vh; return core->get_view_at_point(realx, realy); } void on_viewport_changed(SignalListenerData data) { GetTuple(vw, vh, core->get_viewport_grid_size()); std::cout << "vp changed" << std::endl; float center_w = vw / 2.f; float center_h = vh / 2.f; target_vx = *(int*)data[2]; target_vy = *(int*)data[3]; render_params.off_x = ((target_vx - center_w) * 2.f + 1.f) / vw; render_params.off_y = ((center_h - target_vy) * 2.f - 1.f) / vh; } }; extern "C" { Plugin *newInstance() { return new Expo(); } }
Add viewport-change-notify listener
Expo: Add viewport-change-notify listener
C++
mit
ammen99/wayfire,ammen99/wayfire
e8835da3c74ce442a4726369cb49726b493edbf3
src/abaclade/perf/stopwatch.cxx
src/abaclade/perf/stopwatch.cxx
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/perf/stopwatch.hxx> #if ABC_HOST_API_POSIX #include <time.h> #include <unistd.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::perf::stopwatch namespace abc { namespace perf { namespace { #if ABC_HOST_API_POSIX && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 std::pair<bool, ::clockid_t> get_timer_clock() { ::clockid_t clkid; // Try and get a timer specific to this process. if (::clock_getcpuclockid(0, &clkid) == 0) { return std::make_pair(true, std::move(clkid)); } #if defined(CLOCK_PROCESS_CPUTIME_ID) return std::make_pair(true, CLOCK_PROCESS_CPUTIME_ID); #endif //if defined(CLOCK_PROCESS_CPUTIME_ID) // No suitable timer to use. return std::make_pair(false, ::clockid_t()); } ::timespec get_time_point() { auto clkidTimer = get_timer_clock(); if (!clkidTimer.first) { // No suitable timer to use. // TODO: do something other than throw. throw 0; } ::timespec tsRet; ::clock_gettime(clkidTimer.second, &tsRet); return std::move(tsRet); } stopwatch::duration_type get_duration_ns(::timespec const & tsBegin, ::timespec const & tsEnd) { ABC_TRACE_FUNC(); typedef stopwatch::duration_type duration_type; duration_type iInterval = static_cast<duration_type>(tsEnd.tv_sec - tsBegin.tv_sec) * 1000000000; iInterval += static_cast<duration_type>(tsEnd.tv_nsec); iInterval -= static_cast<duration_type>(tsBegin.tv_nsec); return static_cast<duration_type>(iInterval); } #elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX ::FILETIME get_time_point() { ::FILETIME ftRet, ftUnused; ::GetProcessTimes(::GetCurrentProcess(), &ftUnused, &ftUnused, &ftUnused, &ftRet); return std::move(ftRet); } stopwatch::duration_type get_duration_ns(::FILETIME const & ftBegin, ::FILETIME const & ftEnd) { ABC_TRACE_FUNC(); // Compose the FILETIME arguments into 64-bit integers. ULARGE_INTEGER iBegin, iEnd; iBegin.LowPart = ftBegin.dwLowDateTime; iBegin.HighPart = ftBegin.dwHighDateTime; iEnd.LowPart = ftEnd.dwLowDateTime; iEnd.HighPart = ftEnd.dwHighDateTime; // FILETIME is in units of 100 ns, so scale it to 1 ns. return (iEnd.QuadPart - iBegin.QuadPart) * 100; } #else //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 // We could probably just use std::chrono here. #error "TODO: HOST_API" #endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else } //namespace stopwatch::stopwatch() : m_iTotalDuration(0) { } stopwatch::~stopwatch() { } void stopwatch::start() { ABC_TRACE_FUNC(this); auto timepoint(get_time_point()); *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime) = std::move(timepoint); } stopwatch::duration_type stopwatch::stop() { auto timepoint(get_time_point()); // We do this here to avoid adding ABC_TRACE_FUNC() to the timed execution. ABC_TRACE_FUNC(this); duration_type iPartialDuration = get_duration_ns( *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime), std::move(timepoint) ); m_iTotalDuration += iPartialDuration; return iPartialDuration; } } //namespace perf } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/perf/stopwatch.hxx> #if ABC_HOST_API_POSIX #include <time.h> #include <unistd.h> #endif #if ABC_HOST_API_DARWIN #include <mach/mach_time.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::perf::stopwatch namespace abc { namespace perf { namespace { #if ABC_HOST_API_POSIX && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 std::pair<bool, ::clockid_t> get_timer_clock() { ::clockid_t clkid; // Try and get a timer specific to this process. if (::clock_getcpuclockid(0, &clkid) == 0) { return std::make_pair(true, std::move(clkid)); } #if defined(CLOCK_PROCESS_CPUTIME_ID) return std::make_pair(true, CLOCK_PROCESS_CPUTIME_ID); #endif //if defined(CLOCK_PROCESS_CPUTIME_ID) // No suitable timer to use. return std::make_pair(false, ::clockid_t()); } ::timespec get_time_point() { auto clkidTimer = get_timer_clock(); if (!clkidTimer.first) { // No suitable timer to use. // TODO: do something other than throw. throw 0; } ::timespec tsRet; ::clock_gettime(clkidTimer.second, &tsRet); return std::move(tsRet); } stopwatch::duration_type get_duration_ns(::timespec const & tsBegin, ::timespec const & tsEnd) { ABC_TRACE_FUNC(); typedef stopwatch::duration_type duration_type; duration_type iInterval = static_cast<duration_type>(tsEnd.tv_sec - tsBegin.tv_sec) * 1000000000; iInterval += static_cast<duration_type>(tsEnd.tv_nsec); iInterval -= static_cast<duration_type>(tsBegin.tv_nsec); return static_cast<duration_type>(iInterval); } #elif ABC_HOST_API_DARWIN //if ABC_HOST_API_POSIX std::uint64_t get_time_point() { return ::mach_absolute_time(); } stopwatch::duration_type get_duration_ns(std::uint64_t iBegin, std::uint64_t iEnd) { ::mach_timebase_info_data_t mtid; ::mach_timebase_info(&mtid); return (iEnd - iBegin) * mtid.numer / mtid.denom; } #elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX … elif ABC_HOST_DARWIN ::FILETIME get_time_point() { ::FILETIME ftRet, ftUnused; ::GetProcessTimes(::GetCurrentProcess(), &ftUnused, &ftUnused, &ftUnused, &ftRet); return std::move(ftRet); } stopwatch::duration_type get_duration_ns(::FILETIME const & ftBegin, ::FILETIME const & ftEnd) { ABC_TRACE_FUNC(); // Compose the FILETIME arguments into 64-bit integers. ULARGE_INTEGER iBegin, iEnd; iBegin.LowPart = ftBegin.dwLowDateTime; iBegin.HighPart = ftBegin.dwHighDateTime; iEnd.LowPart = ftEnd.dwLowDateTime; iEnd.HighPart = ftEnd.dwHighDateTime; // FILETIME is in units of 100 ns, so scale it to 1 ns. return (iEnd.QuadPart - iBegin.QuadPart) * 100; } #else //if ABC_HOST_API_POSIX … elif ABC_HOST_DARWIN … elif ABC_HOST_API_WIN32 // We could probably just use std::chrono here. #error "TODO: HOST_API" #endif //if ABC_HOST_API_POSIX … elif ABC_HOST_DARWIN … elif ABC_HOST_API_WIN32 … else } //namespace stopwatch::stopwatch() : m_iTotalDuration(0) { } stopwatch::~stopwatch() { } void stopwatch::start() { ABC_TRACE_FUNC(this); auto timepoint(get_time_point()); *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime) = std::move(timepoint); } stopwatch::duration_type stopwatch::stop() { auto timepoint(get_time_point()); // We do this here to avoid adding ABC_TRACE_FUNC() to the timed execution. ABC_TRACE_FUNC(this); duration_type iPartialDuration = get_duration_ns( *reinterpret_cast<decltype(timepoint) *>(&m_abStartTime), std::move(timepoint) ); m_iTotalDuration += iPartialDuration; return iPartialDuration; } } //namespace perf } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
Implement abc::perf::stopwatch for Darwin
Implement abc::perf::stopwatch for Darwin
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
787a17d20e338de7268553ab1faa1415ee1bdabb
wasm/MarkLive.cpp
wasm/MarkLive.cpp
//===- MarkLive.cpp -------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements --gc-sections, which is a feature to remove unused // chunks from the output. Unused chunks are those that are not reachable from // known root symbols or chunks. This feature is implemented as a mark-sweep // garbage collector. // // Here's how it works. Each InputChunk has a "Live" bit. The bit is off by // default. Starting with the GC-roots, visit all reachable chunks and set their // Live bits. The Writer will then ignore chunks whose Live bits are off, so // that such chunk are not appear in the output. // //===----------------------------------------------------------------------===// #include "MarkLive.h" #include "Config.h" #include "InputChunks.h" #include "InputEvent.h" #include "InputGlobal.h" #include "SymbolTable.h" #include "Symbols.h" #define DEBUG_TYPE "lld" using namespace llvm; using namespace llvm::wasm; void lld::wasm::markLive() { if (!config->gcSections) return; LLVM_DEBUG(dbgs() << "markLive\n"); SmallVector<InputChunk *, 256> q; std::function<void(Symbol*)> enqueue = [&](Symbol *sym) { if (!sym || sym->isLive()) return; LLVM_DEBUG(dbgs() << "markLive: " << sym->getName() << "\n"); sym->markLive(); if (InputChunk *chunk = sym->getChunk()) q.push_back(chunk); // The ctor functions are all referenced by the synthetic callCtors // function. However, this function does not contain relocations so we // have to manually mark the ctors as live if callCtors itself is live. if (sym == WasmSym::callCtors) { if (config->isPic) enqueue(WasmSym::applyRelocs); for (const ObjFile *obj : symtab->objectFiles) { const WasmLinkingData &l = obj->getWasmObj()->linkingData(); for (const WasmInitFunc &f : l.InitFunctions) { auto* initSym = obj->getFunctionSymbol(f.Symbol); if (!initSym->isDiscarded()) enqueue(initSym); } } } }; // Add GC root symbols. if (!config->entry.empty()) enqueue(symtab->find(config->entry)); // We need to preserve any no-strip or exported symbol for (Symbol *sym : symtab->getSymbols()) if (sym->isNoStrip() || sym->isExported()) enqueue(sym); // For relocatable output, we need to preserve all the ctor functions if (config->relocatable) { for (const ObjFile *obj : symtab->objectFiles) { const WasmLinkingData &l = obj->getWasmObj()->linkingData(); for (const WasmInitFunc &f : l.InitFunctions) enqueue(obj->getFunctionSymbol(f.Symbol)); } } if (config->isPic) enqueue(WasmSym::callCtors); if (config->sharedMemory && !config->shared) enqueue(WasmSym::initMemory); // Follow relocations to mark all reachable chunks. while (!q.empty()) { InputChunk *c = q.pop_back_val(); for (const WasmRelocation reloc : c->getRelocations()) { if (reloc.Type == R_WASM_TYPE_INDEX_LEB) continue; Symbol *sym = c->file->getSymbol(reloc.Index); // If the function has been assigned the special index zero in the table, // the relocation doesn't pull in the function body, since the function // won't actually go in the table (the runtime will trap attempts to call // that index, since we don't use it). A function with a table index of // zero is only reachable via "call", not via "call_indirect". The stub // functions used for weak-undefined symbols have this behaviour (compare // equal to null pointer, only reachable via direct call). if (reloc.Type == R_WASM_TABLE_INDEX_SLEB || reloc.Type == R_WASM_TABLE_INDEX_I32) { auto *funcSym = cast<FunctionSymbol>(sym); if (funcSym->hasTableIndex() && funcSym->getTableIndex() == 0) continue; } enqueue(sym); } } // Report garbage-collected sections. if (config->printGcSections) { for (const ObjFile *obj : symtab->objectFiles) { for (InputChunk *c : obj->functions) if (!c->live) message("removing unused section " + toString(c)); for (InputChunk *c : obj->segments) if (!c->live) message("removing unused section " + toString(c)); for (InputGlobal *g : obj->globals) if (!g->live) message("removing unused section " + toString(g)); for (InputEvent *e : obj->events) if (!e->live) message("removing unused section " + toString(e)); } for (InputChunk *c : symtab->syntheticFunctions) if (!c->live) message("removing unused section " + toString(c)); for (InputGlobal *g : symtab->syntheticGlobals) if (!g->live) message("removing unused section " + toString(g)); } }
//===- MarkLive.cpp -------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements --gc-sections, which is a feature to remove unused // chunks from the output. Unused chunks are those that are not reachable from // known root symbols or chunks. This feature is implemented as a mark-sweep // garbage collector. // // Here's how it works. Each InputChunk has a "Live" bit. The bit is off by // default. Starting with the GC-roots, visit all reachable chunks and set their // Live bits. The Writer will then ignore chunks whose Live bits are off, so // that such chunk are not appear in the output. // //===----------------------------------------------------------------------===// #include "MarkLive.h" #include "Config.h" #include "InputChunks.h" #include "InputEvent.h" #include "InputGlobal.h" #include "SymbolTable.h" #include "Symbols.h" #define DEBUG_TYPE "lld" using namespace llvm; using namespace llvm::wasm; namespace lld { namespace wasm { namespace { class MarkLive { public: void run(); private: void enqueue(Symbol *sym); void markSymbol(Symbol *sym); void mark(); // A list of chunks to visit. SmallVector<InputChunk *, 256> queue; }; } // namespace void MarkLive::enqueue(Symbol *sym) { if (!sym || sym->isLive()) return; LLVM_DEBUG(dbgs() << "markLive: " << sym->getName() << "\n"); sym->markLive(); if (InputChunk *chunk = sym->getChunk()) queue.push_back(chunk); // The ctor functions are all referenced by the synthetic callCtors // function. However, this function does not contain relocations so we // have to manually mark the ctors as live if callCtors itself is live. if (sym == WasmSym::callCtors) { if (config->isPic) enqueue(WasmSym::applyRelocs); for (const ObjFile *obj : symtab->objectFiles) { const WasmLinkingData &l = obj->getWasmObj()->linkingData(); for (const WasmInitFunc &f : l.InitFunctions) { auto* initSym = obj->getFunctionSymbol(f.Symbol); if (!initSym->isDiscarded()) enqueue(initSym); } } } } void MarkLive::run() { // Add GC root symbols. if (!config->entry.empty()) enqueue(symtab->find(config->entry)); // We need to preserve any no-strip or exported symbol for (Symbol *sym : symtab->getSymbols()) if (sym->isNoStrip() || sym->isExported()) enqueue(sym); // For relocatable output, we need to preserve all the ctor functions if (config->relocatable) { for (const ObjFile *obj : symtab->objectFiles) { const WasmLinkingData &l = obj->getWasmObj()->linkingData(); for (const WasmInitFunc &f : l.InitFunctions) enqueue(obj->getFunctionSymbol(f.Symbol)); } } if (config->isPic) enqueue(WasmSym::callCtors); if (config->sharedMemory && !config->shared) enqueue(WasmSym::initMemory); mark(); } void MarkLive::mark() { // Follow relocations to mark all reachable chunks. while (!queue.empty()) { InputChunk *c = queue.pop_back_val(); for (const WasmRelocation reloc : c->getRelocations()) { if (reloc.Type == R_WASM_TYPE_INDEX_LEB) continue; Symbol *sym = c->file->getSymbol(reloc.Index); // If the function has been assigned the special index zero in the table, // the relocation doesn't pull in the function body, since the function // won't actually go in the table (the runtime will trap attempts to call // that index, since we don't use it). A function with a table index of // zero is only reachable via "call", not via "call_indirect". The stub // functions used for weak-undefined symbols have this behaviour (compare // equal to null pointer, only reachable via direct call). if (reloc.Type == R_WASM_TABLE_INDEX_SLEB || reloc.Type == R_WASM_TABLE_INDEX_I32) { auto *funcSym = cast<FunctionSymbol>(sym); if (funcSym->hasTableIndex() && funcSym->getTableIndex() == 0) continue; } enqueue(sym); } } } void markLive() { if (!config->gcSections) return; LLVM_DEBUG(dbgs() << "markLive\n"); MarkLive marker; marker.run(); // Report garbage-collected sections. if (config->printGcSections) { for (const ObjFile *obj : symtab->objectFiles) { for (InputChunk *c : obj->functions) if (!c->live) message("removing unused section " + toString(c)); for (InputChunk *c : obj->segments) if (!c->live) message("removing unused section " + toString(c)); for (InputGlobal *g : obj->globals) if (!g->live) message("removing unused section " + toString(g)); for (InputEvent *e : obj->events) if (!e->live) message("removing unused section " + toString(e)); } for (InputChunk *c : symtab->syntheticFunctions) if (!c->live) message("removing unused section " + toString(c)); for (InputGlobal *g : symtab->syntheticGlobals) if (!g->live) message("removing unused section " + toString(g)); } } } // namespace wasm } // namespace lld
Refactor markLive.cpp. NFC
[lld][WebAssembly] Refactor markLive.cpp. NFC This pattern matches the ELF implementation add if also useful as part of a planned change where running `mark` more than once is needed. Differential Revision: https://reviews.llvm.org/D68749 git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@374275 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
401bb43311d2bd15c140a4be840f304121bf9f57
src/arch/sparc/syscallreturn.hh
src/arch/sparc/syscallreturn.hh
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_SYSCALLRETURN_HH__ #define __ARCH_SPARC_SYSCALLRETURN_HH__ #include <inttypes.h> #include "sim/syscallreturn.hh" #include "arch/sparc/regfile.hh" #include "cpu/thread_context.hh" namespace SparcISA { static inline void setSyscallReturn(SyscallReturn return_value, ThreadContext * tc) { // check for error condition. SPARC syscall convention is to // indicate success/failure in reg the carry bit of the ccr // and put the return value itself in the standard return value reg (). if (return_value.successful()) { // no error, clear XCC.C tc->setIntReg(NumIntArchRegs + 2, tc->readIntReg(NumIntArchRegs + 2) & 0xEE); //tc->setMiscReg(MISCREG_CCR, tc->readMiscReg(MISCREG_CCR) & 0xEE); tc->setIntReg(ReturnValueReg, return_value.value()); } else { // got an error, set XCC.C tc->setIntReg(NumIntArchRegs + 2, tc->readIntReg(NumIntArchRegs + 2) | 0x11); //tc->setMiscReg(MISCREG_CCR, tc->readMiscReg(MISCREG_CCR) | 0x11); tc->setIntReg(ReturnValueReg, return_value.value()); } } }; #endif
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_SYSCALLRETURN_HH__ #define __ARCH_SPARC_SYSCALLRETURN_HH__ #include <inttypes.h> #include "sim/syscallreturn.hh" #include "arch/sparc/regfile.hh" #include "cpu/thread_context.hh" namespace SparcISA { static inline void setSyscallReturn(SyscallReturn return_value, ThreadContext * tc) { // check for error condition. SPARC syscall convention is to // indicate success/failure in reg the carry bit of the ccr // and put the return value itself in the standard return value reg (). if (return_value.successful()) { // no error, clear XCC.C tc->setIntReg(NumIntArchRegs + 2, tc->readIntReg(NumIntArchRegs + 2) & 0xEE); //tc->setMiscReg(MISCREG_CCR, tc->readMiscReg(MISCREG_CCR) & 0xEE); tc->setIntReg(ReturnValueReg, return_value.value()); } else { // got an error, set XCC.C tc->setIntReg(NumIntArchRegs + 2, tc->readIntReg(NumIntArchRegs + 2) | 0x11); //tc->setMiscReg(MISCREG_CCR, tc->readMiscReg(MISCREG_CCR) | 0x11); tc->setIntReg(ReturnValueReg, -return_value.value()); } } }; #endif
Change to use -return_value.value like other implementations.
Change to use -return_value.value like other implementations.
C++
bsd-3-clause
haowu4682/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,andrewfu0325/gem5-aladdin,LingxiaoJIA/gem5,LingxiaoJIA/gem5,andrewfu0325/gem5-aladdin,haowu4682/gem5,LingxiaoJIA/gem5,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,LingxiaoJIA/gem5,haowu4682/gem5,andrewfu0325/gem5-aladdin,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5