text
stringlengths
54
60.6k
<commit_before>#include <stdlib.h> #include <sys/stat.h> #include <syslog.h> #include <iostream> #include <cassert> #include <stdexcept> #include <algorithm> #include <numeric> #include <openssl/md5.h> #include "eyetil.h" #include "config.h" #ifdef HAVE_LIBUUID # include <uuid/uuid.h> #endif binary_t& binary_t::from_hex(const std::string& h) { std::string::size_type hs = h.length(); if(hs&1) throw std::runtime_error("odd number of characters in hexadecimal number"); int rvs = hs>>1; resize(rvs); const unsigned char *hp = (const unsigned char*)h.data(); iterator oi=begin(); char t[3] = { 0,0,0 }; for(int i=0;i<rvs;++i) { t[0]=*(hp++); t[1]=*(hp++); *(oi++) = strtol(t,0,16); } return *this; } binary_t& binary_t::from_data(const void *d,size_t s) { resize(s); std::copy((const unsigned char*)d,(const unsigned char *)d+s, begin() ); return *this; } binary_t& binary_t::make_nonce() { #ifdef HAVE_LIBUUID uuid_t uuid; uuid_generate(uuid); from_data((unsigned char*)uuid,sizeof(uuid)); #else resize(16); std::generate_n(begin(),16,rand); #endif /* HAVE_LIBUUID */ return *this; } std::string binary_t::hex() const { std::string rv; rv.reserve((size()<<1)+1); char t[3] = {0,0,0}; for(const_iterator i=begin(),ie=end();i!=ie;++i) { int rc = snprintf(t,sizeof(t),"%02x",*i); assert(rc<sizeof(t)); rv += t; } return rv; } binary_t binary_t::md5() const { binary_t rv(MD5_DIGEST_LENGTH); if(!MD5( (const unsigned char*)&(front()),size(), (unsigned char*)&(rv.front()) )) throw std::runtime_error("failed to md5()"); return rv; } void md5_digester::init() { if(!MD5_Init(&ctx)) throw std::runtime_error("failed to MD5_Init()"); } void md5_digester::update(const void *d,size_t l) { if(!MD5_Update(&ctx,d,l)) throw std::runtime_error("failed to MD5_Update()"); } binary_t md5_digester::final() { binary_t rv(MD5_DIGEST_LENGTH); if(!MD5_Final((unsigned char*)&(rv.front()), &ctx)) throw std::runtime_error("failed to MD5_Final()"); return rv; } static void make_path_for_template(const std::string& p,mode_t m) { struct stat st; std::string pp; for(std::string::size_type sl=p.find('/',1); sl!=std::string::npos; sl=p.find('/',sl+1)) { if(stat( (pp=p.substr(0,sl)).c_str() ,&st) || !S_ISDIR(st.st_mode)) { if(mkdir(pp.c_str(),m)) throw std::runtime_error("failed to mkdir()"); } } } tmpdir_t::tmpdir_t(const std::string& dt) : dir(dt) { make_path_for_template(dt,0777); if(!mkdtemp((char*)dir.data())) throw std::runtime_error("failed to mkdtmp()"); } tmpdir_t::~tmpdir_t() { assert(!dir.empty()); if(rmdir(dir.c_str())) { syslog(LOG_WARNING,"Failed to remove '%s' directory",dir.c_str()); } } std::string tmpdir_t::get_file(const std::string& f) { std::string::size_type ls = f.rfind('/'); return dir+'/'+( (ls==std::string::npos) ? f : f.substr(ls+1) ); } tarchive_t::tarchive_t(void *p,size_t s) : a(archive_read_new()), e(0) { if(!a) throw std::runtime_error("failed to archive_read_new()"); if(archive_read_support_format_tar(a)) { archive_read_finish(a); throw std::runtime_error("failed to archive_read_support_format_tar()"); } if(archive_read_open_memory(a,p,s)) { archive_read_finish(a); throw std::runtime_error("failed to archive_read_open_memory()"); } } tarchive_t::~tarchive_t() { assert(a); archive_read_finish(a); } bool tarchive_t::read_next_header() { assert(a); return archive_read_next_header(a,&e)==ARCHIVE_OK; } std::string tarchive_t::entry_pathname() { assert(a); assert(e); return archive_entry_pathname(e); } bool tarchive_t::read_data_into_fd(int fd) { assert(a); return archive_read_data_into_fd(a,fd)==ARCHIVE_OK; } #pragma pack(1) struct block512_t { enum { words = 512 / sizeof(uint16_t) }; uint16_t data[words]; static uint16_t tcpcksum(block512_t& data) { uint32_t sum = std::accumulate(data.data,data.data+words,0); while(uint32_t hw = sum>>16) sum = (sum&0xffff)+hw; return ~sum; } }; #pragma pack() binary_t integrity_digest(const void *ptr,size_t size,const std::string& ukey) { binary_t key; key.from_hex(ukey); std::vector<uint16_t> blksums; blksums.reserve(size/sizeof(block512_t)); block512_t *db = (block512_t*)ptr, *de = db + size/sizeof(block512_t); std::transform( db, de, std::back_inserter(blksums), block512_t::tcpcksum ); binary_t subject; subject.from_data((void*)&(blksums.front()),blksums.size()*sizeof(uint16_t)); std::copy( key.begin(), key.end(), std::back_inserter(subject) ); return subject.md5(); } <commit_msg>optimize integrity digest calculation memory use<commit_after>#include <stdlib.h> #include <sys/stat.h> #include <syslog.h> #include <iostream> #include <cassert> #include <stdexcept> #include <algorithm> #include <numeric> #include <openssl/md5.h> #include "eyetil.h" #include "config.h" #ifdef HAVE_LIBUUID # include <uuid/uuid.h> #endif binary_t& binary_t::from_hex(const std::string& h) { std::string::size_type hs = h.length(); if(hs&1) throw std::runtime_error("odd number of characters in hexadecimal number"); int rvs = hs>>1; resize(rvs); const unsigned char *hp = (const unsigned char*)h.data(); iterator oi=begin(); char t[3] = { 0,0,0 }; for(int i=0;i<rvs;++i) { t[0]=*(hp++); t[1]=*(hp++); *(oi++) = strtol(t,0,16); } return *this; } binary_t& binary_t::from_data(const void *d,size_t s) { resize(s); std::copy((const unsigned char*)d,(const unsigned char *)d+s, begin() ); return *this; } binary_t& binary_t::make_nonce() { #ifdef HAVE_LIBUUID uuid_t uuid; uuid_generate(uuid); from_data((unsigned char*)uuid,sizeof(uuid)); #else resize(16); std::generate_n(begin(),16,rand); #endif /* HAVE_LIBUUID */ return *this; } std::string binary_t::hex() const { std::string rv; rv.reserve((size()<<1)+1); char t[3] = {0,0,0}; for(const_iterator i=begin(),ie=end();i!=ie;++i) { int rc = snprintf(t,sizeof(t),"%02x",*i); assert(rc<sizeof(t)); rv += t; } return rv; } binary_t binary_t::md5() const { binary_t rv(MD5_DIGEST_LENGTH); if(!MD5( (const unsigned char*)&(front()),size(), (unsigned char*)&(rv.front()) )) throw std::runtime_error("failed to md5()"); return rv; } void md5_digester::init() { if(!MD5_Init(&ctx)) throw std::runtime_error("failed to MD5_Init()"); } void md5_digester::update(const void *d,size_t l) { if(!MD5_Update(&ctx,d,l)) throw std::runtime_error("failed to MD5_Update()"); } binary_t md5_digester::final() { binary_t rv(MD5_DIGEST_LENGTH); if(!MD5_Final((unsigned char*)&(rv.front()), &ctx)) throw std::runtime_error("failed to MD5_Final()"); return rv; } static void make_path_for_template(const std::string& p,mode_t m) { struct stat st; std::string pp; for(std::string::size_type sl=p.find('/',1); sl!=std::string::npos; sl=p.find('/',sl+1)) { if(stat( (pp=p.substr(0,sl)).c_str() ,&st) || !S_ISDIR(st.st_mode)) { if(mkdir(pp.c_str(),m)) throw std::runtime_error("failed to mkdir()"); } } } tmpdir_t::tmpdir_t(const std::string& dt) : dir(dt) { make_path_for_template(dt,0777); if(!mkdtemp((char*)dir.data())) throw std::runtime_error("failed to mkdtmp()"); } tmpdir_t::~tmpdir_t() { assert(!dir.empty()); if(rmdir(dir.c_str())) { syslog(LOG_WARNING,"Failed to remove '%s' directory",dir.c_str()); } } std::string tmpdir_t::get_file(const std::string& f) { std::string::size_type ls = f.rfind('/'); return dir+'/'+( (ls==std::string::npos) ? f : f.substr(ls+1) ); } tarchive_t::tarchive_t(void *p,size_t s) : a(archive_read_new()), e(0) { if(!a) throw std::runtime_error("failed to archive_read_new()"); if(archive_read_support_format_tar(a)) { archive_read_finish(a); throw std::runtime_error("failed to archive_read_support_format_tar()"); } if(archive_read_open_memory(a,p,s)) { archive_read_finish(a); throw std::runtime_error("failed to archive_read_open_memory()"); } } tarchive_t::~tarchive_t() { assert(a); archive_read_finish(a); } bool tarchive_t::read_next_header() { assert(a); return archive_read_next_header(a,&e)==ARCHIVE_OK; } std::string tarchive_t::entry_pathname() { assert(a); assert(e); return archive_entry_pathname(e); } bool tarchive_t::read_data_into_fd(int fd) { assert(a); return archive_read_data_into_fd(a,fd)==ARCHIVE_OK; } #pragma pack(1) struct block512_t { enum { words = 512 / sizeof(uint16_t) }; uint16_t data[words]; static uint16_t tcpcksum(block512_t& data) { uint32_t sum = std::accumulate(data.data,data.data+words,0); while(uint32_t hw = sum>>16) sum = (sum&0xffff)+hw; return ~sum; } }; #pragma pack() binary_t integrity_digest(const void *ptr,size_t size,const std::string& ukey) { md5_digester rv; std::transform( (block512_t*)ptr, ((block512_t*)ptr)+size/sizeof(block512_t), rv.updater<uint16_t>(), block512_t::tcpcksum ); rv.update( binary_t(ukey) ); return rv.final(); } <|endoftext|>
<commit_before>#include <iostream> using namespace std; class frame{ public: frame(); ~frame(); void setSOH(char c){ soh = c; } void setFrameNumber(int i){ frameNumber = i; } void setSTX(char c){ stx = c; } void setData(char c){ data = c; } void setETX(char c){ etx = c; } void setChecksum(string s){ checksum = s; } char getSOH(){ return soh; } int getFrameNumber(){ return i; } char getSTX(){ return stx; } char getData(){ return data; } char getETX(){ return etx; } char getChecksum(){ return checksum; } private: char soh; int frameNumber; char stx; char data; char etx; string checksum; };<commit_msg>Implement constructor<commit_after>#include <iostream> #include <cstring> #include "dcomm.h" using namespace std; class frame{ public: frame() : soh(SOH), stx(STX), etx(ETX) { frameNumber = 0; string s = ""; strcpy(data, s.c_str()); // setChecksum(); } frame(int i, string s) : soh(SOH), stx(STX), etx(ETX) { frameNumber = i; strcpy(data, s.c_str()); // setChecksum(); } ~frame(); void setSOH(char c){ soh = c; } void setFrameNumber(int i){ frameNumber = i; } void setSTX(char c){ stx = c; } void setData(string c){ } void setETX(char c){ etx = c; } void setChecksum(string s){ checksum = s; } char getSOH(){ return soh; } int getFrameNumber(){ return frameNumber; } char getSTX(){ return stx; } char* getData(){ return data; } char getETX(){ return etx; } string getChecksum(){ return checksum; } private: char soh; int frameNumber; char stx; char data[DATASIZE]; char etx; string checksum; };<|endoftext|>
<commit_before> #include "gibbs.h" #include "dstruct/factor_graph/inference_result.h" /* * Parse input arguments */ dd::CmdParser parse_input(int argc, char** argv){ std::vector<std::string> new_args; if (argc < 2) { new_args.push_back(std::string(argv[0]) + " " + "gibbs"); new_args.push_back("-h"); } else { new_args.push_back(std::string(argv[0]) + " " + std::string(argv[1])); for(int i=2;i<argc;i++){ new_args.push_back(std::string(argv[i])); } } char ** new_argv = new char*[new_args.size()]; for(size_t i=0;i<new_args.size();i++){ new_argv[i] = new char[new_args[i].length() + 1]; std::copy(new_args[i].begin(), new_args[i].end(), new_argv[i]); new_argv[i][new_args[i].length()] = '\0'; } std::string final_app_name; if (argc >= 2) final_app_name = argv[1]; else final_app_name = "gibbs"; dd::CmdParser cmd_parser(final_app_name); cmd_parser.parse(new_args.size(), new_argv); return cmd_parser; } void gibbs(dd::CmdParser & cmd_parser){ // number of NUMA nodes int n_numa_node = numa_max_node() + 1; // number of max threads per NUMA node int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node); // get command line arguments std::string fg_file = cmd_parser.fg_file->getValue(); std::string weight_file = cmd_parser.weight_file->getValue(); std::string variable_file = cmd_parser.variable_file->getValue(); std::string factor_file = cmd_parser.factor_file->getValue(); std::string edge_file = cmd_parser.edge_file->getValue(); std::string meta_file = cmd_parser.meta_file->getValue(); std::string output_folder = cmd_parser.output_folder->getValue(); int n_learning_epoch = cmd_parser.n_learning_epoch->getValue(); int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue(); int n_inference_epoch = cmd_parser.n_inference_epoch->getValue(); double stepsize = cmd_parser.stepsize->getValue(); double stepsize2 = cmd_parser.stepsize2->getValue(); // hack to support two parameters to specify step size if (stepsize == 0.01) stepsize = stepsize2; double decay = cmd_parser.decay->getValue(); int n_datacopy = cmd_parser.n_datacopy->getValue(); double reg_param = cmd_parser.reg_param->getValue(); double reg1_param = cmd_parser.reg1_param->getValue(); bool is_quiet = cmd_parser.quiet->getValue(); bool sample_evidence = cmd_parser.sample_evidence->getValue(); int burn_in = cmd_parser.burn_in->getValue(); bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue(); Meta meta = read_meta(fg_file); if (is_quiet) { std::cout << "Running in quiet mode..." << std::endl; } else { std::cout << std::endl; std::cout << "#################MACHINE CONFIG#################" << std::endl; std::cout << "# # NUMA Node : " << n_numa_node << std::endl; std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl; std::cout << "################################################" << std::endl; std::cout << std::endl; std::cout << "#################GIBBS SAMPLING#################" << std::endl; std::cout << "# fg_file : " << fg_file << std::endl; std::cout << "# edge_file : " << edge_file << std::endl; std::cout << "# weight_file : " << weight_file << std::endl; std::cout << "# variable_file : " << variable_file << std::endl; std::cout << "# factor_file : " << factor_file << std::endl; std::cout << "# meta_file : " << meta_file << std::endl; std::cout << "# output_folder : " << output_folder << std::endl; std::cout << "# n_learning_epoch : " << n_learning_epoch << std::endl; std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl; std::cout << "# n_inference_epoch : " << n_inference_epoch << std::endl; std::cout << "# stepsize : " << stepsize << std::endl; std::cout << "# decay : " << decay << std::endl; std::cout << "# regularization : " << reg_param << std::endl; std::cout << "# l1 regularization : " << reg1_param << std::endl; std::cout << "################################################" << std::endl; std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl; std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl; std::cout << "################################################" << std::endl; std::cout << "# nvar : " << meta.num_variables << std::endl; std::cout << "# nfac : " << meta.num_factors << std::endl; std::cout << "# nweight : " << meta.num_weights << std::endl; std::cout << "# nedge : " << meta.num_edges << std::endl; std::cout << "################################################" << std::endl; } // run on NUMA node 0 numa_run_on_node(0); numa_set_localalloc(); // load factor graph dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges); fg.load(cmd_parser, is_quiet); dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence); // number of learning epochs // the factor graph is copied on each NUMA node, so the total epochs = // epochs specified / number of NUMA nodes int numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); // learning gibbs.learn(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); // dump weights gibbs.dump_weights(is_quiet); // number of inference epochs int numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) + (n_inference_epoch%n_numa_node==0?0:1); // inference gibbs.inference(numa_aware_n_epoch, is_quiet); gibbs.aggregate_results_and_dump(is_quiet); // print weights from inference result for(long t=0;t<fg.n_weight;t++) { std::cout<<fg.infrs->weight_values[t]<<std::endl; } // print weights from factor graph std::cout<<"PRINTING WEIGHTS FROM WEIGHT VARIABLE"<<std::endl; for(long t=0;t<fg.n_weight;t++) { std::cout<<fg.weights[t].weight<<std::endl; } } void em(dd::CmdParser & cmd_parser){ // number of NUMA nodes int n_numa_node = numa_max_node() + 1; // number of max threads per NUMA node int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node); // get command line arguments std::string fg_file = cmd_parser.fg_file->getValue(); std::string weight_file = cmd_parser.weight_file->getValue(); std::string variable_file = cmd_parser.variable_file->getValue(); std::string factor_file = cmd_parser.factor_file->getValue(); std::string edge_file = cmd_parser.edge_file->getValue(); std::string meta_file = cmd_parser.meta_file->getValue(); std::string output_folder = cmd_parser.output_folder->getValue(); int n_learning_epoch = cmd_parser.n_learning_epoch->getValue(); int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue(); int n_inference_epoch = cmd_parser.n_inference_epoch->getValue(); double stepsize = cmd_parser.stepsize->getValue(); double stepsize2 = cmd_parser.stepsize2->getValue(); // hack to support two parameters to specify step size if (stepsize == 0.01) stepsize = stepsize2; double decay = cmd_parser.decay->getValue(); int n_datacopy = cmd_parser.n_datacopy->getValue(); double reg_param = cmd_parser.reg_param->getValue(); double reg1_param = cmd_parser.reg1_param->getValue(); bool is_quiet = cmd_parser.quiet->getValue(); bool check_convergence = cmd_parser.check_convergence->getValue(); bool sample_evidence = cmd_parser.sample_evidence->getValue(); int burn_in = cmd_parser.burn_in->getValue(); int n_iter = cmd_parser.n_iter->getValue(); int wl_conv = cmd_parser.wl_conv->getValue(); int delta = cmd_parser.delta->getValue(); bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue(); Meta meta = read_meta(fg_file); if (is_quiet) { std::cout << "Running in quiet mode..." << std::endl; } else { std::cout << std::endl; std::cout << "#################MACHINE CONFIG#################" << std::endl; std::cout << "# # NUMA Node : " << n_numa_node << std::endl; std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl; std::cout << "################################################" << std::endl; std::cout << std::endl; std::cout << "#################GIBBS SAMPLING#################" << std::endl; std::cout << "# fg_file : " << fg_file << std::endl; std::cout << "# edge_file : " << edge_file << std::endl; std::cout << "# weight_file : " << weight_file << std::endl; std::cout << "# variable_file : " << variable_file << std::endl; std::cout << "# factor_file : " << factor_file << std::endl; std::cout << "# meta_file : " << meta_file << std::endl; std::cout << "# output_folder : " << output_folder << std::endl; std::cout << "# n_learning_epoch : " << n_learning_epoch << std::endl; std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl; std::cout << "# n_inference_epoch : " << n_inference_epoch << std::endl; std::cout << "# stepsize : " << stepsize << std::endl; std::cout << "# decay : " << decay << std::endl; std::cout << "# regularization : " << reg_param << std::endl; std::cout << "# l1 regularization : " << reg1_param << std::endl; std::cout << "################################################" << std::endl; std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl; std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl; std::cout << "################################################" << std::endl; std::cout << "# nvar : " << meta.num_variables << std::endl; std::cout << "# nfac : " << meta.num_factors << std::endl; std::cout << "# nweight : " << meta.num_weights << std::endl; std::cout << "# nedge : " << meta.num_edges << std::endl; std::cout << "################################################" << std::endl; } // run on NUMA node 0 numa_run_on_node(0); numa_set_localalloc(); // load factor graph dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges); fg.load(cmd_parser, is_quiet); dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence); // Initialize EM instance dd::ExpMax expMax(&fg, &gibbs, wl_conv, delta, check_convergence); // number of inference epochs int numa_aware_n_epoch; int numa_aware_n_learning_epoch; // EM init -- run Maximzation (semi-supervised learning) // Maximization step numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); while (!expMax.hasConverged && n_iter > 0) { // Expectation step numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) + (n_inference_epoch%n_numa_node==0?0:1); expMax.expectation(numa_aware_n_epoch,is_quiet); // Maximization step numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); //Decrement iteration counter n_iter--; } expMax.dump_weights(is_quiet); expMax.aggregate_results_and_dump(is_quiet); } <commit_msg>open file and read lines<commit_after> #include "gibbs.h" #include "dstruct/factor_graph/inference_result.h" #include <iostream> #include <fstream> /* * Parse input arguments */ dd::CmdParser parse_input(int argc, char** argv){ std::vector<std::string> new_args; if (argc < 2) { new_args.push_back(std::string(argv[0]) + " " + "gibbs"); new_args.push_back("-h"); } else { new_args.push_back(std::string(argv[0]) + " " + std::string(argv[1])); for(int i=2;i<argc;i++){ new_args.push_back(std::string(argv[i])); } } char ** new_argv = new char*[new_args.size()]; for(size_t i=0;i<new_args.size();i++){ new_argv[i] = new char[new_args[i].length() + 1]; std::copy(new_args[i].begin(), new_args[i].end(), new_argv[i]); new_argv[i][new_args[i].length()] = '\0'; } std::string final_app_name; if (argc >= 2) final_app_name = argv[1]; else final_app_name = "gibbs"; dd::CmdParser cmd_parser(final_app_name); cmd_parser.parse(new_args.size(), new_argv); return cmd_parser; } void gibbs(dd::CmdParser & cmd_parser){ // number of NUMA nodes int n_numa_node = numa_max_node() + 1; // number of max threads per NUMA node int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node); // get command line arguments std::string fg_file = cmd_parser.fg_file->getValue(); std::string weight_file = cmd_parser.weight_file->getValue(); std::string variable_file = cmd_parser.variable_file->getValue(); std::string factor_file = cmd_parser.factor_file->getValue(); std::string edge_file = cmd_parser.edge_file->getValue(); std::string meta_file = cmd_parser.meta_file->getValue(); std::cout<<"Opening file "<<meta_file<<std::endl; std::ifstream myfile; std::string data; myfile.open (meta_file); while ( std::getline(myfile,data)) { std::cout << data <<std::endl; } myfile.close(); std::string output_folder = cmd_parser.output_folder->getValue(); int n_learning_epoch = cmd_parser.n_learning_epoch->getValue(); int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue(); int n_inference_epoch = cmd_parser.n_inference_epoch->getValue(); double stepsize = cmd_parser.stepsize->getValue(); double stepsize2 = cmd_parser.stepsize2->getValue(); // hack to support two parameters to specify step size if (stepsize == 0.01) stepsize = stepsize2; double decay = cmd_parser.decay->getValue(); int n_datacopy = cmd_parser.n_datacopy->getValue(); double reg_param = cmd_parser.reg_param->getValue(); double reg1_param = cmd_parser.reg1_param->getValue(); bool is_quiet = cmd_parser.quiet->getValue(); bool sample_evidence = cmd_parser.sample_evidence->getValue(); int burn_in = cmd_parser.burn_in->getValue(); bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue(); Meta meta = read_meta(fg_file); if (is_quiet) { std::cout << "Running in quiet mode..." << std::endl; } else { std::cout << std::endl; std::cout << "#################MACHINE CONFIG#################" << std::endl; std::cout << "# # NUMA Node : " << n_numa_node << std::endl; std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl; std::cout << "################################################" << std::endl; std::cout << std::endl; std::cout << "#################GIBBS SAMPLING#################" << std::endl; std::cout << "# fg_file : " << fg_file << std::endl; std::cout << "# edge_file : " << edge_file << std::endl; std::cout << "# weight_file : " << weight_file << std::endl; std::cout << "# variable_file : " << variable_file << std::endl; std::cout << "# factor_file : " << factor_file << std::endl; std::cout << "# meta_file : " << meta_file << std::endl; std::cout << "# output_folder : " << output_folder << std::endl; std::cout << "# n_learning_epoch : " << n_learning_epoch << std::endl; std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl; std::cout << "# n_inference_epoch : " << n_inference_epoch << std::endl; std::cout << "# stepsize : " << stepsize << std::endl; std::cout << "# decay : " << decay << std::endl; std::cout << "# regularization : " << reg_param << std::endl; std::cout << "# l1 regularization : " << reg1_param << std::endl; std::cout << "################################################" << std::endl; std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl; std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl; std::cout << "################################################" << std::endl; std::cout << "# nvar : " << meta.num_variables << std::endl; std::cout << "# nfac : " << meta.num_factors << std::endl; std::cout << "# nweight : " << meta.num_weights << std::endl; std::cout << "# nedge : " << meta.num_edges << std::endl; std::cout << "################################################" << std::endl; } // run on NUMA node 0 numa_run_on_node(0); numa_set_localalloc(); // load factor graph dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges); fg.load(cmd_parser, is_quiet); dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence); // number of learning epochs // the factor graph is copied on each NUMA node, so the total epochs = // epochs specified / number of NUMA nodes int numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); // learning gibbs.learn(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); // dump weights gibbs.dump_weights(is_quiet); // number of inference epochs int numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) + (n_inference_epoch%n_numa_node==0?0:1); // inference gibbs.inference(numa_aware_n_epoch, is_quiet); gibbs.aggregate_results_and_dump(is_quiet); // print weights from inference result for(long t=0;t<fg.n_weight;t++) { std::cout<<fg.infrs->weight_values[t]<<std::endl; } // print weights from factor graph std::cout<<"PRINTING WEIGHTS FROM WEIGHT VARIABLE"<<std::endl; for(long t=0;t<fg.n_weight;t++) { std::cout<<fg.weights[t].weight<<std::endl; } } void em(dd::CmdParser & cmd_parser){ // number of NUMA nodes int n_numa_node = numa_max_node() + 1; // number of max threads per NUMA node int n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_node); // get command line arguments std::string fg_file = cmd_parser.fg_file->getValue(); std::string weight_file = cmd_parser.weight_file->getValue(); std::string variable_file = cmd_parser.variable_file->getValue(); std::string factor_file = cmd_parser.factor_file->getValue(); std::string edge_file = cmd_parser.edge_file->getValue(); std::string meta_file = cmd_parser.meta_file->getValue(); std::string output_folder = cmd_parser.output_folder->getValue(); int n_learning_epoch = cmd_parser.n_learning_epoch->getValue(); int n_samples_per_learning_epoch = cmd_parser.n_samples_per_learning_epoch->getValue(); int n_inference_epoch = cmd_parser.n_inference_epoch->getValue(); double stepsize = cmd_parser.stepsize->getValue(); double stepsize2 = cmd_parser.stepsize2->getValue(); // hack to support two parameters to specify step size if (stepsize == 0.01) stepsize = stepsize2; double decay = cmd_parser.decay->getValue(); int n_datacopy = cmd_parser.n_datacopy->getValue(); double reg_param = cmd_parser.reg_param->getValue(); double reg1_param = cmd_parser.reg1_param->getValue(); bool is_quiet = cmd_parser.quiet->getValue(); bool check_convergence = cmd_parser.check_convergence->getValue(); bool sample_evidence = cmd_parser.sample_evidence->getValue(); int burn_in = cmd_parser.burn_in->getValue(); int n_iter = cmd_parser.n_iter->getValue(); int wl_conv = cmd_parser.wl_conv->getValue(); int delta = cmd_parser.delta->getValue(); bool learn_non_evidence = cmd_parser.learn_non_evidence->getValue(); Meta meta = read_meta(fg_file); if (is_quiet) { std::cout << "Running in quiet mode..." << std::endl; } else { std::cout << std::endl; std::cout << "#################MACHINE CONFIG#################" << std::endl; std::cout << "# # NUMA Node : " << n_numa_node << std::endl; std::cout << "# # Thread/NUMA Node : " << n_thread_per_numa << std::endl; std::cout << "################################################" << std::endl; std::cout << std::endl; std::cout << "#################GIBBS SAMPLING#################" << std::endl; std::cout << "# fg_file : " << fg_file << std::endl; std::cout << "# edge_file : " << edge_file << std::endl; std::cout << "# weight_file : " << weight_file << std::endl; std::cout << "# variable_file : " << variable_file << std::endl; std::cout << "# factor_file : " << factor_file << std::endl; std::cout << "# meta_file : " << meta_file << std::endl; std::cout << "# output_folder : " << output_folder << std::endl; std::cout << "# n_learning_epoch : " << n_learning_epoch << std::endl; std::cout << "# n_samples/l. epoch : " << n_samples_per_learning_epoch << std::endl; std::cout << "# n_inference_epoch : " << n_inference_epoch << std::endl; std::cout << "# stepsize : " << stepsize << std::endl; std::cout << "# decay : " << decay << std::endl; std::cout << "# regularization : " << reg_param << std::endl; std::cout << "# l1 regularization : " << reg1_param << std::endl; std::cout << "################################################" << std::endl; std::cout << "# IGNORE -s (n_samples/l. epoch). ALWAYS -s 1. #" << std::endl; std::cout << "# IGNORE -t (threads). ALWAYS USE ALL THREADS. #" << std::endl; std::cout << "################################################" << std::endl; std::cout << "# nvar : " << meta.num_variables << std::endl; std::cout << "# nfac : " << meta.num_factors << std::endl; std::cout << "# nweight : " << meta.num_weights << std::endl; std::cout << "# nedge : " << meta.num_edges << std::endl; std::cout << "################################################" << std::endl; } // run on NUMA node 0 numa_run_on_node(0); numa_set_localalloc(); // load factor graph dd::FactorGraph fg(meta.num_variables, meta.num_factors, meta.num_weights, meta.num_edges); fg.load(cmd_parser, is_quiet); dd::GibbsSampling gibbs(&fg, &cmd_parser, n_datacopy, sample_evidence, burn_in, learn_non_evidence); // Initialize EM instance dd::ExpMax expMax(&fg, &gibbs, wl_conv, delta, check_convergence); // number of inference epochs int numa_aware_n_epoch; int numa_aware_n_learning_epoch; // EM init -- run Maximzation (semi-supervised learning) // Maximization step numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); while (!expMax.hasConverged && n_iter > 0) { // Expectation step numa_aware_n_epoch = (int)(n_inference_epoch/n_numa_node) + (n_inference_epoch%n_numa_node==0?0:1); expMax.expectation(numa_aware_n_epoch,is_quiet); // Maximization step numa_aware_n_learning_epoch = (int)(n_learning_epoch/n_numa_node) + (n_learning_epoch%n_numa_node==0?0:1); expMax.maximization(numa_aware_n_learning_epoch, n_samples_per_learning_epoch, stepsize, decay, reg_param, reg1_param, is_quiet); //Decrement iteration counter n_iter--; } expMax.dump_weights(is_quiet); expMax.aggregate_results_and_dump(is_quiet); } <|endoftext|>
<commit_before>// Copyright (C) 2018 David Helkowski // License GNU AGPLv3 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<libgen.h> // Text to print before every hexidecimal byte representation #define HEX_PREFIX '~' // Characters to show normally instead of in hex #define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?" // Comment this out to disable acceptance of alpha-numeric characters #define ALPHA_NUM // Minimum number of sequential acceptable character needed to show text instead of hex #define MIN_SEQUENCE 3 unsigned char let_okay( unsigned char let ); unsigned char accept[ 256 ]; int main( int argc, char *argv[] ) { FILE *data_handle = 0; bool showhelp = 0; if( argc < 2 ) { if( isatty( STDIN_FILENO ) ) { showhelp = 1; } else { fprintf(stderr, "Reading input from redirection\n" ); data_handle = stdin; } } if( argc > 1 ) { if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1; fprintf(stderr, "Using file '%s' for input\n", argv[1] ); data_handle = fopen( argv[1], "r" ); if( !data_handle ) { fprintf(stderr, "File does not exist\n" ); return 1; } } if( showhelp ) { char *base = basename( argv[0] ); printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n"); printf("Characters configured to be output normally:\n"); #ifdef ALPHA_NUM printf(" Alphanumerics\n" ); #endif printf(" %s\n\n", OK_CHARACTERS ); printf("Usage:\n %s [filename]\n %s < filename\n", base, base ); return 0; } if( !data_handle ) { return 1; } #define STACK_SIZE MIN_SEQUENCE + 1 unsigned char stack[ STACK_SIZE ]; memset( stack, 0, STACK_SIZE ); // accept is a global memset( accept, 0, 256 ); unsigned char accept_these[] = OK_CHARACTERS; for( int i=0; i < sizeof( accept_these); i++ ) { unsigned char let = accept_these[ i ]; accept[ let ] = 1; } unsigned char ok_cnt = 0; int stack_fill = 0; // how much of the stack is filled bool stack_full = 0; while( 1 ) { unsigned char let = fgetc( data_handle ); if( feof( data_handle ) ) break; if( !stack_full ) { stack_fill++; if( stack_fill == MIN_SEQUENCE ) { stack_full = 1; } } // shift out the lowest char unsigned char n_ago = stack[ 0 ]; for( int i=0;i<(MIN_SEQUENCE-1);i++ ) { stack[ i ] = stack[ i + 1 ]; } // push the new character onto the stack and pop the last one stack[ MIN_SEQUENCE - 1 ] = let; unsigned char num_ok = 0; if( let_okay( n_ago ) ) { num_ok++; for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) { if( let_okay( stack[ i ] ) ) num_ok++; else i=100; } } else { ok_cnt = 0; } if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) { putchar( n_ago ); ok_cnt++; } else { printf( "%c%02X", HEX_PREFIX, n_ago ); ok_cnt = 0; } } for( int i=0;i<stack_fill;i++ ) { putchar( stack[ i ] ); } fclose( data_handle ); } unsigned char let_okay( unsigned char let ) { unsigned char ok = 0; if( accept[ let ] ) ok = 1; #ifdef ALPHA_NUM if( let >= 'a' && let <= 'z' ) ok = 1; if( let >= 'A' && let <= 'Z' ) ok = 1; if( let >= '0' && let <= '9' ) ok = 1; #endif return ok; }<commit_msg>Inline character check function / always use charmap.<commit_after>// Copyright (C) 2018 David Helkowski // License GNU AGPLv3 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<libgen.h> // Text to print before every hexidecimal byte representation #define HEX_PREFIX '~' // Characters to show normally instead of in hex #define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?" // Comment this out to disable acceptance of alpha-numeric characters #define ALPHA_NUM #ifdef ALPHA_NUM #define OK_CHARS OK_CHARACTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" #else #define OK_CHARS #endif // Minimum number of sequential acceptable character needed to show text instead of hex #define MIN_SEQUENCE 3 int main( int argc, char *argv[] ) { FILE *data_handle = 0; bool showhelp = 0; if( argc < 2 ) { if( isatty( STDIN_FILENO ) ) { showhelp = 1; } else { fprintf(stderr, "Reading input from redirection\n" ); data_handle = stdin; } } if( argc > 1 ) { if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1; fprintf(stderr, "Using file '%s' for input\n", argv[1] ); data_handle = fopen( argv[1], "r" ); if( !data_handle ) { fprintf(stderr, "File does not exist\n" ); return 1; } } if( showhelp ) { char *base = basename( argv[0] ); printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n"); printf("Characters configured to be output normally:\n"); #ifdef ALPHA_NUM printf(" Alphanumerics\n" ); #endif printf(" %s\n\n", OK_CHARACTERS ); printf("Usage:\n %s [filename]\n %s < filename\n", base, base ); return 0; } if( !data_handle ) { return 1; } #define STACK_SIZE MIN_SEQUENCE + 1 unsigned char stack[ STACK_SIZE ]; memset( stack, 0, STACK_SIZE ); // Build accept charmap unsigned char accept[ 256 ]; memset( accept, 0, 256 ); unsigned char accept_these[] = OK_CHARS; for( int i=0; i < sizeof( accept_these ); i++ ) { unsigned char let = accept_these[ i ]; accept[ let ] = 1; } unsigned char ok_cnt = 0; int stack_fill = 0; // how much of the stack is filled bool stack_full = 0; while( 1 ) { unsigned char let = fgetc( data_handle ); if( feof( data_handle ) ) break; if( !stack_full ) { stack_fill++; if( stack_fill == MIN_SEQUENCE ) { stack_full = 1; } } // shift out the lowest char unsigned char n_ago = stack[ 0 ]; for( int i=0;i<(MIN_SEQUENCE-1);i++ ) { stack[ i ] = stack[ i + 1 ]; } // push the new character onto the stack and pop the last one stack[ MIN_SEQUENCE - 1 ] = let; unsigned char num_ok = 0; if( accept[ n_ago ] ) { num_ok++; for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) { if( accept[ stack[ i ] ] ) num_ok++; else i=100; } } else { ok_cnt = 0; } if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) { putchar( n_ago ); ok_cnt++; } else { printf( "%c%02X", HEX_PREFIX, n_ago ); ok_cnt = 0; } } for( int i=0;i<stack_fill;i++ ) { putchar( stack[ i ] ); } fclose( data_handle ); }<|endoftext|>
<commit_before>#include "ofApp.h" using namespace kaleidome; //-------------------------------------------------------------- void ofApp::setup() { // load settings parseSettings(); ofSetWindowShape(setting.windowWidth, setting.windowHeight); ofBackground(255); ofSetColor(255); dome = new Kaleidome(1.0f, setting.subdivide); dome->setPosition(ofVec3f(0, 0, 0)); dome->setScale(10); dome->setOrientation(ofVec3f(180.0f, 0.0f, 0.0f)); /// texture settings if (setting.isCam) { // camera ofSetLogLevel(OF_LOG_VERBOSE); grabber.setVerbose(true); grabber.listDevices(); grabber.initGrabber(setting.cameraWidth, setting.cameraHeight); } else { // image file texture.loadImage(setting.filepath); } /// domemaster.setup(); domemaster.setMeshScale(1); domemaster.resize(setting.renderWidth, setting.renderHeight); domemaster.setCameraPosition(0, 0, 5.77); // inner rendering frame fbo.allocate(setting.renderWidth, setting.renderHeight); } //-------------------------------------------------------------- void ofApp::update() { if (setting.isCam) grabber.update(); } //-------------------------------------------------------------- void ofApp::draw() { for (int i = 0; i < domemaster.renderCount; i++) { domemaster.begin(i); drawScene(); domemaster.end(i); } fbo.begin(false); ofClear(0); domemaster.draw(); fbo.end(); fbo.draw(0, 0, ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void ofApp::drawScene() { ofEnableNormalizedTexCoords(); if (setting.isCam) texture.setFromPixels(grabber.getPixels()); texture.bind(); dome->draw(); texture.unbind(); ofDisableNormalizedTexCoords(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if (key == 's') { ofImage img; img.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); char fileNameStr[255]; string date = ofGetTimestampString(); sprintf(fileNameStr, "S-%s.png", date.c_str()); img.save(fileNameStr, OF_IMAGE_QUALITY_BEST); std::cout << "XN[ۑ܂ " << fileNameStr << std::endl; } if (key == 'f') { ofImage img; ofPixels pixels; fbo.readToPixels(pixels); img.setFromPixels(pixels); char fileNameStr[255]; string date = ofGetTimestampString(); sprintf(fileNameStr, "F-%s.png", date.c_str()); img.save(fileNameStr, OF_IMAGE_QUALITY_BEST); std::cout << "t[ۑ܂" << fileNameStr << std::endl; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { } //-------------------------------------------------------------- void ofApp::exit() { delete dome; } //-------------------------------------------------------------- bool ofApp::parseSettings() { bool success = json.open("sample.json"); if (success) { std::cout << "Succeed to parse JSON" << std::endl; // windows size setting.windowWidth = json["windowSize"][0].asInt(); setting.windowWidth = json["windowSize"][1].asInt(); // inner render size setting.renderWidth = json["renderSize"][0].asInt(); setting.renderHeight = json["renderSize"][1].asInt(); //input setting.isCam = json["enableCamera"].asBool(); setting.camDeviceId = json["cameraDeviceId"].asInt(); setting.cameraWidth = json["cameraResolution"][0].asInt(); setting.cameraHeight = json["cameraResolution"][1].asInt(); setting.filepath = json["filePath"].asString(); // dome setting setting.subdivide = json["subdivide"].asUInt(); } else { std::cout << "Failed to parse JSON" << std::endl; } return success; }<commit_msg>デバイスID対応修正<commit_after>#include "ofApp.h" using namespace kaleidome; //-------------------------------------------------------------- void ofApp::setup() { // load settings parseSettings(); ofSetWindowShape(setting.windowWidth, setting.windowHeight); ofBackground(255); ofSetColor(255); dome = new Kaleidome(1.0f, setting.subdivide); dome->setPosition(ofVec3f(0, 0, 0)); dome->setScale(10); dome->setOrientation(ofVec3f(180.0f, 0.0f, 0.0f)); /// texture settings if (setting.isCam) { // camera ofSetLogLevel(OF_LOG_VERBOSE); grabber.setVerbose(true); grabber.listDevices(); grabber.setDeviceID(setting.camDeviceId); grabber.initGrabber(setting.cameraWidth, setting.cameraHeight); } else { // image file texture.loadImage(setting.filepath); } /// domemaster.setup(); domemaster.setMeshScale(1); domemaster.resize(setting.renderWidth, setting.renderHeight); domemaster.setCameraPosition(0, 0, 5.77); // inner rendering frame fbo.allocate(setting.renderWidth, setting.renderHeight); } //-------------------------------------------------------------- void ofApp::update() { if (setting.isCam) grabber.update(); } //-------------------------------------------------------------- void ofApp::draw() { for (int i = 0; i < domemaster.renderCount; i++) { domemaster.begin(i); drawScene(); domemaster.end(i); } fbo.begin(false); ofClear(0); domemaster.draw(); fbo.end(); fbo.draw(0, 0, ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void ofApp::drawScene() { ofEnableNormalizedTexCoords(); if (setting.isCam) texture.setFromPixels(grabber.getPixels()); texture.bind(); dome->draw(); texture.unbind(); ofDisableNormalizedTexCoords(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if (key == 's') { ofImage img; img.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); char fileNameStr[255]; string date = ofGetTimestampString(); sprintf(fileNameStr, "S-%s.png", date.c_str()); img.save(fileNameStr, OF_IMAGE_QUALITY_BEST); std::cout << "XN[ۑ܂ " << fileNameStr << std::endl; } if (key == 'f') { ofImage img; ofPixels pixels; fbo.readToPixels(pixels); img.setFromPixels(pixels); char fileNameStr[255]; string date = ofGetTimestampString(); sprintf(fileNameStr, "F-%s.png", date.c_str()); img.save(fileNameStr, OF_IMAGE_QUALITY_BEST); std::cout << "t[ۑ܂" << fileNameStr << std::endl; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { } //-------------------------------------------------------------- void ofApp::exit() { delete dome; } //-------------------------------------------------------------- bool ofApp::parseSettings() { bool success = json.open("sample.json"); if (success) { std::cout << "Succeed to parse JSON" << std::endl; // windows size setting.windowWidth = json["windowSize"][0].asInt(); setting.windowWidth = json["windowSize"][1].asInt(); // inner render size setting.renderWidth = json["renderSize"][0].asInt(); setting.renderHeight = json["renderSize"][1].asInt(); //input setting.isCam = json["enableCamera"].asBool(); setting.camDeviceId = json["cameraDeviceId"].asInt(); setting.cameraWidth = json["cameraResolution"][0].asInt(); setting.cameraHeight = json["cameraResolution"][1].asInt(); setting.filepath = json["filePath"].asString(); // dome setting setting.subdivide = json["subdivide"].asUInt(); } else { std::cout << "Failed to parse JSON" << std::endl; } return success; }<|endoftext|>
<commit_before>#include "./parser.h" #include <string> #include <vector> #include <v8.h> #include <nan.h> #include "./conversions.h" #include "./input_reader.h" #include "./logger.h" #include "./tree.h" #include "./util.h" #include "text-buffer-snapshot-wrapper.h" namespace node_tree_sitter { using namespace v8; using std::vector; using std::pair; Nan::Persistent<Function> Parser::constructor; void Parser::Init(Local<Object> exports) { Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<String> class_name = Nan::New("Parser").ToLocalChecked(); tpl->SetClassName(class_name); FunctionPair methods[] = { {"getLogger", GetLogger}, {"setLogger", SetLogger}, {"setLanguage", SetLanguage}, {"printDotGraphs", PrintDotGraphs}, {"parse", Parse}, {"parseTextBuffer", ParseTextBuffer}, }; for (size_t i = 0; i < length_of_array(methods); i++) { Nan::SetPrototypeMethod(tpl, methods[i].name, methods[i].callback); } constructor.Reset(Nan::Persistent<Function>(tpl->GetFunction())); exports->Set(class_name, Nan::New(constructor)); exports->Set(Nan::New("LANGUAGE_VERSION").ToLocalChecked(), Nan::New<Number>(TREE_SITTER_LANGUAGE_VERSION)); } Parser::Parser() : parser_(ts_parser_new()), is_parsing_async_(false) {} Parser::~Parser() { ts_parser_delete(parser_); } void Parser::New(const Nan::FunctionCallbackInfo<Value> &info) { if (info.IsConstructCall()) { Parser *parser = new Parser(); parser->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { Local<Object> self; MaybeLocal<Object> maybe_self = Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()); if (maybe_self.ToLocal(&self)) { info.GetReturnValue().Set(self); } else { info.GetReturnValue().Set(Nan::Null()); } } } void Parser::SetLanguage(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("Invalid language object"); return; } Local<Object> arg = Local<Object>::Cast(info[0]); if (arg->InternalFieldCount() != 1) { Nan::ThrowTypeError("Invalid language object"); return; } TSLanguage *language = (TSLanguage *)Nan::GetInternalFieldPointer(arg, 0); if (!language) { Nan::ThrowTypeError("Invalid language object"); return; } if (ts_language_version(language) != TREE_SITTER_LANGUAGE_VERSION) { std::string message = "Incompatible language version. Expected " + std::to_string(TREE_SITTER_LANGUAGE_VERSION) + ". Got " + std::to_string(ts_language_version(language)); Nan::ThrowError(Nan::RangeError(message.c_str())); return; } ts_parser_set_language(parser->parser_, language); info.GetReturnValue().Set(info.This()); } void Parser::Parse(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("Input must be an object"); return; } Local<Object> input = Local<Object>::Cast(info[0]); if (!input->Get(Nan::New("seek").ToLocalChecked())->IsFunction()) { Nan::ThrowTypeError("Input must implement seek(n)"); return; } if (!input->Get(Nan::New("read").ToLocalChecked())->IsFunction()) { Nan::ThrowTypeError("Input must implement read(n)"); return; } const TSTree *old_tree = nullptr; if (info.Length() > 1 && info[1]->BooleanValue()) { const TSTree *tree = Tree::UnwrapTree(info[1]); if (!tree) { Nan::ThrowTypeError("Second argument must be a tree"); return; } old_tree = tree; } InputReader input_reader(input); TSTree *tree = ts_parser_parse(parser->parser_, old_tree, input_reader.Input()); Local<Value> result = Tree::NewInstance(tree); info.GetReturnValue().Set(result); } class ParseWorker : public Nan::AsyncWorker { Parser *parser_; const vector<pair<const char16_t *, uint32_t>> *slices_; TSTree *old_tree_; TSTree *result_; uint32_t slice_index_; uint32_t slice_offset_; static int Seek(void *payload, uint32_t byte, TSPoint position) { ParseWorker *worker = static_cast<ParseWorker *>(payload); uint32_t total_length = 0; uint32_t goal_index = byte / 2; for (unsigned i = 0, n = worker->slices_->size(); i < n; i++) { uint32_t next_total_length = total_length + worker->slices_->at(i).second; if (next_total_length > goal_index) { worker->slice_index_ = i; worker->slice_offset_ = goal_index - total_length; return true; } total_length = next_total_length; } worker->slice_index_ = worker->slices_->size(); worker->slice_offset_ = 0; return true; } static const char *Read(void *payload, uint32_t *length) { ParseWorker *worker = static_cast<ParseWorker *>(payload); if (worker->slice_index_ == worker->slices_->size()) { *length = 0; return ""; } auto &slice = worker->slices_->at(worker->slice_index_); const char16_t *result = slice.first + worker->slice_offset_; *length = 2 * (slice.second - worker->slice_offset_); worker->slice_index_++; worker->slice_offset_ = 0; return reinterpret_cast<const char *>(result); } public: ParseWorker(Nan::Callback *callback, Parser *parser, const vector<pair<const char16_t *, uint32_t>> *slices, TSTree *old_tree) : AsyncWorker(callback), parser_(parser), slices_(slices), old_tree_(old_tree), result_(nullptr) {} void Execute() { TSInput input = { this, Read, Seek, TSInputEncodingUTF16, }; result_ = ts_parser_parse(parser_->parser_, old_tree_, input); } void HandleOKCallback() { parser_->is_parsing_async_ = false; if (old_tree_) ts_tree_delete(old_tree_); Local<Value> argv[] = {Tree::NewInstance(result_)}; callback->Call(1, argv); } }; void Parser::ParseTextBuffer(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } auto callback = new Nan::Callback(info[0].As<Function>()); auto snapshot = Nan::ObjectWrap::Unwrap<TextBufferSnapshotWrapper>(info[1].As<Object>()); parser->is_parsing_async_ = true; TSTree *old_tree = nullptr; if (info.Length() > 2 && info[2]->BooleanValue()) { const TSTree *tree = Tree::UnwrapTree(info[2]); if (!tree) { Nan::ThrowTypeError("Second argument must be a tree"); return; } old_tree = ts_tree_copy(tree); } Nan::AsyncQueueWorker(new ParseWorker( callback, parser, snapshot->slices(), old_tree )); } void Parser::GetLogger(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); TSLogger current_logger = ts_parser_logger(parser->parser_); if (current_logger.payload && current_logger.log == Logger::Log) { Logger *logger = (Logger *)current_logger.payload; info.GetReturnValue().Set(Nan::New(logger->func)); } else { info.GetReturnValue().Set(Nan::Null()); } } void Parser::SetLogger(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } TSLogger current_logger = ts_parser_logger(parser->parser_); if (info[0]->IsFunction()) { if (current_logger.payload) delete (Logger *)current_logger.payload; ts_parser_set_logger(parser->parser_, Logger::Make(Local<Function>::Cast(info[0]))); } else if (!info[0]->BooleanValue()) { if (current_logger.payload) delete (Logger *)current_logger.payload; ts_parser_set_logger(parser->parser_, { 0, 0 }); } else { Nan::ThrowTypeError("Logger callback must either be a function or a falsy value"); return; } info.GetReturnValue().Set(info.This()); } void Parser::PrintDotGraphs(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } Local<Boolean> value = Local<Boolean>::Cast(info[0]); if (value->IsBoolean() && value->BooleanValue()) { ts_parser_print_dot_graphs(parser->parser_, stderr); } else { ts_parser_print_dot_graphs(parser->parser_, nullptr); } info.GetReturnValue().Set(info.This()); } } // namespace node_tree_sitter <commit_msg>Avoid calling JS logger functions during async parsing<commit_after>#include "./parser.h" #include <string> #include <vector> #include <v8.h> #include <nan.h> #include "./conversions.h" #include "./input_reader.h" #include "./logger.h" #include "./tree.h" #include "./util.h" #include "text-buffer-snapshot-wrapper.h" namespace node_tree_sitter { using namespace v8; using std::vector; using std::pair; Nan::Persistent<Function> Parser::constructor; void Parser::Init(Local<Object> exports) { Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<String> class_name = Nan::New("Parser").ToLocalChecked(); tpl->SetClassName(class_name); FunctionPair methods[] = { {"getLogger", GetLogger}, {"setLogger", SetLogger}, {"setLanguage", SetLanguage}, {"printDotGraphs", PrintDotGraphs}, {"parse", Parse}, {"parseTextBuffer", ParseTextBuffer}, }; for (size_t i = 0; i < length_of_array(methods); i++) { Nan::SetPrototypeMethod(tpl, methods[i].name, methods[i].callback); } constructor.Reset(Nan::Persistent<Function>(tpl->GetFunction())); exports->Set(class_name, Nan::New(constructor)); exports->Set(Nan::New("LANGUAGE_VERSION").ToLocalChecked(), Nan::New<Number>(TREE_SITTER_LANGUAGE_VERSION)); } Parser::Parser() : parser_(ts_parser_new()), is_parsing_async_(false) {} Parser::~Parser() { ts_parser_delete(parser_); } void Parser::New(const Nan::FunctionCallbackInfo<Value> &info) { if (info.IsConstructCall()) { Parser *parser = new Parser(); parser->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { Local<Object> self; MaybeLocal<Object> maybe_self = Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()); if (maybe_self.ToLocal(&self)) { info.GetReturnValue().Set(self); } else { info.GetReturnValue().Set(Nan::Null()); } } } void Parser::SetLanguage(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("Invalid language object"); return; } Local<Object> arg = Local<Object>::Cast(info[0]); if (arg->InternalFieldCount() != 1) { Nan::ThrowTypeError("Invalid language object"); return; } TSLanguage *language = (TSLanguage *)Nan::GetInternalFieldPointer(arg, 0); if (!language) { Nan::ThrowTypeError("Invalid language object"); return; } if (ts_language_version(language) != TREE_SITTER_LANGUAGE_VERSION) { std::string message = "Incompatible language version. Expected " + std::to_string(TREE_SITTER_LANGUAGE_VERSION) + ". Got " + std::to_string(ts_language_version(language)); Nan::ThrowError(Nan::RangeError(message.c_str())); return; } ts_parser_set_language(parser->parser_, language); info.GetReturnValue().Set(info.This()); } void Parser::Parse(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("Input must be an object"); return; } Local<Object> input = Local<Object>::Cast(info[0]); if (!input->Get(Nan::New("seek").ToLocalChecked())->IsFunction()) { Nan::ThrowTypeError("Input must implement seek(n)"); return; } if (!input->Get(Nan::New("read").ToLocalChecked())->IsFunction()) { Nan::ThrowTypeError("Input must implement read(n)"); return; } const TSTree *old_tree = nullptr; if (info.Length() > 1 && info[1]->BooleanValue()) { const TSTree *tree = Tree::UnwrapTree(info[1]); if (!tree) { Nan::ThrowTypeError("Second argument must be a tree"); return; } old_tree = tree; } InputReader input_reader(input); TSTree *tree = ts_parser_parse(parser->parser_, old_tree, input_reader.Input()); Local<Value> result = Tree::NewInstance(tree); info.GetReturnValue().Set(result); } class ParseWorker : public Nan::AsyncWorker { Parser *parser_; const vector<pair<const char16_t *, uint32_t>> *slices_; TSTree *old_tree_; TSTree *result_; uint32_t slice_index_; uint32_t slice_offset_; static int Seek(void *payload, uint32_t byte, TSPoint position) { ParseWorker *worker = static_cast<ParseWorker *>(payload); uint32_t total_length = 0; uint32_t goal_index = byte / 2; for (unsigned i = 0, n = worker->slices_->size(); i < n; i++) { uint32_t next_total_length = total_length + worker->slices_->at(i).second; if (next_total_length > goal_index) { worker->slice_index_ = i; worker->slice_offset_ = goal_index - total_length; return true; } total_length = next_total_length; } worker->slice_index_ = worker->slices_->size(); worker->slice_offset_ = 0; return true; } static const char *Read(void *payload, uint32_t *length) { ParseWorker *worker = static_cast<ParseWorker *>(payload); if (worker->slice_index_ == worker->slices_->size()) { *length = 0; return ""; } auto &slice = worker->slices_->at(worker->slice_index_); const char16_t *result = slice.first + worker->slice_offset_; *length = 2 * (slice.second - worker->slice_offset_); worker->slice_index_++; worker->slice_offset_ = 0; return reinterpret_cast<const char *>(result); } public: ParseWorker(Nan::Callback *callback, Parser *parser, const vector<pair<const char16_t *, uint32_t>> *slices, TSTree *old_tree) : AsyncWorker(callback), parser_(parser), slices_(slices), old_tree_(old_tree), result_(nullptr) {} void Execute() { TSInput input = { this, Read, Seek, TSInputEncodingUTF16, }; TSLogger logger = ts_parser_logger(parser_->parser_); ts_parser_set_logger(parser_->parser_, TSLogger{0, 0}); result_ = ts_parser_parse(parser_->parser_, old_tree_, input); ts_parser_set_logger(parser_->parser_, logger); } void HandleOKCallback() { parser_->is_parsing_async_ = false; if (old_tree_) ts_tree_delete(old_tree_); Local<Value> argv[] = {Tree::NewInstance(result_)}; callback->Call(1, argv); } }; void Parser::ParseTextBuffer(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } auto callback = new Nan::Callback(info[0].As<Function>()); auto snapshot = Nan::ObjectWrap::Unwrap<TextBufferSnapshotWrapper>(info[1].As<Object>()); parser->is_parsing_async_ = true; TSTree *old_tree = nullptr; if (info.Length() > 2 && info[2]->BooleanValue()) { const TSTree *tree = Tree::UnwrapTree(info[2]); if (!tree) { Nan::ThrowTypeError("Second argument must be a tree"); return; } old_tree = ts_tree_copy(tree); } Nan::AsyncQueueWorker(new ParseWorker( callback, parser, snapshot->slices(), old_tree )); } void Parser::GetLogger(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); TSLogger current_logger = ts_parser_logger(parser->parser_); if (current_logger.payload && current_logger.log == Logger::Log) { Logger *logger = (Logger *)current_logger.payload; info.GetReturnValue().Set(Nan::New(logger->func)); } else { info.GetReturnValue().Set(Nan::Null()); } } void Parser::SetLogger(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } TSLogger current_logger = ts_parser_logger(parser->parser_); if (info[0]->IsFunction()) { if (current_logger.payload) delete (Logger *)current_logger.payload; ts_parser_set_logger(parser->parser_, Logger::Make(Local<Function>::Cast(info[0]))); } else if (!info[0]->BooleanValue()) { if (current_logger.payload) delete (Logger *)current_logger.payload; ts_parser_set_logger(parser->parser_, { 0, 0 }); } else { Nan::ThrowTypeError("Logger callback must either be a function or a falsy value"); return; } info.GetReturnValue().Set(info.This()); } void Parser::PrintDotGraphs(const Nan::FunctionCallbackInfo<Value> &info) { Parser *parser = ObjectWrap::Unwrap<Parser>(info.This()); if (parser->is_parsing_async_) { Nan::ThrowError("Parser is in use"); return; } Local<Boolean> value = Local<Boolean>::Cast(info[0]); if (value->IsBoolean() && value->BooleanValue()) { ts_parser_print_dot_graphs(parser->parser_, stderr); } else { ts_parser_print_dot_graphs(parser->parser_, nullptr); } info.GetReturnValue().Set(info.This()); } } // namespace node_tree_sitter <|endoftext|>
<commit_before>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <cmath> #include <vector> #include <limits> template <typename T> inline T number_of_bits(T) { return static_cast<T>(sizeof(T) * 8); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } inline int64_t isquare(int64_t x) { return x * x; } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root inline int32_t isqrt(int64_t x) { int32_t r = static_cast<int32_t>(std::sqrt(static_cast<double>(x))); // correct rounding error while (ipow<2>(r) > x) r--; while (ipow<2>(r + 1) <= x) r++; return r; } /// Integer nth root template <int N> inline int32_t iroot(int64_t x) { int32_t r = static_cast<int32_t>(std::pow(static_cast<double>(x), 1.0 / N)); // correct rounding error while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Initialize a vector with Möbius function values. /// This implementation is based on code by Rick Sladkey /// posted here: http://mathoverflow.net/a/99545 /// inline std::vector<int32_t> make_moebius(int64_t max) { std::vector<int32_t> mu(max + 1, 1); for (int32_t i = 2; i * i <= max; i++) { if (mu[i] == 1) { for (int32_t j = i; j <= max; j += i) mu[j] *= -i; for (int32_t j = i * i; j <= max; j += i * i) mu[j] = 0; } } for (int32_t i = 2; i <= max; i++) { if (mu[i] == i) mu[i] = 1; else if (mu[i] == -i) mu[i] = -1; else if (mu[i] < 0) mu[i] = 1; else if (mu[i] > 0) mu[i] = -1; } return mu; } /// Initialize a vector with the least prime /// factors of the integers <= max. /// inline std::vector<int32_t> make_least_prime_factor(int64_t max) { std::vector<int32_t> lpf(max + 1, 1); // phi(x / 1, c) contributes to the sum, thus // set lpf[1] = MAX in order to pass // if (lpf[1] > primes[c]) if (lpf.size() > 1) lpf[1] = std::numeric_limits<int32_t>::max(); for (int32_t i = 2; i * i <= max; i++) if (lpf[i] == 1) for (int32_t j = i * 2; j <= max; j += i) if (lpf[j] == 1) lpf[j] = i; for (int32_t i = 2; i <= max; i++) if (lpf[i] == 1) lpf[i] = i; return lpf; } #endif <commit_msg>Update pmath.hpp<commit_after>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <cmath> #include <vector> #include <limits> inline int64_t isquare(int64_t x) { return x * x; } template <typename T> inline T number_of_bits(T) { return static_cast<T>(sizeof(T) * 8); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = static_cast<T>(std::sqrt(static_cast<double>(x))); // correct rounding error while (ipow<2>(r) > x) r--; while (ipow<2>(r + 1) <= x) r++; return r; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = static_cast<T>(std::pow(static_cast<double>(x), 1.0 / N)); // correct rounding error while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Initialize a vector with Möbius function values. /// This implementation is based on code by Rick Sladkey /// posted here: http://mathoverflow.net/a/99545 /// inline std::vector<int32_t> make_moebius(int64_t max) { std::vector<int32_t> mu(max + 1, 1); for (int32_t i = 2; i * i <= max; i++) { if (mu[i] == 1) { for (int32_t j = i; j <= max; j += i) mu[j] *= -i; for (int32_t j = i * i; j <= max; j += i * i) mu[j] = 0; } } for (int32_t i = 2; i <= max; i++) { if (mu[i] == i) mu[i] = 1; else if (mu[i] == -i) mu[i] = -1; else if (mu[i] < 0) mu[i] = 1; else if (mu[i] > 0) mu[i] = -1; } return mu; } /// Initialize a vector with the least prime /// factors of the integers <= max. /// inline std::vector<int32_t> make_least_prime_factor(int64_t max) { std::vector<int32_t> lpf(max + 1, 1); // phi(x / 1, c) contributes to the sum, thus // set lpf[1] = MAX in order to pass // if (lpf[1] > primes[c]) if (lpf.size() > 1) lpf[1] = std::numeric_limits<int32_t>::max(); for (int32_t i = 2; i * i <= max; i++) if (lpf[i] == 1) for (int32_t j = i * 2; j <= max; j += i) if (lpf[j] == 1) lpf[j] = i; for (int32_t i = 2; i <= max; i++) if (lpf[i] == 1) lpf[i] = i; return lpf; } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2019 Nagisa Sekiguchi * * 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 <sys/wait.h> #include <climits> #include "redir.h" #include "vm.h" #include "logger.h" namespace ydsh { PipelineObject::~PipelineObject() { /** * due to prevent write blocking of child processes, force to restore stdin before call wait. * in some situation, raise SIGPIPE in child processes. */ bool restored = this->entry->restoreStdin(); auto waitOp = state.isRootShell() && state.isJobControl() ? Proc::BLOCK_UNTRACED : Proc::BLOCKING; this->entry->wait(waitOp); this->state.updatePipeStatus(this->entry->getProcSize(), this->entry->getProcs(), true); if(restored) { int ret = this->state.tryToBeForeground(); LOG(DUMP_EXEC, "tryToBeForeground: %d, %s", ret, strerror(errno)); } if(this->entry->available()) { // job is still running, attach to JobTable this->state.jobTable.attach(this->entry); } this->state.jobTable.updateStatus(); } static bool isPassingFD(const std::pair<RedirOP, DSValue> &pair) { return pair.first == RedirOP::NOP && pair.second.isObject() && isa<UnixFdObject>(pair.second.get()); } RedirObject::~RedirObject() { this->restoreFDs(); for(int fd : this->oldFds) { close(fd); } // set close-on-exec flag to fds for(auto &e : this->ops) { if(isPassingFD(e) && e.second.get()->getRefcount() > 1) { typeAs<UnixFdObject>(e.second).closeOnExec(true); } } } static int doIOHere(const StringRef &value) { pipe_t pipe[1]; initAllPipe(1, pipe); dup2(pipe[0][READ_PIPE], STDIN_FILENO); if(value.size() + 1 <= PIPE_BUF) { int errnum = 0; if(write(pipe[0][WRITE_PIPE], value.data(), sizeof(char) * value.size()) < 0) { errnum = errno; } if(errnum == 0 && write(pipe[0][WRITE_PIPE], "\n", 1) < 0) { errnum = errno; } closeAllPipe(1, pipe); return errnum; } else { pid_t pid = fork(); if(pid < 0) { return errno; } if(pid == 0) { // child pid = fork(); // double-fork (not wait IO-here process termination.) if(pid == 0) { // child close(pipe[0][READ_PIPE]); dup2(pipe[0][WRITE_PIPE], STDOUT_FILENO); if(write(STDOUT_FILENO, value.data(), value.size()) < 0) { exit(1); } if(write(STDOUT_FILENO, "\n", 1) < 0) { exit(1); } } exit(0); } closeAllPipe(1, pipe); waitpid(pid, nullptr, 0); return 0; } } /** * if failed, return non-zero value(errno) */ static int redirectToFile(const DSValue &fileName, const char *mode, int targetFD) { if(fileName.hasType(TYPE::String)) { FILE *fp = fopen(fileName.asCStr(), mode); if(fp == nullptr) { return errno; } int fd = fileno(fp); if(dup2(fd, targetFD) < 0) { int e = errno; fclose(fp); return e; } fclose(fp); } else { assert(fileName.hasType(TYPE::UnixFD)); int fd = typeAs<UnixFdObject>(fileName).getValue(); if(strchr(mode, 'a') != nullptr) { if(lseek(fd, 0, SEEK_END) == -1) { return errno; } } if(dup2(fd, targetFD) < 0) { return errno; } } return 0; } static int redirectImpl(const std::pair<RedirOP, DSValue> &pair) { switch(pair.first) { case RedirOP::IN_2_FILE: return redirectToFile(pair.second, "rb", STDIN_FILENO); case RedirOP::OUT_2_FILE: return redirectToFile(pair.second, "wb", STDOUT_FILENO); case RedirOP::OUT_2_FILE_APPEND: return redirectToFile(pair.second, "ab", STDOUT_FILENO); case RedirOP::ERR_2_FILE: return redirectToFile(pair.second, "wb", STDERR_FILENO); case RedirOP::ERR_2_FILE_APPEND: return redirectToFile(pair.second, "ab", STDERR_FILENO); case RedirOP::MERGE_ERR_2_OUT_2_FILE: { int r = redirectToFile(pair.second, "wb", STDOUT_FILENO); if(r != 0) { return r; } if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; } case RedirOP::MERGE_ERR_2_OUT_2_FILE_APPEND: { int r = redirectToFile(pair.second, "ab", STDOUT_FILENO); if(r != 0) { return r; } if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; } case RedirOP::MERGE_ERR_2_OUT: if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; case RedirOP::MERGE_OUT_2_ERR: if(dup2(STDERR_FILENO, STDOUT_FILENO) < 0) { return errno; } return 0; case RedirOP::HERE_STR: return doIOHere(pair.second.asStrRef()); case RedirOP::NOP: break; } return 0; // do nothing } void RedirObject::passFDToExtProc() { for(auto &e : this->ops) { if(isPassingFD(e)) { typeAs<UnixFdObject>(e.second).closeOnExec(false); } } } bool RedirObject::redirect(DSState &st) { this->backupFDs(); for(auto &pair : this->ops) { int r = redirectImpl(pair); if(this->backupFDset > 0 && r != 0) { std::string msg = REDIR_ERROR; if(pair.second) { if(pair.second.hasType(TYPE::String)) { auto ref = pair.second.asStrRef(); if(!ref.empty()) { msg += ": "; msg.append(ref.data(), ref.size()); } } else if(pair.second.hasType(TYPE::UnixFD)) { msg += ": "; msg += std::to_string(typeAs<UnixFdObject>(pair.second).getValue()); } } raiseSystemError(st, r, std::move(msg)); return false; } } return true; } } // namespace ydsh<commit_msg>replace fopen with open in internal redirection<commit_after>/* * Copyright (C) 2019 Nagisa Sekiguchi * * 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 <sys/wait.h> #include <climits> #include "redir.h" #include "vm.h" #include "logger.h" namespace ydsh { PipelineObject::~PipelineObject() { /** * due to prevent write blocking of child processes, force to restore stdin before call wait. * in some situation, raise SIGPIPE in child processes. */ bool restored = this->entry->restoreStdin(); auto waitOp = state.isRootShell() && state.isJobControl() ? Proc::BLOCK_UNTRACED : Proc::BLOCKING; this->entry->wait(waitOp); this->state.updatePipeStatus(this->entry->getProcSize(), this->entry->getProcs(), true); if(restored) { int ret = this->state.tryToBeForeground(); LOG(DUMP_EXEC, "tryToBeForeground: %d, %s", ret, strerror(errno)); } if(this->entry->available()) { // job is still running, attach to JobTable this->state.jobTable.attach(this->entry); } this->state.jobTable.updateStatus(); } static bool isPassingFD(const std::pair<RedirOP, DSValue> &pair) { return pair.first == RedirOP::NOP && pair.second.isObject() && isa<UnixFdObject>(pair.second.get()); } RedirObject::~RedirObject() { this->restoreFDs(); for(int fd : this->oldFds) { close(fd); } // set close-on-exec flag to fds for(auto &e : this->ops) { if(isPassingFD(e) && e.second.get()->getRefcount() > 1) { typeAs<UnixFdObject>(e.second).closeOnExec(true); } } } static int doIOHere(const StringRef &value) { pipe_t pipe[1]; initAllPipe(1, pipe); dup2(pipe[0][READ_PIPE], STDIN_FILENO); if(value.size() + 1 <= PIPE_BUF) { int errnum = 0; if(write(pipe[0][WRITE_PIPE], value.data(), sizeof(char) * value.size()) < 0) { errnum = errno; } if(errnum == 0 && write(pipe[0][WRITE_PIPE], "\n", 1) < 0) { errnum = errno; } closeAllPipe(1, pipe); return errnum; } else { pid_t pid = fork(); if(pid < 0) { return errno; } if(pid == 0) { // child pid = fork(); // double-fork (not wait IO-here process termination.) if(pid == 0) { // child close(pipe[0][READ_PIPE]); dup2(pipe[0][WRITE_PIPE], STDOUT_FILENO); if(write(STDOUT_FILENO, value.data(), value.size()) < 0) { exit(1); } if(write(STDOUT_FILENO, "\n", 1) < 0) { exit(1); } } exit(0); } closeAllPipe(1, pipe); waitpid(pid, nullptr, 0); return 0; } } enum class RedirOpenFlag { READ, WRITE, APPEND, }; /** * * @param fileName * @param openFlag * @param targetFD * @return * if failed, return non-zero value (errno) */ static int redirectToFile(const DSValue &fileName, RedirOpenFlag openFlag, int targetFD) { if(fileName.hasType(TYPE::String)) { int flag = 0; switch(openFlag) { case RedirOpenFlag::READ: flag = O_RDONLY; break; case RedirOpenFlag::WRITE: flag = O_WRONLY | O_CREAT | O_TRUNC; break; case RedirOpenFlag::APPEND: flag = O_WRONLY | O_APPEND | O_CREAT; break; } int fd = open(fileName.asCStr(), flag, 0666); if(fd < 0) { return errno; } if(dup2(fd, targetFD) < 0) { int e = errno; close(fd); return e; } close(fd); } else { assert(fileName.hasType(TYPE::UnixFD)); int fd = typeAs<UnixFdObject>(fileName).getValue(); if(openFlag == RedirOpenFlag::APPEND) { if(lseek(fd, 0, SEEK_END) == -1) { return errno; } } if(dup2(fd, targetFD) < 0) { return errno; } } return 0; } static int redirectImpl(const std::pair<RedirOP, DSValue> &pair) { switch(pair.first) { case RedirOP::IN_2_FILE: return redirectToFile(pair.second, RedirOpenFlag::READ, STDIN_FILENO); case RedirOP::OUT_2_FILE: return redirectToFile(pair.second, RedirOpenFlag::WRITE, STDOUT_FILENO); case RedirOP::OUT_2_FILE_APPEND: return redirectToFile(pair.second, RedirOpenFlag::APPEND, STDOUT_FILENO); case RedirOP::ERR_2_FILE: return redirectToFile(pair.second, RedirOpenFlag::WRITE, STDERR_FILENO); case RedirOP::ERR_2_FILE_APPEND: return redirectToFile(pair.second, RedirOpenFlag::APPEND, STDERR_FILENO); case RedirOP::MERGE_ERR_2_OUT_2_FILE: { int r = redirectToFile(pair.second, RedirOpenFlag::WRITE, STDOUT_FILENO); if(r != 0) { return r; } if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; } case RedirOP::MERGE_ERR_2_OUT_2_FILE_APPEND: { int r = redirectToFile(pair.second, RedirOpenFlag::APPEND, STDOUT_FILENO); if(r != 0) { return r; } if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; } case RedirOP::MERGE_ERR_2_OUT: if(dup2(STDOUT_FILENO, STDERR_FILENO) < 0) { return errno; } return 0; case RedirOP::MERGE_OUT_2_ERR: if(dup2(STDERR_FILENO, STDOUT_FILENO) < 0) { return errno; } return 0; case RedirOP::HERE_STR: return doIOHere(pair.second.asStrRef()); case RedirOP::NOP: break; } return 0; // do nothing } void RedirObject::passFDToExtProc() { for(auto &e : this->ops) { if(isPassingFD(e)) { typeAs<UnixFdObject>(e.second).closeOnExec(false); } } } bool RedirObject::redirect(DSState &st) { this->backupFDs(); for(auto &pair : this->ops) { int r = redirectImpl(pair); if(this->backupFDset > 0 && r != 0) { std::string msg = REDIR_ERROR; if(pair.second) { if(pair.second.hasType(TYPE::String)) { auto ref = pair.second.asStrRef(); if(!ref.empty()) { msg += ": "; msg.append(ref.data(), ref.size()); } } else if(pair.second.hasType(TYPE::UnixFD)) { msg += ": "; msg += std::to_string(typeAs<UnixFdObject>(pair.second).getValue()); } } raiseSystemError(st, r, std::move(msg)); return false; } } return true; } } // namespace ydsh<|endoftext|>
<commit_before>#include "remote.hh" #include "display_buffer.hh" #include "debug.hh" #include "client_manager.hh" #include "event_manager.hh" #include "buffer_manager.hh" #include "command_manager.hh" #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> namespace Kakoune { enum class RemoteUIMsg { PrintStatus, MenuShow, MenuSelect, MenuHide, InfoShow, InfoHide, Draw }; struct socket_error{}; class Message { public: Message(int sock) : m_socket(sock) {} ~Message() { if (m_stream.size() == 0) return; int res = ::write(m_socket, m_stream.data(), m_stream.size()); if (res == 0) throw peer_disconnected{}; } void write(const char* val, size_t size) { m_stream.insert(m_stream.end(), val, val + size); } template<typename T> void write(const T& val) { write((const char*)&val, sizeof(val)); }; void write(const String& str) { write(str.length()); write(str.c_str(), (int)str.length()); }; template<typename T> void write(const memoryview<T>& view) { write<uint32_t>(view.size()); for (auto& val : view) write(val); }; template<typename T> void write(const std::vector<T>& vec) { write(memoryview<T>(vec)); } void write(const DisplayAtom& atom) { write(atom.colors.first); write(atom.colors.second); write(atom.attribute); write(atom.content.content()); } void write(const DisplayLine& line) { write(line.atoms()); } void write(const DisplayBuffer& display_buffer) { write(display_buffer.lines()); } private: std::vector<char> m_stream; int m_socket; }; void read(int socket, char* buffer, size_t size) { while (size) { int res = ::read(socket, buffer, size); if (res == 0) throw peer_disconnected{}; if (res < 0) throw socket_error{}; buffer += res; size -= res; } } template<typename T> T read(int socket) { char value[sizeof(T)]; read(socket, value, sizeof(T)); return *(T*)(value); }; template<> String read<String>(int socket) { ByteCount length = read<ByteCount>(socket); if (length == 0) return String{}; char buffer[2048]; assert(length < 2048); read(socket, buffer, (int)length); return String(buffer, buffer+(int)length); }; template<typename T> std::vector<T> read_vector(int socket) { uint32_t size = read<uint32_t>(socket); std::vector<T> res; res.reserve(size); while (size--) res.push_back(read<T>(socket)); return res; }; template<> DisplayAtom read<DisplayAtom>(int socket) { Color fg_color = read<Color>(socket); Color bg_color = read<Color>(socket); Attribute attribute = read<Attribute>(socket); DisplayAtom atom(AtomContent(read<String>(socket))); atom.colors = { fg_color, bg_color }; atom.attribute = attribute; return atom; } template<> DisplayLine read<DisplayLine>(int socket) { return DisplayLine(0, read_vector<DisplayAtom>(socket)); } template<> DisplayBuffer read<DisplayBuffer>(int socket) { DisplayBuffer db; db.lines() = read_vector<DisplayLine>(socket); return db; } class RemoteUI : public UserInterface { public: RemoteUI(int socket); ~RemoteUI(); void print_status(const String& status, CharCount cursor_pos) override; void menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) override; void menu_select(int selected) override; void menu_hide() override; void info_show(const String& content, const DisplayCoord& anchor, MenuStyle style) override; void info_hide() override; void draw(const DisplayBuffer& display_buffer, const String& mode_line) override; bool is_key_available() override; Key get_key() override; DisplayCoord dimensions() override; void set_input_callback(InputCallback callback) override; private: FDWatcher m_socket_watcher; DisplayCoord m_dimensions; InputCallback m_input_callback; }; RemoteUI::RemoteUI(int socket) : m_socket_watcher(socket, [this](FDWatcher&) { if (m_input_callback) m_input_callback(); }) { write_debug("remote client connected: " + int_to_str(m_socket_watcher.fd())); } RemoteUI::~RemoteUI() { write_debug("remote client disconnected: " + int_to_str(m_socket_watcher.fd())); close(m_socket_watcher.fd()); } void RemoteUI::print_status(const String& status, CharCount cursor_pos) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::PrintStatus); msg.write(status); msg.write(cursor_pos); } void RemoteUI::menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuShow); msg.write(choices); msg.write(anchor); msg.write(style); } void RemoteUI::menu_select(int selected) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuSelect); msg.write(selected); } void RemoteUI::menu_hide() { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuHide); } void RemoteUI::info_show(const String& content, const DisplayCoord& anchor, MenuStyle style) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::InfoShow); msg.write(content); msg.write(anchor); msg.write(style); } void RemoteUI::info_hide() { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::InfoHide); } void RemoteUI::draw(const DisplayBuffer& display_buffer, const String& mode_line) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::Draw); msg.write(display_buffer); msg.write(mode_line); } static const Key::Modifiers resize_modifier = (Key::Modifiers)0x80; bool RemoteUI::is_key_available() { timeval tv; fd_set rfds; int sock = m_socket_watcher.fd(); FD_ZERO(&rfds); FD_SET(sock, &rfds); tv.tv_sec = 0; tv.tv_usec = 0; int res = select(sock+1, &rfds, NULL, NULL, &tv); return res == 1; } Key RemoteUI::get_key() { Key key = read<Key>(m_socket_watcher.fd()); if (key.modifiers == resize_modifier) { m_dimensions = { (int)(key.key >> 16), (int)(key.key & 0xFFFF) }; return Key::Invalid; } return key; } DisplayCoord RemoteUI::dimensions() { return m_dimensions; } void RemoteUI::set_input_callback(InputCallback callback) { m_input_callback = std::move(callback); } RemoteClient::RemoteClient(int socket, std::unique_ptr<UserInterface>&& ui, const String& init_command) : m_ui(std::move(ui)), m_dimensions(m_ui->dimensions()), m_socket_watcher{socket, [this](FDWatcher&){ process_next_message(); }} { Message msg(socket); msg.write(init_command.c_str(), (int)init_command.length()+1); Key key{ resize_modifier, Codepoint(((int)m_dimensions.line << 16) | (int)m_dimensions.column) }; msg.write(key); m_ui->set_input_callback([this]{ write_next_key(); }); } void RemoteClient::process_next_message() { int socket = m_socket_watcher.fd(); RemoteUIMsg msg = read<RemoteUIMsg>(socket); switch (msg) { case RemoteUIMsg::PrintStatus: { auto status = read<String>(socket); auto cursor_pos = read<CharCount>(socket); m_ui->print_status(status, cursor_pos); break; } case RemoteUIMsg::MenuShow: { auto choices = read_vector<String>(socket); auto anchor = read<DisplayCoord>(socket); auto style = read<MenuStyle>(socket); m_ui->menu_show(choices, anchor, style); break; } case RemoteUIMsg::MenuSelect: m_ui->menu_select(read<int>(socket)); break; case RemoteUIMsg::MenuHide: m_ui->menu_hide(); break; case RemoteUIMsg::InfoShow: { auto choices = read<String>(socket); auto anchor = read<DisplayCoord>(socket); auto style = read<MenuStyle>(socket); m_ui->info_show(choices, anchor, style); break; } case RemoteUIMsg::InfoHide: m_ui->info_hide(); break; case RemoteUIMsg::Draw: { DisplayBuffer display_buffer = read<DisplayBuffer>(socket); String mode_line = read<String>(socket); m_ui->draw(display_buffer, mode_line); break; } } } void RemoteClient::write_next_key() { Message msg(m_socket_watcher.fd()); // do that before checking dimensions as get_key may // handle a resize event. msg.write(m_ui->get_key()); DisplayCoord dimensions = m_ui->dimensions(); if (dimensions != m_dimensions) { m_dimensions = dimensions; Key key{ resize_modifier, Codepoint(((int)dimensions.line << 16) | (int)dimensions.column) }; msg.write(key); } } std::unique_ptr<RemoteClient> connect_to(const String& pid, std::unique_ptr<UserInterface>&& ui, const String& init_command) { auto filename = "/tmp/kak-" + pid; int sock = socket(AF_UNIX, SOCK_STREAM, 0); fcntl(sock, F_SETFD, FD_CLOEXEC); sockaddr_un addr; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, filename.c_str(), sizeof(addr.sun_path) - 1); if (connect(sock, (sockaddr*)&addr, sizeof(addr.sun_path)) == -1) throw runtime_error("connect to " + filename + " failed"); return std::unique_ptr<RemoteClient>{new RemoteClient{sock, std::move(ui), init_command}}; } // A client accepter handle a connection until it closes or a nul byte is // recieved. Everything recieved before is considered to be a command. // // * When a nul byte is recieved, the socket is handed to a new Client along // with the command. // * When the connection is closed, the command is run in an empty context. class ClientAccepter { public: ClientAccepter(int socket) : m_socket_watcher(socket, [this](FDWatcher&) { handle_available_input(); }) {} private: void handle_available_input() { int socket = m_socket_watcher.fd(); timeval tv{ 0, 0 }; fd_set rfds; do { char c; int res = ::read(socket, &c, 1); if (res <= 0) { if (not m_buffer.empty()) try { Context context{}; CommandManager::instance().execute(m_buffer, context); } catch (runtime_error& e) { write_debug("error running command '" + m_buffer + "' : " + e.description()); } delete this; return; } if (c == 0) // end of initial command stream, go to interactive ui mode { ClientManager::instance().create_client( std::unique_ptr<UserInterface>{new RemoteUI{socket}}, m_buffer); delete this; return; } else m_buffer += c; FD_ZERO(&rfds); FD_SET(socket, &rfds); } while (select(socket+1, &rfds, NULL, NULL, &tv) == 1); } String m_buffer; FDWatcher m_socket_watcher; }; Server::Server() : m_filename{"/tmp/kak-" + int_to_str(getpid())} { int listen_sock = socket(AF_UNIX, SOCK_STREAM, 0); fcntl(listen_sock, F_SETFD, FD_CLOEXEC); sockaddr_un addr; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, m_filename.c_str(), sizeof(addr.sun_path) - 1); if (bind(listen_sock, (sockaddr*) &addr, sizeof(sockaddr_un)) == -1) throw runtime_error("unable to bind listen socket " + m_filename); if (listen(listen_sock, 4) == -1) throw runtime_error("unable to listen on socket " + m_filename); auto accepter = [](FDWatcher& watcher) { sockaddr_un client_addr; socklen_t client_addr_len = sizeof(sockaddr_un); int sock = accept(watcher.fd(), (sockaddr*) &client_addr, &client_addr_len); if (sock == -1) throw runtime_error("accept failed"); fcntl(sock, F_SETFD, FD_CLOEXEC); new ClientAccepter{sock}; }; m_listener.reset(new FDWatcher{listen_sock, accepter}); } Server::~Server() { unlink(m_filename.c_str()); close(m_listener->fd()); } } <commit_msg>ClientAccepter triggers window redrawing after executing a command<commit_after>#include "remote.hh" #include "display_buffer.hh" #include "debug.hh" #include "client_manager.hh" #include "event_manager.hh" #include "buffer_manager.hh" #include "command_manager.hh" #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> namespace Kakoune { enum class RemoteUIMsg { PrintStatus, MenuShow, MenuSelect, MenuHide, InfoShow, InfoHide, Draw }; struct socket_error{}; class Message { public: Message(int sock) : m_socket(sock) {} ~Message() { if (m_stream.size() == 0) return; int res = ::write(m_socket, m_stream.data(), m_stream.size()); if (res == 0) throw peer_disconnected{}; } void write(const char* val, size_t size) { m_stream.insert(m_stream.end(), val, val + size); } template<typename T> void write(const T& val) { write((const char*)&val, sizeof(val)); }; void write(const String& str) { write(str.length()); write(str.c_str(), (int)str.length()); }; template<typename T> void write(const memoryview<T>& view) { write<uint32_t>(view.size()); for (auto& val : view) write(val); }; template<typename T> void write(const std::vector<T>& vec) { write(memoryview<T>(vec)); } void write(const DisplayAtom& atom) { write(atom.colors.first); write(atom.colors.second); write(atom.attribute); write(atom.content.content()); } void write(const DisplayLine& line) { write(line.atoms()); } void write(const DisplayBuffer& display_buffer) { write(display_buffer.lines()); } private: std::vector<char> m_stream; int m_socket; }; void read(int socket, char* buffer, size_t size) { while (size) { int res = ::read(socket, buffer, size); if (res == 0) throw peer_disconnected{}; if (res < 0) throw socket_error{}; buffer += res; size -= res; } } template<typename T> T read(int socket) { char value[sizeof(T)]; read(socket, value, sizeof(T)); return *(T*)(value); }; template<> String read<String>(int socket) { ByteCount length = read<ByteCount>(socket); if (length == 0) return String{}; char buffer[2048]; assert(length < 2048); read(socket, buffer, (int)length); return String(buffer, buffer+(int)length); }; template<typename T> std::vector<T> read_vector(int socket) { uint32_t size = read<uint32_t>(socket); std::vector<T> res; res.reserve(size); while (size--) res.push_back(read<T>(socket)); return res; }; template<> DisplayAtom read<DisplayAtom>(int socket) { Color fg_color = read<Color>(socket); Color bg_color = read<Color>(socket); Attribute attribute = read<Attribute>(socket); DisplayAtom atom(AtomContent(read<String>(socket))); atom.colors = { fg_color, bg_color }; atom.attribute = attribute; return atom; } template<> DisplayLine read<DisplayLine>(int socket) { return DisplayLine(0, read_vector<DisplayAtom>(socket)); } template<> DisplayBuffer read<DisplayBuffer>(int socket) { DisplayBuffer db; db.lines() = read_vector<DisplayLine>(socket); return db; } class RemoteUI : public UserInterface { public: RemoteUI(int socket); ~RemoteUI(); void print_status(const String& status, CharCount cursor_pos) override; void menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) override; void menu_select(int selected) override; void menu_hide() override; void info_show(const String& content, const DisplayCoord& anchor, MenuStyle style) override; void info_hide() override; void draw(const DisplayBuffer& display_buffer, const String& mode_line) override; bool is_key_available() override; Key get_key() override; DisplayCoord dimensions() override; void set_input_callback(InputCallback callback) override; private: FDWatcher m_socket_watcher; DisplayCoord m_dimensions; InputCallback m_input_callback; }; RemoteUI::RemoteUI(int socket) : m_socket_watcher(socket, [this](FDWatcher&) { if (m_input_callback) m_input_callback(); }) { write_debug("remote client connected: " + int_to_str(m_socket_watcher.fd())); } RemoteUI::~RemoteUI() { write_debug("remote client disconnected: " + int_to_str(m_socket_watcher.fd())); close(m_socket_watcher.fd()); } void RemoteUI::print_status(const String& status, CharCount cursor_pos) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::PrintStatus); msg.write(status); msg.write(cursor_pos); } void RemoteUI::menu_show(const memoryview<String>& choices, const DisplayCoord& anchor, MenuStyle style) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuShow); msg.write(choices); msg.write(anchor); msg.write(style); } void RemoteUI::menu_select(int selected) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuSelect); msg.write(selected); } void RemoteUI::menu_hide() { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::MenuHide); } void RemoteUI::info_show(const String& content, const DisplayCoord& anchor, MenuStyle style) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::InfoShow); msg.write(content); msg.write(anchor); msg.write(style); } void RemoteUI::info_hide() { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::InfoHide); } void RemoteUI::draw(const DisplayBuffer& display_buffer, const String& mode_line) { Message msg(m_socket_watcher.fd()); msg.write(RemoteUIMsg::Draw); msg.write(display_buffer); msg.write(mode_line); } static const Key::Modifiers resize_modifier = (Key::Modifiers)0x80; bool RemoteUI::is_key_available() { timeval tv; fd_set rfds; int sock = m_socket_watcher.fd(); FD_ZERO(&rfds); FD_SET(sock, &rfds); tv.tv_sec = 0; tv.tv_usec = 0; int res = select(sock+1, &rfds, NULL, NULL, &tv); return res == 1; } Key RemoteUI::get_key() { Key key = read<Key>(m_socket_watcher.fd()); if (key.modifiers == resize_modifier) { m_dimensions = { (int)(key.key >> 16), (int)(key.key & 0xFFFF) }; return Key::Invalid; } return key; } DisplayCoord RemoteUI::dimensions() { return m_dimensions; } void RemoteUI::set_input_callback(InputCallback callback) { m_input_callback = std::move(callback); } RemoteClient::RemoteClient(int socket, std::unique_ptr<UserInterface>&& ui, const String& init_command) : m_ui(std::move(ui)), m_dimensions(m_ui->dimensions()), m_socket_watcher{socket, [this](FDWatcher&){ process_next_message(); }} { Message msg(socket); msg.write(init_command.c_str(), (int)init_command.length()+1); Key key{ resize_modifier, Codepoint(((int)m_dimensions.line << 16) | (int)m_dimensions.column) }; msg.write(key); m_ui->set_input_callback([this]{ write_next_key(); }); } void RemoteClient::process_next_message() { int socket = m_socket_watcher.fd(); RemoteUIMsg msg = read<RemoteUIMsg>(socket); switch (msg) { case RemoteUIMsg::PrintStatus: { auto status = read<String>(socket); auto cursor_pos = read<CharCount>(socket); m_ui->print_status(status, cursor_pos); break; } case RemoteUIMsg::MenuShow: { auto choices = read_vector<String>(socket); auto anchor = read<DisplayCoord>(socket); auto style = read<MenuStyle>(socket); m_ui->menu_show(choices, anchor, style); break; } case RemoteUIMsg::MenuSelect: m_ui->menu_select(read<int>(socket)); break; case RemoteUIMsg::MenuHide: m_ui->menu_hide(); break; case RemoteUIMsg::InfoShow: { auto choices = read<String>(socket); auto anchor = read<DisplayCoord>(socket); auto style = read<MenuStyle>(socket); m_ui->info_show(choices, anchor, style); break; } case RemoteUIMsg::InfoHide: m_ui->info_hide(); break; case RemoteUIMsg::Draw: { DisplayBuffer display_buffer = read<DisplayBuffer>(socket); String mode_line = read<String>(socket); m_ui->draw(display_buffer, mode_line); break; } } } void RemoteClient::write_next_key() { Message msg(m_socket_watcher.fd()); // do that before checking dimensions as get_key may // handle a resize event. msg.write(m_ui->get_key()); DisplayCoord dimensions = m_ui->dimensions(); if (dimensions != m_dimensions) { m_dimensions = dimensions; Key key{ resize_modifier, Codepoint(((int)dimensions.line << 16) | (int)dimensions.column) }; msg.write(key); } } std::unique_ptr<RemoteClient> connect_to(const String& pid, std::unique_ptr<UserInterface>&& ui, const String& init_command) { auto filename = "/tmp/kak-" + pid; int sock = socket(AF_UNIX, SOCK_STREAM, 0); fcntl(sock, F_SETFD, FD_CLOEXEC); sockaddr_un addr; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, filename.c_str(), sizeof(addr.sun_path) - 1); if (connect(sock, (sockaddr*)&addr, sizeof(addr.sun_path)) == -1) throw runtime_error("connect to " + filename + " failed"); return std::unique_ptr<RemoteClient>{new RemoteClient{sock, std::move(ui), init_command}}; } // A client accepter handle a connection until it closes or a nul byte is // recieved. Everything recieved before is considered to be a command. // // * When a nul byte is recieved, the socket is handed to a new Client along // with the command. // * When the connection is closed, the command is run in an empty context. class ClientAccepter { public: ClientAccepter(int socket) : m_socket_watcher(socket, [this](FDWatcher&) { handle_available_input(); }) {} private: void handle_available_input() { int socket = m_socket_watcher.fd(); timeval tv{ 0, 0 }; fd_set rfds; do { char c; int res = ::read(socket, &c, 1); if (res <= 0) { if (not m_buffer.empty()) try { Context context{}; CommandManager::instance().execute(m_buffer, context); } catch (runtime_error& e) { write_debug("error running command '" + m_buffer + "' : " + e.description()); } ClientManager::instance().redraw_clients(); delete this; return; } if (c == 0) // end of initial command stream, go to interactive ui mode { ClientManager::instance().create_client( std::unique_ptr<UserInterface>{new RemoteUI{socket}}, m_buffer); delete this; return; } else m_buffer += c; FD_ZERO(&rfds); FD_SET(socket, &rfds); } while (select(socket+1, &rfds, NULL, NULL, &tv) == 1); } String m_buffer; FDWatcher m_socket_watcher; }; Server::Server() : m_filename{"/tmp/kak-" + int_to_str(getpid())} { int listen_sock = socket(AF_UNIX, SOCK_STREAM, 0); fcntl(listen_sock, F_SETFD, FD_CLOEXEC); sockaddr_un addr; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, m_filename.c_str(), sizeof(addr.sun_path) - 1); if (bind(listen_sock, (sockaddr*) &addr, sizeof(sockaddr_un)) == -1) throw runtime_error("unable to bind listen socket " + m_filename); if (listen(listen_sock, 4) == -1) throw runtime_error("unable to listen on socket " + m_filename); auto accepter = [](FDWatcher& watcher) { sockaddr_un client_addr; socklen_t client_addr_len = sizeof(sockaddr_un); int sock = accept(watcher.fd(), (sockaddr*) &client_addr, &client_addr_len); if (sock == -1) throw runtime_error("accept failed"); fcntl(sock, F_SETFD, FD_CLOEXEC); new ClientAccepter{sock}; }; m_listener.reset(new FDWatcher{listen_sock, accepter}); } Server::~Server() { unlink(m_filename.c_str()); close(m_listener->fd()); } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> #include <queue> #include <stdio.h> #include <cstring> #include <sys/wait.h> #include <sys/types.h> using namespace std; using namespace boost; class Connectors //abstract base class so we can dynamically call run { private: bool bee; public: void setbool(bool b) { bee = b; } bool getbool() { return bee; } virtual bool run(bool state) = 0; }; class Semicolon : public Connectors { private: vector<char *> vctr; public: Semicolon(vector<string> v) : vctr(50) //constructor creates char* vector { //which stores one command+params vctr.reserve(v.size()); //in a semicolon object for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //makes sure the command ends with a null char } //so execvp can determine the end virtual bool run(bool state) { char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if were in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class And : public Connectors { private: vector<char *> vctr; public: And(vector<string> v) : vctr(50) { vctr.reserve(v.size()); //store one command+param of type And for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null char } virtual bool run(bool state) { if (state != 1) { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if were in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class Or : public Connectors { private: vector<char *> vctr; public: Or(vector<string> v) : vctr(50) //stores one command+params of type Or { vctr.reserve(v.size()); for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null } virtual bool run(bool state) { if (state != 0) { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if were in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; int main() { int w = 0; while (w == 0) { // extra credit part char *username; int host; if ((username = getlogin()) != NULL) // get the username { char name[101]; int len = 100; if ((host = gethostname(name, len)) == 0) // get the hostname { cout << username << "@" << name << "$ "; } else { cout << "$ "; //outputs terminal $ } } else { cout << "$ "; } string input; getline(cin, input); //gets user input //containers we'll use for storage vector< vector<string> > v; vector<string> t; vector<Connectors*> objects; queue<string> q; int column = 0; //creates tokenizer and char separator to parse input typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" ", ";"); tokenizer tokens(input, sep); bool flag = 0; //flag to check when to start a new column //holds commands in a 2d vector for (tokenizer::iterator itr = tokens.begin(); itr != tokens.end(); ++itr) { if ((*itr == ";") || (*itr == "||") || (*itr == "&&")) { q.push(*itr); //pushes connecter into queue and increments column column = column + 1; flag = 0; } else if (*itr == "#") { break; //if theres a comment, break out of loop } else { if (!flag) { v.push_back(t); //starts a new column v.at(column).push_back(*itr); flag = 1; } else { //push value into position v.at(column).push_back(*itr); } } } //checks the contents of v //for (unsigned i = 0; i < v.size(); ++i) //{ //for (unsigned j = 0; j < v.at(i).size(); ++j) //{ //cout << v.at(i).at(j); //} //} //this part of the code creates a temp vector current which holds //a single command+param chunk at a time //then determines the connector previous to the command its told to run //it then creates the corresponding connector class type object //and pushes the new object into a vector of Connectors pointers bool first = 1; vector<string> current; for (unsigned i = 0; i < v.size(); ++i) { for (unsigned j = 0; j < v.at(i).size(); ++j) { current.push_back(v.at(i).at(j)); } if (!q.empty() && first != 1) { if (q.front() == ";") { objects.push_back(new Semicolon(current)); } if (q.front() == "||") { objects.push_back(new Or(current)); } if (q.front() == "&&") { objects.push_back(new And(current)); } q.pop(); } if (first == 1) { objects.push_back(new Semicolon(current)); first = 0; } current.clear(); } bool beg = 0; bool durr = 0; //this loop goes through the object vector and calls run on each //object, dynamically callig the run of the class type //cout << "Size: " << objects.size() << endl; for (unsigned i = 0; i < objects.size(); ++i) { //cout << "Curr size: " << objects.size() << endl; durr = objects.at(i)->run(beg); //cout << "State after run: " << durr << endl; beg = durr; } } return 0; } <commit_msg>fixed typos<commit_after>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> #include <queue> #include <stdio.h> #include <cstring> #include <sys/wait.h> #include <sys/types.h> using namespace std; using namespace boost; class Connectors //abstract base class so we can dynamically call run { private: bool bee; public: void setbool(bool b) { bee = b; } bool getbool() { return bee; } virtual bool run(bool state) = 0; }; class Semicolon : public Connectors { private: vector<char *> vctr; public: Semicolon(vector<string> v) : vctr(50) //constructor creates char* vector { //which stores one command+params vctr.reserve(v.size()); //in a semicolon object for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //makes sure the command ends with a null char } //so execvp can determine the end virtual bool run(bool state) { char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //returns the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class And : public Connectors { private: vector<char *> vctr; public: And(vector<string> v) : vctr(50) { vctr.reserve(v.size()); //store one command+param of type And for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null char } virtual bool run(bool state) { if (state != 1) //return if the previous command failed { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class Or : public Connectors { private: vector<char *> vctr; public: Or(vector<string> v) : vctr(50) //stores one command+params of type Or { vctr.reserve(v.size()); for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null } virtual bool run(bool state) { if (state != 0) //return if the previous command succeeded { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { exit(0); } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = wait(&status)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; int main() { int w = 0; while (w == 0) { // extra credit part char *username; int host; if ((username = getlogin()) != NULL) // get the username { char name[101]; int len = 100; if ((host = gethostname(name, len)) == 0) // get the hostname { cout << username << "@" << name << "$ "; } else { cout << "$ "; //outputs terminal $ } } else { cout << "$ "; } string input; getline(cin, input); //gets user input //containers we'll use for storage vector< vector<string> > v; vector<string> t; vector<Connectors*> objects; queue<string> q; int column = 0; //creates tokenizer and char separator to parse input typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" ", ";"); tokenizer tokens(input, sep); bool flag = 0; //flag to check when to start a new column //holds commands in a 2d vector for (tokenizer::iterator itr = tokens.begin(); itr != tokens.end(); ++itr) { if ((*itr == ";") || (*itr == "||") || (*itr == "&&")) { q.push(*itr); //pushes connector into queue column = column + 1; //increments column flag = 0; } else if (*itr == "#") { break; //if there's a comment, break out of loop } else { if (!flag) { v.push_back(t); //starts a new column v.at(column).push_back(*itr); flag = 1; } else { //push value into position v.at(column).push_back(*itr); } } } //checks the contents of v //for (unsigned i = 0; i < v.size(); ++i) //{ //for (unsigned j = 0; j < v.at(i).size(); ++j) //{ //cout << v.at(i).at(j); //} //} //this part of the code creates a temp vector current which holds //a single command+param chunk at a time //then determines the connector previous to the command its told to run //it then creates the corresponding connector class type object //and pushes the new object into a vector of Connectors pointers bool first = 1; vector<string> current; for (unsigned i = 0; i < v.size(); ++i) { for (unsigned j = 0; j < v.at(i).size(); ++j) { current.push_back(v.at(i).at(j)); } if (!q.empty() && first != 1) { if (q.front() == ";") { objects.push_back(new Semicolon(current)); } if (q.front() == "||") { objects.push_back(new Or(current)); } if (q.front() == "&&") { objects.push_back(new And(current)); } q.pop(); } if (first == 1) { objects.push_back(new Semicolon(current)); first = 0; } current.clear(); } bool beg = 0; bool durr = 0; //this loop goes through the object vector and calls run on each //object, dynamically calling the run of the class type //cout << "Size: " << objects.size() << endl; for (unsigned i = 0; i < objects.size(); ++i) { //cout << "Curr size: " << objects.size() << endl; durr = objects.at(i)->run(beg); //cout << "State after run: " << durr << endl; beg = durr; } } return 0; } <|endoftext|>
<commit_before>#include <set> #include <string> #include <fstream> #include <iostream> class Scene { protected: // Storage for shapes in scene set<Shape> shapes; set<Light> lights; public: /* * In the case of an empty constructor, Scene will generate a predefined * scene for rendering. */ Scene() { shapes.add(new Shere(new Point(0,0,0), 7.0, 0.0)); shapes.add(new Shere(new Point(10,10,10), 3.0, 0.7)); shapes.add(new Plane(new Point(10,0,0), new Vector(1,0,0) , 0.5)); // Yet to add default lights. }n Scene(string fileName) { ifstream input_scene (fileName); // Read the file and add specified shapes. // We need to figure out what our syntax/grammar is first though. input_scene.close(); } } <commit_msg>Added Scene destructor and fixed indentation issue. Fixed includes.<commit_after>#include <std::set> #include <string> #include <std::fstream> #include <iostream> class Scene { protected: // Storage for shapes in scene set<Shape> shapes; set<Light> lights; public: /* * In the case of an empty constructor, Scene will generate a predefined * scene for rendering. */ Scene() { shapes.add(new Shere(new Point(0,0,0), 7.0, 0.0)); shapes.add(new Shere(new Point(10,10,10), 3.0, 0.7)); shapes.add(new Plane(new Point(10,0,0), new Vector(1,0,0) , 0.5)); // Yet to add default lights. } Scene(string fileName) { ifstream input_scene (fileName); // Read the file and add specified shapes. // We need to figure out what our syntax/grammar is first though. } ~Scene() { for(set<Shape>::iterator it = shapes.cbegin(); it != shapes.cend(); i++) { delete *it; } for(set<Sphere>::iterator it = lights.cbegin(); it != shapes.cend(); i++) { delete *it; } } } <|endoftext|>
<commit_before>#include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./graphics/buffer_drawer.h" #include "./camera_controllers.h" #include "./nodes.h" #include "./labelling/labeller_frame_data.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" #include "./placement/to_gray.h" #include "./placement/distance_transform.h" #include "./placement/occupancy.h" #include "./placement/apollonius.h" #include "./texture_mapper_manager.h" #include "./constraint_buffer_object.h" #include "./placement/constraint_updater.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> forcesLabeller, std::shared_ptr<Placement::Labeller> placementLabeller, std::shared_ptr<TextureMapperManager> textureMapperManager) : nodes(nodes), labels(labels), forcesLabeller(forcesLabeller), placementLabeller(placementLabeller), frustumOptimizer(nodes), textureMapperManager(textureMapperManager) { cameraControllers = std::make_shared<CameraControllers>(invokeManager, camera); fbo = std::make_shared<Graphics::FrameBufferObject>(); constraintBufferObject = std::make_shared<ConstraintBufferObject>(); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { nodes->clear(); qInfo() << "Destructor of Scene" << "Remaining managers instances" << managers.use_count(); } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); positionQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/positionRenderTarget.frag"); distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/distanceTransform.frag"); transparentQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/transparentOverlay.frag"); fbo->initialize(gl, width, height); constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); managers->getObjectManager()->initialize(gl, 128, 10000000); haBuffer->initialize(gl, managers); quad->initialize(gl, managers); positionQuad->initialize(gl, managers); distanceTransformQuad->initialize(gl, managers); transparentQuad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); textureMapperManager->resize(width, height); textureMapperManager->initialize(gl, fbo, constraintBufferObject); auto drawer = std::make_shared<Graphics::BufferDrawer>( textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize(), gl, managers->getShaderManager()); auto constraintUpdater = std::make_shared<ConstraintUpdater>( drawer, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); placementLabeller->initialize( textureMapperManager->getOccupancyTextureMapper(), textureMapperManager->getDistanceTransformTextureMapper(), textureMapperManager->getApolloniusTextureMapper(), textureMapperManager->getConstraintTextureMapper(), constraintUpdater); } void Scene::cleanup() { placementLabeller->cleanup(); textureMapperManager->cleanup(); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraControllers->update(frameTime); frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); /* auto newPositions = forcesLabeller->update(LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); */ auto newPositions = placementLabeller->getLastPlacementResult(); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData = createRenderData(); renderNodesWithHABufferIntoFBO(renderData); glAssert(gl->glDisable(GL_DEPTH_TEST)); renderScreenQuad(); textureMapperManager->update(); constraintBufferObject->bind(); placementLabeller->update(LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); constraintBufferObject->unbind(); glAssert(gl->glViewport(0, 0, width, height)); if (showConstraintOverlay) { constraintBufferObject->bindTexture(GL_TEXTURE0); renderQuad(transparentQuad, Eigen::Matrix4f::Identity()); } if (showBufferDebuggingViews) renderDebuggingViews(renderData); glAssert(gl->glEnable(GL_DEPTH_TEST)); nodes->renderLabels(gl, managers, renderData); } void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData) { fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); haBuffer->render(managers, renderData); // doPick(); fbo->unbind(); } void Scene::renderDebuggingViews(const RenderData &renderData) { fbo->bindDepthTexture(GL_TEXTURE0); auto transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindOccupancyTexture(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindDistanceTransform(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(distanceTransformQuad, transformation.matrix()); textureMapperManager->bindApollonius(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); constraintBufferObject->bindTexture(GL_TEXTURE0); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); } void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad, Eigen::Matrix4f modelMatrix) { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = modelMatrix; quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::renderScreenQuad() { fbo->bindColorTexture(GL_TEXTURE0); renderQuad(quad, Eigen::Matrix4f::Identity()); } void Scene::resize(int width, int height) { this->width = width; this->height = height; placementLabeller->resize(width, height); shouldResize = true; forcesLabeller->resize(width, height); } RenderData Scene::createRenderData() { RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); renderData.modelMatrix = Eigen::Matrix4f::Identity(); renderData.windowPixelSize = Eigen::Vector2f(width, height); return renderData; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } void Scene::enableBufferDebuggingViews(bool enable) { showBufferDebuggingViews = enable; } void Scene::enableConstraingOverlay(bool enable) { showConstraintOverlay = enable; } <commit_msg>Re-enable picking.<commit_after>#include "./scene.h" #include <Eigen/Core> #include <Eigen/Geometry> #include <string> #include <vector> #include "./graphics/gl.h" #include "./input/invoke_manager.h" #include "./graphics/render_data.h" #include "./graphics/managers.h" #include "./graphics/volume_manager.h" #include "./graphics/shader_program.h" #include "./graphics/buffer_drawer.h" #include "./camera_controllers.h" #include "./nodes.h" #include "./labelling/labeller_frame_data.h" #include "./label_node.h" #include "./eigen_qdebug.h" #include "./utils/path_helper.h" #include "./placement/to_gray.h" #include "./placement/distance_transform.h" #include "./placement/occupancy.h" #include "./placement/apollonius.h" #include "./texture_mapper_manager.h" #include "./constraint_buffer_object.h" #include "./placement/constraint_updater.h" Scene::Scene(std::shared_ptr<InvokeManager> invokeManager, std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels, std::shared_ptr<Forces::Labeller> forcesLabeller, std::shared_ptr<Placement::Labeller> placementLabeller, std::shared_ptr<TextureMapperManager> textureMapperManager) : nodes(nodes), labels(labels), forcesLabeller(forcesLabeller), placementLabeller(placementLabeller), frustumOptimizer(nodes), textureMapperManager(textureMapperManager) { cameraControllers = std::make_shared<CameraControllers>(invokeManager, camera); fbo = std::make_shared<Graphics::FrameBufferObject>(); constraintBufferObject = std::make_shared<ConstraintBufferObject>(); managers = std::make_shared<Graphics::Managers>(); } Scene::~Scene() { nodes->clear(); qInfo() << "Destructor of Scene" << "Remaining managers instances" << managers.use_count(); } void Scene::initialize() { glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f)); quad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/textureForRenderBuffer.frag"); positionQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/positionRenderTarget.frag"); distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/distanceTransform.frag"); transparentQuad = std::make_shared<Graphics::ScreenQuad>( ":shader/pass.vert", ":shader/transparentOverlay.frag"); fbo->initialize(gl, width, height); constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); haBuffer = std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height)); managers->getShaderManager()->initialize(gl, haBuffer); managers->getObjectManager()->initialize(gl, 128, 10000000); haBuffer->initialize(gl, managers); quad->initialize(gl, managers); positionQuad->initialize(gl, managers); distanceTransformQuad->initialize(gl, managers); transparentQuad->initialize(gl, managers); managers->getTextureManager()->initialize(gl, true, 8); textureMapperManager->resize(width, height); textureMapperManager->initialize(gl, fbo, constraintBufferObject); auto drawer = std::make_shared<Graphics::BufferDrawer>( textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize(), gl, managers->getShaderManager()); auto constraintUpdater = std::make_shared<ConstraintUpdater>( drawer, textureMapperManager->getBufferSize(), textureMapperManager->getBufferSize()); placementLabeller->initialize( textureMapperManager->getOccupancyTextureMapper(), textureMapperManager->getDistanceTransformTextureMapper(), textureMapperManager->getApolloniusTextureMapper(), textureMapperManager->getConstraintTextureMapper(), constraintUpdater); } void Scene::cleanup() { placementLabeller->cleanup(); textureMapperManager->cleanup(); } void Scene::update(double frameTime, QSet<Qt::Key> keysPressed) { this->frameTime = frameTime; cameraControllers->update(frameTime); frustumOptimizer.update(camera.getViewMatrix()); camera.updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(), frustumOptimizer.getFar()); /* auto newPositions = forcesLabeller->update(LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); */ auto newPositions = placementLabeller->getLastPlacementResult(); for (auto &labelNode : nodes->getLabelNodes()) { labelNode->labelPosition = newPositions[labelNode->label.id]; } } void Scene::render() { if (shouldResize) { camera.resize(width, height); fbo->resize(width, height); shouldResize = false; } glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); RenderData renderData = createRenderData(); renderNodesWithHABufferIntoFBO(renderData); glAssert(gl->glDisable(GL_DEPTH_TEST)); renderScreenQuad(); textureMapperManager->update(); constraintBufferObject->bind(); placementLabeller->update(LabellerFrameData( frameTime, camera.getProjectionMatrix(), camera.getViewMatrix())); constraintBufferObject->unbind(); glAssert(gl->glViewport(0, 0, width, height)); if (showConstraintOverlay) { constraintBufferObject->bindTexture(GL_TEXTURE0); renderQuad(transparentQuad, Eigen::Matrix4f::Identity()); } if (showBufferDebuggingViews) renderDebuggingViews(renderData); glAssert(gl->glEnable(GL_DEPTH_TEST)); nodes->renderLabels(gl, managers, renderData); } void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData) { fbo->bind(); glAssert(gl->glViewport(0, 0, width, height)); glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); haBuffer->clearAndPrepare(managers); nodes->render(gl, managers, renderData); managers->getObjectManager()->render(renderData); haBuffer->render(managers, renderData); doPick(); fbo->unbind(); } void Scene::renderDebuggingViews(const RenderData &renderData) { fbo->bindDepthTexture(GL_TEXTURE0); auto transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindOccupancyTexture(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); textureMapperManager->bindDistanceTransform(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(distanceTransformQuad, transformation.matrix()); textureMapperManager->bindApollonius(); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); constraintBufferObject->bindTexture(GL_TEXTURE0); transformation = Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) * Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1))); renderQuad(quad, transformation.matrix()); } void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad, Eigen::Matrix4f modelMatrix) { RenderData renderData; renderData.projectionMatrix = Eigen::Matrix4f::Identity(); renderData.viewMatrix = Eigen::Matrix4f::Identity(); renderData.modelMatrix = modelMatrix; quad->getShaderProgram()->bind(); quad->getShaderProgram()->setUniform("textureSampler", 0); quad->renderImmediately(gl, managers, renderData); } void Scene::renderScreenQuad() { fbo->bindColorTexture(GL_TEXTURE0); renderQuad(quad, Eigen::Matrix4f::Identity()); } void Scene::resize(int width, int height) { this->width = width; this->height = height; placementLabeller->resize(width, height); shouldResize = true; forcesLabeller->resize(width, height); } RenderData Scene::createRenderData() { RenderData renderData; renderData.projectionMatrix = camera.getProjectionMatrix(); renderData.viewMatrix = camera.getViewMatrix(); renderData.cameraPosition = camera.getPosition(); renderData.modelMatrix = Eigen::Matrix4f::Identity(); renderData.windowPixelSize = Eigen::Vector2f(width, height); return renderData; } void Scene::pick(int id, Eigen::Vector2f position) { pickingPosition = position; performPicking = true; pickingLabelId = id; } void Scene::doPick() { if (!performPicking) return; float depth = -2.0f; fbo->bindDepthTexture(GL_TEXTURE0); glAssert(gl->glReadPixels(pickingPosition.x(), height - pickingPosition.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)); Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f, pickingPosition.y() * -2.0f / height + 1.0f, depth * 2.0f - 1.0f, 1.0f); Eigen::Matrix4f viewProjection = camera.getProjectionMatrix() * camera.getViewMatrix(); Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC; positionWorld = positionWorld / positionWorld.w(); qWarning() << "picked:" << positionWorld; performPicking = false; auto label = labels->getById(pickingLabelId); label.anchorPosition = toVector3f(positionWorld); labels->update(label); } void Scene::enableBufferDebuggingViews(bool enable) { showBufferDebuggingViews = enable; } void Scene::enableConstraingOverlay(bool enable) { showConstraintOverlay = enable; } <|endoftext|>
<commit_before>#include "defs.h" #include "search.h" #include "eval.h" #include "movegen.h" #include "transptable.h" #include "movepicker.h" #include "generalmovepicker.h" #include "capturemovepicker.h" #include <string> #include <algorithm> #include <time.h> #include <iostream> #include <chrono> Search::Search(const Board& board, Limits limits, bool logUci) : _orderingInfo(OrderingInfo(const_cast<TranspTable*>(&_tt))), _limits(limits), _board(board), _logUci(logUci), _stop(false), _limitCheckCount(0), _bestScore(0) { if (_limits.infinite) { // Infinite search _searchDepth = INF; _timeAllocated = INF; } else if (_limits.depth != 0) { // Depth search _searchDepth = _limits.depth; _timeAllocated = INF; } else if (_limits.time[_board.getActivePlayer()] != 0) { // Time search int timeRemaining = _limits.time[_board.getActivePlayer()] + _limits.increment[_board.getActivePlayer()]; // If movestogo not specified, sudden death, assume SUDDEN_DEATH_MOVESTOGO moves remaining _timeAllocated = _limits.movesToGo == 0 ? timeRemaining / SUDDEN_DEATH_MOVESTOGO : timeRemaining / _limits.movesToGo; // Depth is infinity in a timed search (ends when time runs out) _searchDepth = MAX_SEARCH_DEPTH; } else { // No limits specified, use default depth _searchDepth = DEFAULT_SEARCH_DEPTH; _timeAllocated = INF; } } void Search::iterDeep() { _start = std::chrono::steady_clock::now(); for (int currDepth=1;currDepth<=_searchDepth;currDepth++) { _rootMax(_board, currDepth); int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-_start).count(); // If limits were exceeded in the search, break without logging UCI info (search was incomplete) if (_stop) break; if (_logUci) { _logUciInfo(_getPv(currDepth), currDepth, _bestMove, _bestScore, _nodes, elapsed); } // If the last search has exceeded or hit 50% of the allocated time, stop searching if (elapsed >= (_timeAllocated / 2)) break; } if (_logUci) std::cout << "bestmove " << getBestMove().getNotation() << std::endl; } MoveList Search::_getPv(int length) { MoveList pv; Board currBoard = _board; const TranspTableEntry* currEntry; int currLength = 0; while (currLength++ < length && (currEntry = _tt.getEntry(currBoard.getZKey()))) { pv.push_back(currEntry->getBestMove()); currBoard.doMove(currEntry->getBestMove()); } return pv; } void Search::_logUciInfo(const MoveList& pv, int depth, Move bestMove, int bestScore, int nodes, int elapsed) { std::string pvString; for(auto move : pv) { pvString += move.getNotation() + " "; } std::string scoreString; if (bestScore == INF) { scoreString = "mate " + std::to_string(pv.size()); } else if (_bestScore == -INF) { scoreString = "mate -" + std::to_string(pv.size()); } else { scoreString = "cp " + std::to_string(bestScore); } // Avoid divide by zero errors with nps elapsed++; std::cout << "info depth " + std::to_string(depth) + " "; std::cout << "nodes " + std::to_string(nodes) + " "; std::cout << "score " + scoreString + " "; std::cout << "nps " + std::to_string(nodes * 1000 / elapsed) + " "; std::cout << "time " + std::to_string(elapsed) + " "; std::cout << "pv " + pvString; std::cout << std::endl; } void Search::stop() { _stop = true; } Move Search::getBestMove() { return _bestMove; } int Search::getBestScore() { return _bestScore; } bool Search::_checkLimits() { if (--_limitCheckCount > 0) { return false; } _limitCheckCount = 4096; int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-_start).count(); if (_limits.nodes != 0 && (_nodes >= _limits.nodes)) return true; if (elapsed >= (_timeAllocated)) return true; return false; } void Search::_rootMax(const Board& board, int depth) { MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); _nodes = 0; // If no legal moves are avaliable, just return, setting bestmove to a null move if (legalMoves.size() == 0) { _bestMove = Move(); _bestScore = -INF; return; } GeneralMovePicker movePicker(const_cast<OrderingInfo*>(&_orderingInfo), const_cast<Board*>(&board), const_cast<MoveList*>(&legalMoves)); int alpha = -INF; int beta = INF; int currScore; Move bestMove; bool fullWindow = true; while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); _orderingInfo.incrementPly(); if (fullWindow) { currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha); } else { currScore = -_negaMax(movedBoard, depth-1, -alpha-1, -alpha); if (currScore > alpha) currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha); } _orderingInfo.deincrementPly(); if (_stop || _checkLimits()) { _stop = true; break; } // If the current score is better than alpha, or this is the first move in the loop if (currScore > alpha) { fullWindow = false; bestMove = move; alpha = currScore; // Break if we've found a checkmate if (currScore == INF) { break; } } } // If the best move was not set in the main search loop // alpha was not raised at any point, just pick the first move // avaliable (arbitrary) to avoid putting a null move in the // transposition table if (bestMove.getFlags() & Move::NULL_MOVE) { bestMove = legalMoves.at(0); } if (!_stop) { TranspTableEntry ttEntry(alpha, depth, TranspTableEntry::EXACT, bestMove); _tt.set(board.getZKey(), ttEntry); _bestMove = bestMove; _bestScore = alpha; } } int Search::_negaMax(const Board& board, int depth, int alpha, int beta) { // Check search limits if (_stop || _checkLimits()) { _stop = true; return 0; } int alphaOrig = alpha; const TranspTableEntry* ttEntry = _tt.getEntry(board.getZKey()); // Check transposition table cache if (ttEntry && (ttEntry->getDepth() >= depth)) { switch(ttEntry->getFlag()) { case TranspTable::EXACT: return ttEntry->getScore(); case TranspTable::UPPER_BOUND: beta = std::min(beta, ttEntry->getScore()); break; case TranspTable::LOWER_BOUND: alpha = std::max(alpha, ttEntry->getScore()); break; } if (alpha >= beta) { return ttEntry->getScore(); } } // Transposition table lookups are inconclusive, generate moves and recurse MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); // Check for checkmate and stalemate if (legalMoves.size() == 0) { int score = board.colorIsInCheck(board.getActivePlayer()) ? -INF : 0; // -INF = checkmate, 0 = stalemate (draw) return score; } // Eval if depth is 0 if (depth == 0) { return _qSearch(board, alpha, beta); } GeneralMovePicker movePicker(const_cast<OrderingInfo*>(&_orderingInfo), const_cast<Board*>(&board), const_cast<MoveList*>(&legalMoves)); Move bestMove; bool fullWindow = true; while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); int score; _orderingInfo.incrementPly(); if (fullWindow) { score = -_negaMax(movedBoard, depth-1, -beta, -alpha); } else { score = -_negaMax(movedBoard, depth-1, -alpha-1, -alpha); if (score > alpha) score = -_negaMax(movedBoard, depth-1, -beta, -alpha); } _orderingInfo.deincrementPly(); // Beta cutoff if (score >= beta) { // Add this move as a new killer move and update history if move is quiet _orderingInfo.updateKillers(_orderingInfo.getPly(), move); if (!(move.getFlags() & Move::CAPTURE)) { _orderingInfo.incrementHistory(_board.getActivePlayer(), move.getFrom(), move.getTo(), depth); } // Add a new tt entry for this node TranspTableEntry newTTEntry(score, depth, TranspTableEntry::LOWER_BOUND, move); _tt.set(board.getZKey(), newTTEntry); return beta; } // Check if alpha raised (new best move) if (score > alpha) { fullWindow = false; alpha = score; bestMove = move; } } // If the best move was not set in the main search loop // alpha was not raised at any point, just pick the first move // avaliable (arbitrary) to avoid putting a null move in the // transposition table if (bestMove.getFlags() & Move::NULL_MOVE) { bestMove = legalMoves.at(0); } // Store bestScore in transposition table TranspTableEntry::Flag flag; if (alpha <= alphaOrig) { flag = TranspTableEntry::UPPER_BOUND; } else { flag = TranspTableEntry::EXACT; } TranspTableEntry newTTEntry(alpha, depth, flag, bestMove); _tt.set(board.getZKey(), newTTEntry); return alpha; } int Search::_qSearch(const Board& board, int alpha, int beta) { // Check search limits if (_stop || _checkLimits()) { _stop = true; return 0; } MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); // Check for checkmate / stalemate if (legalMoves.size() == 0) { if (board.colorIsInCheck(board.getActivePlayer())) { // Checkmate return -INF; } else { // Stalemate return 0; } } int standPat = Eval::evaluate(board, board.getActivePlayer()); _nodes ++; CaptureMovePicker movePicker(const_cast<MoveList*>(&legalMoves)); // If node is quiet, just return eval if (!movePicker.hasNext()) { return standPat; } if (standPat >= beta) { return beta; } if (alpha < standPat) { alpha = standPat; } while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); int score = -_qSearch(movedBoard, -beta, -alpha); if (score >= beta) { return beta; } if (score > alpha) { alpha = score; } } return alpha; } <commit_msg>Improve time management<commit_after>#include "defs.h" #include "search.h" #include "eval.h" #include "movegen.h" #include "transptable.h" #include "movepicker.h" #include "generalmovepicker.h" #include "capturemovepicker.h" #include <string> #include <algorithm> #include <time.h> #include <iostream> #include <chrono> Search::Search(const Board& board, Limits limits, bool logUci) : _orderingInfo(OrderingInfo(const_cast<TranspTable*>(&_tt))), _limits(limits), _board(board), _logUci(logUci), _stop(false), _limitCheckCount(0), _bestScore(0) { if (_limits.infinite) { // Infinite search _searchDepth = INF; _timeAllocated = INF; } else if (_limits.depth != 0) { // Depth search _searchDepth = _limits.depth; _timeAllocated = INF; } else if (_limits.time[_board.getActivePlayer()] != 0) { // Time search int timeRemaining = _limits.time[_board.getActivePlayer()]; // Divide up the remaining time (If movestogo not specified we are in sudden death) if(_limits.movesToGo == 0) { _timeAllocated = timeRemaining / SUDDEN_DEATH_MOVESTOGO; } else { // A small constant (3) is added to _limits.movesToGo when dividing to // ensure we don't go over time when movesToGo is small _timeAllocated = timeRemaining / (_limits.movesToGo + 3); } // Use all of the increment to think _timeAllocated += _limits.increment[_board.getActivePlayer()]; // Depth is infinity in a timed search (ends when time runs out) _searchDepth = MAX_SEARCH_DEPTH; } else { // No limits specified, use default depth _searchDepth = DEFAULT_SEARCH_DEPTH; _timeAllocated = INF; } } void Search::iterDeep() { _start = std::chrono::steady_clock::now(); for (int currDepth=1;currDepth<=_searchDepth;currDepth++) { _rootMax(_board, currDepth); int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-_start).count(); // If limits were exceeded in the search, break without logging UCI info (search was incomplete) if (_stop) break; if (_logUci) { _logUciInfo(_getPv(currDepth), currDepth, _bestMove, _bestScore, _nodes, elapsed); } // If the last search has exceeded or hit 50% of the allocated time, stop searching if (elapsed >= (_timeAllocated / 2)) break; } if (_logUci) std::cout << "bestmove " << getBestMove().getNotation() << std::endl; } MoveList Search::_getPv(int length) { MoveList pv; Board currBoard = _board; const TranspTableEntry* currEntry; int currLength = 0; while (currLength++ < length && (currEntry = _tt.getEntry(currBoard.getZKey()))) { pv.push_back(currEntry->getBestMove()); currBoard.doMove(currEntry->getBestMove()); } return pv; } void Search::_logUciInfo(const MoveList& pv, int depth, Move bestMove, int bestScore, int nodes, int elapsed) { std::string pvString; for(auto move : pv) { pvString += move.getNotation() + " "; } std::string scoreString; if (bestScore == INF) { scoreString = "mate " + std::to_string(pv.size()); } else if (_bestScore == -INF) { scoreString = "mate -" + std::to_string(pv.size()); } else { scoreString = "cp " + std::to_string(bestScore); } // Avoid divide by zero errors with nps elapsed++; std::cout << "info depth " + std::to_string(depth) + " "; std::cout << "nodes " + std::to_string(nodes) + " "; std::cout << "score " + scoreString + " "; std::cout << "nps " + std::to_string(nodes * 1000 / elapsed) + " "; std::cout << "time " + std::to_string(elapsed) + " "; std::cout << "pv " + pvString; std::cout << std::endl; } void Search::stop() { _stop = true; } Move Search::getBestMove() { return _bestMove; } int Search::getBestScore() { return _bestScore; } bool Search::_checkLimits() { if (--_limitCheckCount > 0) { return false; } _limitCheckCount = 4096; int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-_start).count(); if (_limits.nodes != 0 && (_nodes >= _limits.nodes)) return true; if (elapsed >= (_timeAllocated)) return true; return false; } void Search::_rootMax(const Board& board, int depth) { MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); _nodes = 0; // If no legal moves are avaliable, just return, setting bestmove to a null move if (legalMoves.size() == 0) { _bestMove = Move(); _bestScore = -INF; return; } GeneralMovePicker movePicker(const_cast<OrderingInfo*>(&_orderingInfo), const_cast<Board*>(&board), const_cast<MoveList*>(&legalMoves)); int alpha = -INF; int beta = INF; int currScore; Move bestMove; bool fullWindow = true; while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); _orderingInfo.incrementPly(); if (fullWindow) { currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha); } else { currScore = -_negaMax(movedBoard, depth-1, -alpha-1, -alpha); if (currScore > alpha) currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha); } _orderingInfo.deincrementPly(); if (_stop || _checkLimits()) { _stop = true; break; } // If the current score is better than alpha, or this is the first move in the loop if (currScore > alpha) { fullWindow = false; bestMove = move; alpha = currScore; // Break if we've found a checkmate if (currScore == INF) { break; } } } // If the best move was not set in the main search loop // alpha was not raised at any point, just pick the first move // avaliable (arbitrary) to avoid putting a null move in the // transposition table if (bestMove.getFlags() & Move::NULL_MOVE) { bestMove = legalMoves.at(0); } if (!_stop) { TranspTableEntry ttEntry(alpha, depth, TranspTableEntry::EXACT, bestMove); _tt.set(board.getZKey(), ttEntry); _bestMove = bestMove; _bestScore = alpha; } } int Search::_negaMax(const Board& board, int depth, int alpha, int beta) { // Check search limits if (_stop || _checkLimits()) { _stop = true; return 0; } int alphaOrig = alpha; const TranspTableEntry* ttEntry = _tt.getEntry(board.getZKey()); // Check transposition table cache if (ttEntry && (ttEntry->getDepth() >= depth)) { switch(ttEntry->getFlag()) { case TranspTable::EXACT: return ttEntry->getScore(); case TranspTable::UPPER_BOUND: beta = std::min(beta, ttEntry->getScore()); break; case TranspTable::LOWER_BOUND: alpha = std::max(alpha, ttEntry->getScore()); break; } if (alpha >= beta) { return ttEntry->getScore(); } } // Transposition table lookups are inconclusive, generate moves and recurse MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); // Check for checkmate and stalemate if (legalMoves.size() == 0) { int score = board.colorIsInCheck(board.getActivePlayer()) ? -INF : 0; // -INF = checkmate, 0 = stalemate (draw) return score; } // Eval if depth is 0 if (depth == 0) { return _qSearch(board, alpha, beta); } GeneralMovePicker movePicker(const_cast<OrderingInfo*>(&_orderingInfo), const_cast<Board*>(&board), const_cast<MoveList*>(&legalMoves)); Move bestMove; bool fullWindow = true; while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); int score; _orderingInfo.incrementPly(); if (fullWindow) { score = -_negaMax(movedBoard, depth-1, -beta, -alpha); } else { score = -_negaMax(movedBoard, depth-1, -alpha-1, -alpha); if (score > alpha) score = -_negaMax(movedBoard, depth-1, -beta, -alpha); } _orderingInfo.deincrementPly(); // Beta cutoff if (score >= beta) { // Add this move as a new killer move and update history if move is quiet _orderingInfo.updateKillers(_orderingInfo.getPly(), move); if (!(move.getFlags() & Move::CAPTURE)) { _orderingInfo.incrementHistory(_board.getActivePlayer(), move.getFrom(), move.getTo(), depth); } // Add a new tt entry for this node TranspTableEntry newTTEntry(score, depth, TranspTableEntry::LOWER_BOUND, move); _tt.set(board.getZKey(), newTTEntry); return beta; } // Check if alpha raised (new best move) if (score > alpha) { fullWindow = false; alpha = score; bestMove = move; } } // If the best move was not set in the main search loop // alpha was not raised at any point, just pick the first move // avaliable (arbitrary) to avoid putting a null move in the // transposition table if (bestMove.getFlags() & Move::NULL_MOVE) { bestMove = legalMoves.at(0); } // Store bestScore in transposition table TranspTableEntry::Flag flag; if (alpha <= alphaOrig) { flag = TranspTableEntry::UPPER_BOUND; } else { flag = TranspTableEntry::EXACT; } TranspTableEntry newTTEntry(alpha, depth, flag, bestMove); _tt.set(board.getZKey(), newTTEntry); return alpha; } int Search::_qSearch(const Board& board, int alpha, int beta) { // Check search limits if (_stop || _checkLimits()) { _stop = true; return 0; } MoveGen movegen(board); MoveList legalMoves = movegen.getLegalMoves(); // Check for checkmate / stalemate if (legalMoves.size() == 0) { if (board.colorIsInCheck(board.getActivePlayer())) { // Checkmate return -INF; } else { // Stalemate return 0; } } int standPat = Eval::evaluate(board, board.getActivePlayer()); _nodes ++; CaptureMovePicker movePicker(const_cast<MoveList*>(&legalMoves)); // If node is quiet, just return eval if (!movePicker.hasNext()) { return standPat; } if (standPat >= beta) { return beta; } if (alpha < standPat) { alpha = standPat; } while (movePicker.hasNext()) { Move move = movePicker.getNext(); Board movedBoard = board; movedBoard.doMove(move); int score = -_qSearch(movedBoard, -beta, -alpha); if (score >= beta) { return beta; } if (score > alpha) { alpha = score; } } return alpha; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "server.h" #include "common.h" using namespace std; using namespace httpserver; void WebServerResource::render_GET(const http_request& req, http_response** res) { *res = new http_response(http_response_builder("I is hungry. Post me some stuff.", 200).string_response()); } void WebServerResource::render_POST(const http_request& req, http_response** res) { string &data_str = req.get_content(); unsigned char *data = (unsigned char*)req.get_content().c_str(); switch(ImageDB::getInstance()->getImage(data, req.get_content().length())) { case PRESENT: *res = new http_response(http_response_builder("",200).string_response()); break; case ABSENT: *res = new http_response(http_response_builder("",404).string_response()); break; case ADDED: *res = new http_response(http_response_builder("",201).string_response()); break; default: *res = new http_response(http_response_builder("",301).string_response()); break; } } void WebServerResource::addImages(const std::string& path) { ImageDB::getInstance()->addImages(path); } int main(int argc, char **argv) { webserver server = create_webserver(PORT).max_threads(WS_THREADS); WebServerResource resource; server.register_resource("/", &resource, true); server.start(false); if(argc > 1) { cout <<"Hello, I will process your images"<<endl; resource.addImages(argv[1]); } else { cout <<"Hello."<<endl; } server.start(true); cout <<" Done. Now send me some images"<<endl; return 0; } <commit_msg>fixed extra string copy<commit_after>#include <iostream> #include <string> #include "server.h" #include "common.h" using namespace std; using namespace httpserver; void WebServerResource::render_GET(const http_request& req, http_response** res) { *res = new http_response(http_response_builder("I is hungry. Post me some stuff.", 200).string_response()); } void WebServerResource::render_POST(const http_request& req, http_response** res) { string data_str = req.get_content(); unsigned char *data = (unsigned char*)data_str.c_str(); switch(ImageDB::getInstance()->getImage(data, data_str.length())) { case PRESENT: *res = new http_response(http_response_builder("",200).string_response()); break; case ABSENT: *res = new http_response(http_response_builder("",404).string_response()); break; case ADDED: *res = new http_response(http_response_builder("",201).string_response()); break; default: *res = new http_response(http_response_builder("",301).string_response()); break; } } void WebServerResource::addImages(const std::string& path) { ImageDB::getInstance()->addImages(path); } int main(int argc, char **argv) { webserver server = create_webserver(PORT).max_threads(WS_THREADS); WebServerResource resource; server.register_resource("/", &resource, true); server.start(false); if(argc > 1) { cout <<"Hello, I will process your images"<<endl; resource.addImages(argv[1]); } else { cout <<"Hello."<<endl; } server.start(true); cout <<" Done. Now send me some images"<<endl; return 0; } <|endoftext|>
<commit_before>/* * File: PIDController.cpp * Author: User * * Created on April 22, 2014, 6:28 PM */ #include "PIDController.h" using namespace boost::chrono; PIDController::PIDController(double kp, double ki, double kd) { this->setGains(kp, ki, kd); this->setConstraints(-1, -1); this->init(); } PIDController::PIDController(double kp, double ki, double kd, double lowerConstraint, double upperConstraint) { this->setGains(kp, ki, kd); this->setConstraints(lowerConstraint, upperConstraint); this->init(); } PIDController::PIDController() { this->setGains(0, 0, 0); this->setConstraints(-100,100); this->init(); } PIDController::PIDController(const PIDController& orig) { this->setGains(orig.kp, orig.ki, orig.kd); this->setConstraints(orig.lowerConstraint, orig.upperConstraint); integrator = orig.integrator; lastError = orig.lastError; } PIDController::~PIDController() { } void PIDController::targetSetpoint(double setpoint) { this->setpoint = setpoint; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.start(); performance_timer.start(); } void PIDController::setGains(double kp, double ki, double kd) { this->kp = kp; this->ki = ki; this->kd = kd; } void PIDController::setConstraints(double lowerConstraint, double upperConstraint) { this->lowerConstraint = lowerConstraint; this->upperConstraint = upperConstraint; } double PIDController::getSetpoint() { return setpoint; } double PIDController::getKp() { return kp; } double PIDController::getKi() { return ki; } double PIDController::getKd() { return kd; } void PIDController::init() { setpoint = 0; integrator = 0; lastError = 0; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.stop(); performance_timer.stop(); } bool PIDController::hasSettled() { if(settlingTime != -1) { return true; } else { return false; } } double PIDController::calc(double processVariable) { sample_timer.stop(); double percent = (processVariable/setpoint) - 1; if(percent > percentOvershoot && percent > 0) { percentOvershoot = processVariable/setpoint; peakTime = (performance_timer.elapsed().wall)/1e9; } if(abs(percent) < 0.05 && settlingTime == -1) { performance_timer.stop(); settlingTime = (performance_timer.elapsed().wall)/1e9; std::cout << "Peak Time Tp: " << peakTime << std::endl; std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl; std::cout << "Settling Time Ts" << settlingTime << std::endl; } double error = setpoint - processVariable; double samplingTime = (sample_timer.elapsed().wall)/1e9; double differentiator = (error - lastError)/samplingTime; integrator += (error * samplingTime); double controlVariable = kp * error + ki * integrator + kd * differentiator; if(controlVariable < lowerConstraint) { controlVariable = lowerConstraint; } else if(controlVariable > upperConstraint) { controlVariable = upperConstraint; } lastError = error; sample_timer.start(); return controlVariable; } <commit_msg>Fix tabs again<commit_after>/* * File: PIDController.cpp * Author: User * * Created on April 22, 2014, 6:28 PM */ #include "PIDController.h" using namespace boost::chrono; PIDController::PIDController(double kp, double ki, double kd) { this->setGains(kp, ki, kd); this->setConstraints(-1, -1); this->init(); } PIDController::PIDController(double kp, double ki, double kd, double lowerConstraint, double upperConstraint) { this->setGains(kp, ki, kd); this->setConstraints(lowerConstraint, upperConstraint); this->init(); } PIDController::PIDController() { this->setGains(0, 0, 0); this->setConstraints(-100,100); this->init(); } PIDController::PIDController(const PIDController& orig) { this->setGains(orig.kp, orig.ki, orig.kd); this->setConstraints(orig.lowerConstraint, orig.upperConstraint); integrator = orig.integrator; lastError = orig.lastError; } PIDController::~PIDController() { } void PIDController::targetSetpoint(double setpoint) { this->setpoint = setpoint; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.start(); performance_timer.start(); } void PIDController::setGains(double kp, double ki, double kd) { this->kp = kp; this->ki = ki; this->kd = kd; } void PIDController::setConstraints(double lowerConstraint, double upperConstraint) { this->lowerConstraint = lowerConstraint; this->upperConstraint = upperConstraint; } double PIDController::getSetpoint() { return setpoint; } double PIDController::getKp() { return kp; } double PIDController::getKi() { return ki; } double PIDController::getKd() { return kd; } void PIDController::init() { setpoint = 0; integrator = 0; lastError = 0; peakTime = -1; settlingTime = -1; percentOvershoot = 0; sample_timer.stop(); performance_timer.stop(); } bool PIDController::hasSettled() { if(settlingTime != -1) { return true; } else { return false; } } double PIDController::calc(double processVariable) { sample_timer.stop(); double percent = (processVariable/setpoint) - 1; if(percent > percentOvershoot && percent > 0) { percentOvershoot = processVariable/setpoint; peakTime = (performance_timer.elapsed().wall)/1e9; } if(abs(percent) < 0.05 && settlingTime == -1) { performance_timer.stop(); settlingTime = (performance_timer.elapsed().wall)/1e9; std::cout << "Peak Time Tp: " << peakTime << std::endl; std::cout << "Percent Overshoot %OS: " << percentOvershoot << std::endl; std::cout << "Settling Time Ts" << settlingTime << std::endl; } double error = setpoint - processVariable; double samplingTime = (sample_timer.elapsed().wall)/1e9; double differentiator = (error - lastError)/samplingTime; integrator += (error * samplingTime); double controlVariable = kp * error + ki * integrator + kd * differentiator; if(controlVariable < lowerConstraint) { controlVariable = lowerConstraint; } else if(controlVariable > upperConstraint) { controlVariable = upperConstraint; } lastError = error; sample_timer.start(); return controlVariable; } <|endoftext|>
<commit_before>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * 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 (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ #ifndef _SVNCPP_LOG_ENTRY_H_ #define _SVNCPP_LOG_ENTRY_H_ //Qt #include <qglobal.h> #if QT_VERSION < 0x040000 #include <qstring.h> #include <qvaluelist.h> #else #include <QtCore> #endif // apr #include "apr_time.h" // subversion api #include "svn_types.h" namespace svn { class LogChangePathEntry { public: LogChangePathEntry (const char *path_, char action_, const char *copyFromPath_, const svn_revnum_t copyFromRevision_); LogChangePathEntry (const QString &path_, char action_, const QString &copyFromPath_, const svn_revnum_t copyFromRevision_); LogChangePathEntry (const QString &path_, char action_, const QString &copyFromPath_, const svn_revnum_t copyFromRevision_, const QString &copyToPath_, const svn_revnum_t copyToRevision_); LogChangePathEntry(); QString path; char action; QString copyFromPath; svn_revnum_t copyFromRevision; //! future use or useful in backends QString copyToPath; //! future use or useful in backends svn_revnum_t copyToRevision; }; class LogEntry { public: LogEntry (); LogEntry (const svn_revnum_t revision, const char * author, const char * date, const char * message); svn_revnum_t revision; QString author; QString message; #if QT_VERSION < 0x040000 QValueList<LogChangePathEntry> changedPaths; #else QList<LogChangePathEntry> changedPaths; #endif apr_time_t date; }; } #endif /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <commit_msg>- typedef LogChangePathEntries<commit_after>/* * ==================================================================== * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved. * * 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 (in the file LGPL.txt); if not, * write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://rapidsvn.tigris.org/. * ==================================================================== */ #ifndef _SVNCPP_LOG_ENTRY_H_ #define _SVNCPP_LOG_ENTRY_H_ //Qt #include <qglobal.h> #if QT_VERSION < 0x040000 #include <qstring.h> #include <qvaluelist.h> #else #include <QtCore> #endif // apr #include "apr_time.h" // subversion api #include "svn_types.h" namespace svn { class LogChangePathEntry { public: LogChangePathEntry (const char *path_, char action_, const char *copyFromPath_, const svn_revnum_t copyFromRevision_); LogChangePathEntry (const QString &path_, char action_, const QString &copyFromPath_, const svn_revnum_t copyFromRevision_); LogChangePathEntry (const QString &path_, char action_, const QString &copyFromPath_, const svn_revnum_t copyFromRevision_, const QString &copyToPath_, const svn_revnum_t copyToRevision_); LogChangePathEntry(); QString path; char action; QString copyFromPath; svn_revnum_t copyFromRevision; //! future use or useful in backends QString copyToPath; //! future use or useful in backends svn_revnum_t copyToRevision; }; #if QT_VERSION < 0x040000 typedef QValueList<LogChangePathEntry> LogChangePathEntries; #else typedef QList<LogChangePathEntry> LogChangePathEntries; #endif class LogEntry { public: LogEntry (); LogEntry (const svn_revnum_t revision, const char * author, const char * date, const char * message); svn_revnum_t revision; QString author; QString message; LogChangePathEntries changedPaths; apr_time_t date; }; } #endif /* ----------------------------------------------------------------- * local variables: * eval: (load-file "../../rapidsvn-dev.el") * end: */ <|endoftext|>
<commit_before><commit_msg>added wxFAIL<commit_after><|endoftext|>
<commit_before>/* $Id$ */ // Helper macros can be found in this file // A set of them can be used to connect to proof and execute selectors. TProof* connectProof(const char* proofServer) { TProof* proof = TProof::Open(proofServer); if (!proof) { printf("ERROR: PROOF connection not established.\n"); return 0; } // enable the new packetizer //proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive")); proof->ClearInput(); return proof; } Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot) { // if not proof load libraries if (!gProof) { TObjArray* librariesList = libraries.Tokenize(";"); for (Int_t i=0; i<librariesList->GetEntries(); ++i) { TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i)); if (!str) continue; printf("Loading %s...", str->String().Data()); Int_t result = CheckLoadLibrary(str->String()); if (result < 0) { printf("failed\n"); //return kFALSE; } else printf("succeeded\n"); } } else { if (useAliRoot > 0) ProofEnableAliRoot(useAliRoot); TObjArray* packagesList = packages.Tokenize(";"); for (Int_t i=0; i<packagesList->GetEntries(); ++i) { TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i)); if (!str) continue; /*if (!EnablePackageLocal(str->String())) { printf("Loading of package %s locally failed\n", str->String().Data()); return kFALSE; }*/ if (gProof->UploadPackage(Form("%s.par", str->String().Data()))) { printf("Uploading of package %s failed\n", str->String().Data()); return kFALSE; } if (gProof->EnablePackage(str->String())) { printf("Loading of package %s failed\n", str->String().Data()); return kFALSE; } } } return kTRUE; } Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber) { if (!gProof) chain->GetUserInfo()->AddAll(inputList); else { for (Int_t i=0; i<inputList->GetEntries(); ++i) gProof->AddInput(inputList->At(i)); } TStopwatch timer; timer.Start(); Long64_t result = -1; if (gProof) { chain->SetProof(); result = chain->Process(selectorName, option, entries); } else result = chain->Process(selectorName, option, entries); if (result < 0) printf("ERROR: Executing process failed with %d.\n", result); timer.Stop(); timer.Print(); return result; } void ProofEnableAliRoot(Int_t aliroot) { // enables a locally deployed AliRoot in a PROOF cluster /* executes the following commands on each node: gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head") gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include"); gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux")) gSystem->Load("libMinuit"); gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C"); */ const char* location = 0; const char* target = "tgt_linux"; switch (aliroot) { case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break; case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break; case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break; default: return; } gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE); gProof->AddIncludePath(Form("%s/include", location)); gProof->AddDynamicPath(Form("%s/lib/%s", location, target)); // load all libraries gProof->Exec("gSystem->Load(\"libMinuit\")"); gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")"); } Bool_t EnablePackageLocal(const char* package) { printf("Enabling package %s locally...\n", package); TString currentDir(gSystem->pwd()); if (!gSystem->cd(package)) return kFALSE; gROOT->ProcessLine(".x PROOF-INF/SETUP.C"); gSystem->cd(currentDir); return kTRUE; } Int_t CheckLoadLibrary(const char* library) { // checks if a library is already loaded, if not loads the library if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0) return 1; return gSystem->Load(library); } void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE) { // deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT // when localAliRoot is false ESD.par is also deployed TProof::Reset(proofServer); TVirtualProof* proof = TProof::Open(proofServer); proof->ClearPackages(); if (localAliRoot) ProofEnableAliRoot(); else { proof->UploadPackage("$ALICE_ROOT/ESD.par"); proof->EnablePackage("ESD"); } proof->UploadPackage("$ALICE_ROOT/PWG0base.par"); proof->EnablePackage("PWG0base"); proof->UploadPackage("$ALICE_ROOT/PWG0dep.par"); proof->EnablePackage("PWG0dep"); } <commit_msg>new aliroot path on CAF<commit_after>/* $Id$ */ // Helper macros can be found in this file // A set of them can be used to connect to proof and execute selectors. TProof* connectProof(const char* proofServer) { TProof* proof = TProof::Open(proofServer); if (!proof) { printf("ERROR: PROOF connection not established.\n"); return 0; } // enable the new packetizer //proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive")); proof->ClearInput(); return proof; } Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot) { // if not proof load libraries if (!gProof) { TObjArray* librariesList = libraries.Tokenize(";"); for (Int_t i=0; i<librariesList->GetEntries(); ++i) { TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i)); if (!str) continue; printf("Loading %s...", str->String().Data()); Int_t result = CheckLoadLibrary(str->String()); if (result < 0) { printf("failed\n"); //return kFALSE; } else printf("succeeded\n"); } } else { if (useAliRoot > 0) ProofEnableAliRoot(useAliRoot); TObjArray* packagesList = packages.Tokenize(";"); for (Int_t i=0; i<packagesList->GetEntries(); ++i) { TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i)); if (!str) continue; /*if (!EnablePackageLocal(str->String())) { printf("Loading of package %s locally failed\n", str->String().Data()); return kFALSE; }*/ if (gProof->UploadPackage(Form("%s.par", str->String().Data()))) { printf("Uploading of package %s failed\n", str->String().Data()); return kFALSE; } if (gProof->EnablePackage(str->String())) { printf("Loading of package %s failed\n", str->String().Data()); return kFALSE; } } } return kTRUE; } Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber) { if (!gProof) chain->GetUserInfo()->AddAll(inputList); else { for (Int_t i=0; i<inputList->GetEntries(); ++i) gProof->AddInput(inputList->At(i)); } TStopwatch timer; timer.Start(); Long64_t result = -1; if (gProof) { chain->SetProof(); result = chain->Process(selectorName, option, entries); } else result = chain->Process(selectorName, option, entries); if (result < 0) printf("ERROR: Executing process failed with %d.\n", result); timer.Stop(); timer.Print(); return result; } void ProofEnableAliRoot(Int_t aliroot) { // enables a locally deployed AliRoot in a PROOF cluster /* executes the following commands on each node: gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head") gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include"); gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux")) gSystem->Load("libMinuit"); gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C"); */ const char* location = 0; const char* target = "tgt_linux"; switch (aliroot) { case 1: location = "/afs/cern.ch/alice/caf/sw/ALICE/v4-04-Release/slc4_ia32_gcc34/aliroot"; break; default: return; } gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE); gProof->AddIncludePath(Form("%s/include", location)); gProof->AddDynamicPath(Form("%s/lib/%s", location, target)); // load all libraries gProof->Exec("gSystem->Load(\"libMinuit\")"); gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")"); } Bool_t EnablePackageLocal(const char* package) { printf("Enabling package %s locally...\n", package); TString currentDir(gSystem->pwd()); if (!gSystem->cd(package)) return kFALSE; gROOT->ProcessLine(".x PROOF-INF/SETUP.C"); gSystem->cd(currentDir); return kTRUE; } Int_t CheckLoadLibrary(const char* library) { // checks if a library is already loaded, if not loads the library if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0) return 1; return gSystem->Load(library); } void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE) { // deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT // when localAliRoot is false ESD.par is also deployed TProof::Reset(proofServer); TVirtualProof* proof = TProof::Open(proofServer); proof->ClearPackages(); if (localAliRoot) ProofEnableAliRoot(); else { proof->UploadPackage("$ALICE_ROOT/ESD.par"); proof->EnablePackage("ESD"); } proof->UploadPackage("$ALICE_ROOT/PWG0base.par"); proof->EnablePackage("PWG0base"); proof->UploadPackage("$ALICE_ROOT/PWG0dep.par"); proof->EnablePackage("PWG0dep"); } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Intel Corporation. All Rights Reserved. ///////////////////////////////////////////////////////////////////////////// // This set of tests is valid for any device that supports the HDR feature // ///////////////////////////////////////////////////////////////////////////// #define CATCH_CONFIG_MAIN #include "../../catch.h" #include "../func-common.h" #include <librealsense2/rsutil.h> #include <easylogging++.h> #ifdef BUILD_SHARED_LIBS // With static linkage, ELPP is initialized by librealsense, so doing it here will // create errors. When we're using the shared .so/.dll, the two are separate and we have // to initialize ours if we want to use the APIs! INITIALIZE_EASYLOGGINGPP #endif using namespace rs2; // structure of a matrix 4 X 4, representing rotation and translation as following: // pos_and_rot[i][j] is // _ _ // | | | // | rotation | translation | // | (3x3) | (3x1) | // | _________ |____________ | // | 0 | 1 | // |_ (1x3) | (1x1) _| // struct position_and_rotation { double pos_and_rot[4][4]; position_and_rotation operator* (const position_and_rotation& other) { position_and_rotation product; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { product.pos_and_rot[i][j] = 0; for (int k = 0; k < 4; k++) product.pos_and_rot[i][j] += pos_and_rot[i][k] * other.pos_and_rot[k][j]; } } return product; } bool equals(const position_and_rotation& other) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { double tolerance = 0.0000001; // lower tolerance needed for translation if (j == 3) tolerance = 0.0005; if (fabs(pos_and_rot[i][j] - other.pos_and_rot[i][j]) > tolerance) return false; } return true; } bool is_identity() { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { double target = 0.0; if (i == j) target = 1.0; double tolerance = 0.0000001; // lower tolerance needed for translation if (j == 3) tolerance = 0.0005; if (fabs(pos_and_rot[i][j] - target) > tolerance) return false; } return true; } }; position_and_rotation matrix_4_by_4_from_translation_and_rotation(const float* position, const float* rotation) { position_and_rotation pos_rot; pos_rot.pos_and_rot[0][0] = static_cast<double>(rotation[0]); pos_rot.pos_and_rot[0][1] = static_cast<double>(rotation[1]); pos_rot.pos_and_rot[0][2] = static_cast<double>(rotation[2]); pos_rot.pos_and_rot[1][0] = static_cast<double>(rotation[3]); pos_rot.pos_and_rot[1][1] = static_cast<double>(rotation[4]); pos_rot.pos_and_rot[1][2] = static_cast<double>(rotation[5]); pos_rot.pos_and_rot[2][0] = static_cast<double>(rotation[6]); pos_rot.pos_and_rot[2][1] = static_cast<double>(rotation[7]); pos_rot.pos_and_rot[2][2] = static_cast<double>(rotation[8]); pos_rot.pos_and_rot[3][0] = 0.0; pos_rot.pos_and_rot[3][1] = 0.0; pos_rot.pos_and_rot[3][2] = 0.0; pos_rot.pos_and_rot[0][3] = static_cast<double>(position[0]); pos_rot.pos_and_rot[1][3] = static_cast<double>(position[1]); pos_rot.pos_and_rot[2][3] = static_cast<double>(position[2]); pos_rot.pos_and_rot[3][3] = 1.0; return pos_rot; } // checking the extrinsics graph // steps are: // 1. get all the profiles // 2. for each pair of these profiles: // check that: // point P(x,y,z,head,pitch,roll) in profile A transformed to profile B coordinates, and then transformed back to profile A coordinates == same point P TEST_CASE("Extrinsics graph - matrices 4x4", "[live]") { rs2::context ctx; auto list = ctx.query_devices(); for (auto&& device : list) { std::cout << "device: " << device.get_info(RS2_CAMERA_INFO_NAME) << std::endl; auto sensors = device.query_sensors(); // getting stream profiles from all sensors std::vector<rs2::stream_profile> profiles; for (auto&& sensor : sensors) { std::vector<rs2::stream_profile> stream_profiles = sensor.get_stream_profiles(); for (auto&& profile : stream_profiles) { profiles.push_back(profile); } } float start_point[3] = { 1.f, 2.f, 3.f }; for (int i = 0; i < profiles.size() - 2; ++i) { for (int j = i + 1; j < profiles.size() - 1; ++j) { rs2_extrinsics extr_i_to_j = profiles[i].get_extrinsics_to(profiles[j]); rs2_extrinsics extr_j_to_i = profiles[j].get_extrinsics_to(profiles[i]); position_and_rotation pr_i_to_j = matrix_4_by_4_from_translation_and_rotation(extr_i_to_j.translation, extr_i_to_j.rotation); position_and_rotation pr_j_to_i = matrix_4_by_4_from_translation_and_rotation(extr_j_to_i.translation, extr_j_to_i.rotation); position_and_rotation product = pr_i_to_j * pr_j_to_i; // checking that product of extrinsics from i to j with extrinsiscs from j to i is identity matrix REQUIRE(product.is_identity()); // checking with API rs2_transform_point_to_point float transformed_point[3]; rs2_transform_point_to_point(transformed_point, &extr_i_to_j, start_point); float end_point[3]; rs2_transform_point_to_point(end_point, &extr_j_to_i, transformed_point); bool res = true; for (int t = 0; t < 3; ++t) { if (fabs(start_point[t] - end_point[t]) > 0.001f) res = false; } // checking that transforming a point with extrinsiscs from i to j and the from j to i // gets back to the initial point REQUIRE(res); // checking that a point and orientation, represented by a 4x4 matrix // is equal to the result of transforming it by the extrinsics // from profile A to B, and then from profile B to A position_and_rotation point_and_orientation; // rotation part with 30 degrees rotation on each axis point_and_orientation.pos_and_rot[0][0] = 0.75f; point_and_orientation.pos_and_rot[0][1] = -0.4330127f; point_and_orientation.pos_and_rot[0][2] = 0.5f; point_and_orientation.pos_and_rot[1][0] = 0.649519f; point_and_orientation.pos_and_rot[1][1] = 0.625f; point_and_orientation.pos_and_rot[1][2] = -0.4330127f; point_and_orientation.pos_and_rot[2][0] = -0.125f; point_and_orientation.pos_and_rot[2][1] = 0.649519f; point_and_orientation.pos_and_rot[2][2] = 0.75f; point_and_orientation.pos_and_rot[3][0] = 0.f; point_and_orientation.pos_and_rot[3][1] = 0.f; point_and_orientation.pos_and_rot[3][2] = 0.f; // translation part point_and_orientation.pos_and_rot[0][3] = 1.f; point_and_orientation.pos_and_rot[1][3] = 2.f; point_and_orientation.pos_and_rot[2][3] = 3.f; point_and_orientation.pos_and_rot[3][3] = 1.f; // applying extrinsics from i to j on point with orientation position_and_rotation retransformed_temp = pr_j_to_i * point_and_orientation; // applying extrinsics from j to i position_and_rotation retransformed = pr_i_to_j * retransformed_temp; // checking that the point and orientation are the same as before the transformations REQUIRE(retransformed.equals(point_and_orientation)); } } } } <commit_msg>correcting test<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Intel Corporation. All Rights Reserved. #include <easylogging++.h> #ifdef BUILD_SHARED_LIBS // With static linkage, ELPP is initialized by librealsense, so doing it here will // create errors. When we're using the shared .so/.dll, the two are separate and we have // to initialize ours if we want to use the APIs! INITIALIZE_EASYLOGGINGPP #endif // Let Catch define its own main() function #define CATCH_CONFIG_MAIN #include "../../catch.h" #include <librealsense2/rs.hpp> #include <librealsense2/rsutil.h> using namespace rs2; // structure of a matrix 4 X 4, representing rotation and translation as following: // pos_and_rot[i][j] is // _ _ // | | | // | rotation | translation | // | (3x3) | (3x1) | // | _________ |____________ | // | 0 | 1 | // |_ (1x3) | (1x1) _| // struct position_and_rotation { double pos_and_rot[4][4]; // rotation tolerance - units are in cosinus of radians const double rotation_tolerance = 0.000001; // translation tolerance - units are in meters const double translation_tolerance = 0.000001; // 0.001mm position_and_rotation operator* (const position_and_rotation& other) { position_and_rotation product; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { product.pos_and_rot[i][j] = 0; for (int k = 0; k < 4; k++) product.pos_and_rot[i][j] += pos_and_rot[i][k] * other.pos_and_rot[k][j]; } } return product; } bool equals(const position_and_rotation& other) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { double tolerance = rotation_tolerance; if (j == 3) tolerance = translation_tolerance; if (fabs(pos_and_rot[i][j] - other.pos_and_rot[i][j]) > tolerance) { std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << (double)pos_and_rot[i][j] << ", tolerance = " << tolerance << std::endl; return false; } } return true; } bool is_identity() { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { double target = 0.0; if (i == j) target = 1.0; double tolerance = rotation_tolerance; if (j == 3) tolerance = translation_tolerance; if (fabs(pos_and_rot[i][j] - target) > tolerance) { std::cout << "i,j = " << i << "," << j << ", pos_and_rot[i][j] = " << (double)pos_and_rot[i][j] << ", target = " << (double)target << ", tolerance = " << tolerance << std::endl; return false; } } return true; } }; // This method takes in consideration that the totation array is given in the order of a column major 3x3 matrix position_and_rotation matrix_4_by_4_from_translation_and_rotation(const float* position, const float* rotation) { position_and_rotation pos_rot; pos_rot.pos_and_rot[0][0] = static_cast<double>(rotation[0]); pos_rot.pos_and_rot[1][0] = static_cast<double>(rotation[1]); pos_rot.pos_and_rot[2][0] = static_cast<double>(rotation[2]); pos_rot.pos_and_rot[0][1] = static_cast<double>(rotation[3]); pos_rot.pos_and_rot[1][1] = static_cast<double>(rotation[4]); pos_rot.pos_and_rot[2][1] = static_cast<double>(rotation[5]); pos_rot.pos_and_rot[0][2] = static_cast<double>(rotation[6]); pos_rot.pos_and_rot[1][2] = static_cast<double>(rotation[7]); pos_rot.pos_and_rot[2][2] = static_cast<double>(rotation[8]); pos_rot.pos_and_rot[3][0] = 0.0; pos_rot.pos_and_rot[3][1] = 0.0; pos_rot.pos_and_rot[3][2] = 0.0; pos_rot.pos_and_rot[0][3] = static_cast<double>(position[0]); pos_rot.pos_and_rot[1][3] = static_cast<double>(position[1]); pos_rot.pos_and_rot[2][3] = static_cast<double>(position[2]); pos_rot.pos_and_rot[3][3] = 1.0; return pos_rot; } // checking the extrinsics graph // steps are: // 1. get all the profiles // 2. for each pair of these profiles: // check that: // point P(x,y,z,head,pitch,roll) in profile A transformed to profile B coordinates, and then transformed back to profile A coordinates == same point P TEST_CASE("Extrinsics graph - matrices 4x4", "[live]") { rs2::context ctx; auto list = ctx.query_devices(); for (auto&& device : list) { std::cout << "device: " << device.get_info(RS2_CAMERA_INFO_NAME) << std::endl; auto sensors = device.query_sensors(); // getting stream profiles from all sensors std::vector<rs2::stream_profile> profiles; for (auto&& sensor : sensors) { std::vector<rs2::stream_profile> stream_profiles = sensor.get_stream_profiles(); for (auto&& profile : stream_profiles) { profiles.push_back(profile); } } float start_point[3] = { 1.f, 2.f, 3.f }; for (int i = 0; i < profiles.size() - 2; ++i) { for (int j = i + 1; j < profiles.size() - 1; ++j) { rs2_extrinsics extr_i_to_j = profiles[i].get_extrinsics_to(profiles[j]); rs2_extrinsics extr_j_to_i = profiles[j].get_extrinsics_to(profiles[i]); position_and_rotation pr_i_to_j = matrix_4_by_4_from_translation_and_rotation(extr_i_to_j.translation, extr_i_to_j.rotation); position_and_rotation pr_j_to_i = matrix_4_by_4_from_translation_and_rotation(extr_j_to_i.translation, extr_j_to_i.rotation); position_and_rotation product = pr_i_to_j * pr_j_to_i; // checking that product of extrinsics from i to j with extrinsiscs from j to i is identity matrix REQUIRE(product.is_identity()); // checking with API rs2_transform_point_to_point float transformed_point[3]; rs2_transform_point_to_point(transformed_point, &extr_i_to_j, start_point); float end_point[3]; rs2_transform_point_to_point(end_point, &extr_j_to_i, transformed_point); bool res = true; for (int t = 0; t < 3; ++t) { if (fabs(start_point[t] - end_point[t]) > 0.001f) res = false; } // checking that transforming a point with extrinsiscs from i to j and the from j to i // gets back to the initial point REQUIRE(res); // checking that a point and orientation, represented by a 4x4 matrix // is equal to the result of transforming it by the extrinsics // from profile A to B, and then from profile B to A position_and_rotation point_and_orientation; // rotation part with 30 degrees rotation on each axis point_and_orientation.pos_and_rot[0][0] = 0.75f; point_and_orientation.pos_and_rot[0][1] = -0.4330127f; point_and_orientation.pos_and_rot[0][2] = 0.5f; point_and_orientation.pos_and_rot[1][0] = 0.649519f; point_and_orientation.pos_and_rot[1][1] = 0.625f; point_and_orientation.pos_and_rot[1][2] = -0.4330127f; point_and_orientation.pos_and_rot[2][0] = -0.125f; point_and_orientation.pos_and_rot[2][1] = 0.649519f; point_and_orientation.pos_and_rot[2][2] = 0.75f; point_and_orientation.pos_and_rot[3][0] = 0.f; point_and_orientation.pos_and_rot[3][1] = 0.f; point_and_orientation.pos_and_rot[3][2] = 0.f; // translation part point_and_orientation.pos_and_rot[0][3] = 1.f; point_and_orientation.pos_and_rot[1][3] = 2.f; point_and_orientation.pos_and_rot[2][3] = 3.f; point_and_orientation.pos_and_rot[3][3] = 1.f; // applying extrinsics from i to j on point with orientation position_and_rotation retransformed_temp = pr_j_to_i * point_and_orientation; // applying extrinsics from j to i position_and_rotation retransformed = pr_i_to_j * retransformed_temp; // checking that the point and orientation are the same as before the transformations REQUIRE(retransformed.equals(point_and_orientation)); } } } } <|endoftext|>
<commit_before>#include "ride/quickopendlg.h" #include "ride/wx.h" #include "ride/generated/ui.h" #include <vector> // based on http://docs.wholetomato.com/default.asp?W193 class QuickOpenDlg : public ui::QuickOpen { public: QuickOpenDlg(wxWindow* parent); private: void UpdateFilters(); protected: void OnCancel(wxCommandEvent& event); void OnOk(wxCommandEvent& event); void OnFilterUpdated(wxCommandEvent& event); std::vector<wxString> files_; }; bool MatchFilter(const wxString& filter, const wxString file) { return file.EndsWith(filter); } void QuickOpenDlg::UpdateFilters() { const wxString filter = uiFilterName->GetValue(); uiFileList->Freeze(); uiFileList->DeleteAllItems(); for (const wxString& file : files_) { if (MatchFilter(filter, file)) { int i = uiFileList->InsertItem(0, ""); uiFileList->SetItem(i, 0, wxFileName(file).GetFullName()); uiFileList->SetItem(i, 1, file); } } uiFileList->Thaw(); } QuickOpenDlg::QuickOpenDlg(wxWindow* parent) : ui::QuickOpen(parent, wxID_ANY) { const long file_index = uiFileList->InsertColumn(0, "File"); const long path_index = uiFileList->InsertColumn(1, "Path"); uiFileList->SetColumnWidth(file_index, 100); uiFileList->SetColumnWidth(path_index, 200); files_.push_back("/project/dog/src/BigCalendarCtrl.rs"); files_.push_back("/project/dog/src/BigCalendarTask.rs"); files_.push_back("/project/dog/src/CalendarButtonsDlg.rs"); files_.push_back("/project/dog/src/CalendarData.rs"); files_.push_back("/project/dog/src/CalendarDefines.rs"); files_.push_back("/project/dog/src/CalendarExt.rs"); files_.push_back("/project/dog/src/CalendarExt.rs"); /*files_.push_back("/project/dog/src/big-calendar-ctrl.rs"); files_.push_back("/project/dog/src/big-calendar-task.rs"); files_.push_back("/project/dog/src/calendar-buttons-dlg.rs"); files_.push_back("/project/dog/src/calendar-data.rs"); files_.push_back("/project/dog/src/calendar-defines.rs"); files_.push_back("/project/dog/src/calendar-ext.rs"); files_.push_back("/project/dog/src/calendar-ext.rs"); files_.push_back("/project/dog/src/big_calendar_ctrl.rs"); files_.push_back("/project/dog/src/big_calendar_task.rs"); files_.push_back("/project/dog/src/calendar_buttons_dlg.rs"); files_.push_back("/project/dog/src/calendar_data.rs"); files_.push_back("/project/dog/src/calendar_defines.rs"); files_.push_back("/project/dog/src/calendar_ext.rs"); files_.push_back("/project/dog/src/calendar_ext.rs");*/ UpdateFilters(); } void QuickOpenDlg::OnFilterUpdated(wxCommandEvent& event) { UpdateFilters(); } void QuickOpenDlg::OnCancel(wxCommandEvent& event) { EndModal(wxID_OK); } void QuickOpenDlg::OnOk(wxCommandEvent& event) { EndModal(wxID_CANCEL); } bool ShowQuickOpenDlg(wxWindow* parent) { QuickOpenDlg dlg(parent); if (wxID_OK != dlg.ShowModal()) return false;; // do something! return true; } <commit_msg>started on matching<commit_after>#include "ride/quickopendlg.h" #include "ride/wx.h" #include "ride/generated/ui.h" #include "ride/wxutils.h" #include <vector> // based on http://docs.wholetomato.com/default.asp?W193 class QuickOpenDlg : public ui::QuickOpen { public: QuickOpenDlg(wxWindow* parent); private: void UpdateFilters(); protected: void OnCancel(wxCommandEvent& event); void OnOk(wxCommandEvent& event); void OnFilterUpdated(wxCommandEvent& event); std::vector<wxString> files_; }; void add_if_more_than_one(std::vector<wxString>& ret, const std::vector<wxString>& space) { if (space.size() != 1) { ret.insert(ret.begin(), space.begin(), space.end()); } } std::vector<wxString> SmartSplit(const wxString str) { const auto space = Split(str, ' '); const auto dash = Split(str, '-'); const auto under = Split(str, '_'); std::vector<wxString> ret; ret.push_back(str); add_if_more_than_one(ret, space); add_if_more_than_one(ret, dash); add_if_more_than_one(ret, under); return ret; } bool MatchFilter(const wxString& filter, const wxString file, int* count) { const wxFileName name(file); const auto filters = Split(filter, ' '); const auto bn = SmartSplit(name.GetFullName()); if (filters.empty()) return true; for (auto f : filters) { for (auto b : bn) { if (b.StartsWith(f)) { *count += 1; } } } return *count > 0; } void QuickOpenDlg::UpdateFilters() { const wxString filter = uiFilterName->GetValue(); uiFileList->Freeze(); uiFileList->DeleteAllItems(); for (const wxString& file : files_) { int count = 0; if (MatchFilter(filter, file, &count)) { int i = uiFileList->InsertItem(0, ""); uiFileList->SetItem(i, 0, wxFileName(file).GetFullName()); uiFileList->SetItem(i, 1, file); uiFileList->SetItem(i, 2, wxString::Format("%d", count)); } } uiFileList->Thaw(); } QuickOpenDlg::QuickOpenDlg(wxWindow* parent) : ui::QuickOpen(parent, wxID_ANY) { const long file_index = uiFileList->InsertColumn(0, "File"); const long path_index = uiFileList->InsertColumn(1, "Path"); const long count_index = uiFileList->InsertColumn(2, "Hits"); uiFileList->SetColumnWidth(file_index, 150); uiFileList->SetColumnWidth(path_index, 300); uiFileList->SetColumnWidth(count_index, 50); /*files_.push_back("/project/dog/src/BigCalendarCtrl.rs"); files_.push_back("/project/dog/src/BigCalendarTask.rs"); files_.push_back("/project/dog/src/CalendarButtonsDlg.rs"); files_.push_back("/project/dog/src/CalendarData.rs"); files_.push_back("/project/dog/src/CalendarDefines.rs"); files_.push_back("/project/dog/src/CalendarExt.rs"); files_.push_back("/project/dog/src/CalendarExt.rs"); */ files_.push_back("/project/dog/src/big-calendar-ctrl.rs"); files_.push_back("/project/dog/src/big-calendar-task.rs"); files_.push_back("/project/dog/src/calendar-buttons-dlg.rs"); files_.push_back("/project/dog/src/calendar-data.rs"); files_.push_back("/project/dog/src/calendar-defines.rs"); files_.push_back("/project/dog/src/calendar-ext.rs"); files_.push_back("/project/dog/src/calendar-ext.rs"); /* files_.push_back("/project/dog/src/big_calendar_ctrl.rs"); files_.push_back("/project/dog/src/big_calendar_task.rs"); files_.push_back("/project/dog/src/calendar_buttons_dlg.rs"); files_.push_back("/project/dog/src/calendar_data.rs"); files_.push_back("/project/dog/src/calendar_defines.rs"); files_.push_back("/project/dog/src/calendar_ext.rs"); files_.push_back("/project/dog/src/calendar_ext.rs");*/ UpdateFilters(); } void QuickOpenDlg::OnFilterUpdated(wxCommandEvent& event) { UpdateFilters(); } void QuickOpenDlg::OnCancel(wxCommandEvent& event) { EndModal(wxID_OK); } void QuickOpenDlg::OnOk(wxCommandEvent& event) { EndModal(wxID_CANCEL); } bool ShowQuickOpenDlg(wxWindow* parent) { QuickOpenDlg dlg(parent); if (wxID_OK != dlg.ShowModal()) return false;; // do something! return true; } <|endoftext|>
<commit_before>#include "number.h" using namespace qReal; Number::Number(QVariant n, Type t): mNumber(n), mType(t) { } Number::Number() : mType(Number::intType), mNumber(0) { } Number::~Number() { } QVariant Number::property(QString name) { if (name.compare("Number") == 0) { return mNumber; } else if (name.compare("Type") == 0) { return mType; } return QVariant(); } void Number::setProperty(QString name, QVariant value) { if (name.compare("Number") == 0) { mNumber = value; } else if (name.compare("Type") == 0) { mType = value.toInt() ? Number::intType : Number::doubleType; } } void Number::operator+=(Number add) { Number::Type type = add.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = add.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() + val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() + val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() + val.toDouble(); } } void Number::operator-=(Number sub) { Number::Type type = sub.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = sub.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() - val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() - val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() - val.toDouble(); } } void Number::operator*=(Number mult) { Number::Type type = mult.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = mult.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() * val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() * val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() * val.toDouble(); } } void Number::operator/=(Number div) { Number::Type type = div.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = div.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() / val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() / val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() / val.toDouble(); } } Number Number::operator-() { switch (mType) { case Number::intType: mNumber = -mNumber.toInt(); break; case Number::doubleType: mNumber = -mNumber.toDouble(); break; } return *this; } bool Number::operator<(Number arg) { Number::Type type = arg.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = arg.property("Number"); if (mType == Number::intType && type == Number::intType) { return mNumber.toInt() < val.toInt(); } else if (mType == Number::intType && type == Number::doubleType) { return mNumber.toInt() < val.toDouble(); } else if (mType == Number::doubleType && type == Number::intType) { return mNumber.toDouble() < val.toInt(); } else { return mNumber.toDouble() < val.toDouble(); } } bool Number::operator==(Number arg) { Number::Type type = arg.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = arg.property("Number"); if (mType == Number::intType && type == Number::intType) { return mNumber.toInt() == val.toInt(); } else if (mType == Number::intType && type == Number::doubleType) { return mNumber.toInt() == val.toDouble(); } else if (mType == Number::doubleType && type == Number::intType) { return mNumber.toDouble() == val.toInt(); } else { return mNumber.toDouble() == val.toDouble(); } } bool Number::operator>(Number arg) { return !((*this) < arg || (*this) == arg); } bool Number::operator<=(Number arg) { return (*this) < arg || (*this) == arg; } bool Number::operator>=(Number arg) { return !((*this) < arg); } bool Number::operator!=(Number arg) { return !((*this) == arg); } <commit_msg>fixing the build -- changed fields initialization order<commit_after>#include "number.h" using namespace qReal; Number::Number(QVariant n, Type t): mNumber(n), mType(t) { } Number::Number() : mNumber(0), mType(Number::intType) { } Number::~Number() { } QVariant Number::property(QString name) { if (name.compare("Number") == 0) { return mNumber; } else if (name.compare("Type") == 0) { return mType; } return QVariant(); } void Number::setProperty(QString name, QVariant value) { if (name.compare("Number") == 0) { mNumber = value; } else if (name.compare("Type") == 0) { mType = value.toInt() ? Number::intType : Number::doubleType; } } void Number::operator+=(Number add) { Number::Type type = add.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = add.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() + val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() + val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() + val.toDouble(); } } void Number::operator-=(Number sub) { Number::Type type = sub.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = sub.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() - val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() - val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() - val.toDouble(); } } void Number::operator*=(Number mult) { Number::Type type = mult.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = mult.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() * val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() * val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() * val.toDouble(); } } void Number::operator/=(Number div) { Number::Type type = div.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = div.property("Number"); if (mType == type) { switch (type) { case Number::intType: mNumber = mNumber.toInt() / val.toInt(); break; case Number::doubleType: mNumber = mNumber.toDouble() / val.toDouble(); break; } } else { mType = Number::doubleType; mNumber = mNumber.toDouble() / val.toDouble(); } } Number Number::operator-() { switch (mType) { case Number::intType: mNumber = -mNumber.toInt(); break; case Number::doubleType: mNumber = -mNumber.toDouble(); break; } return *this; } bool Number::operator<(Number arg) { Number::Type type = arg.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = arg.property("Number"); if (mType == Number::intType && type == Number::intType) { return mNumber.toInt() < val.toInt(); } else if (mType == Number::intType && type == Number::doubleType) { return mNumber.toInt() < val.toDouble(); } else if (mType == Number::doubleType && type == Number::intType) { return mNumber.toDouble() < val.toInt(); } else { return mNumber.toDouble() < val.toDouble(); } } bool Number::operator==(Number arg) { Number::Type type = arg.property("Type").toInt() ? Number::intType : Number::doubleType; QVariant val = arg.property("Number"); if (mType == Number::intType && type == Number::intType) { return mNumber.toInt() == val.toInt(); } else if (mType == Number::intType && type == Number::doubleType) { return mNumber.toInt() == val.toDouble(); } else if (mType == Number::doubleType && type == Number::intType) { return mNumber.toDouble() == val.toInt(); } else { return mNumber.toDouble() == val.toDouble(); } } bool Number::operator>(Number arg) { return !((*this) < arg || (*this) == arg); } bool Number::operator<=(Number arg) { return (*this) < arg || (*this) == arg; } bool Number::operator>=(Number arg) { return !((*this) < arg); } bool Number::operator!=(Number arg) { return !((*this) == arg); } <|endoftext|>
<commit_before>/* * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "gc_implementation/parallelScavenge/generationSizer.hpp" #include "memory/collectorPolicy.hpp" void GenerationSizer::trace_gen_sizes(const char* const str) { if (TracePageSizes) { tty->print_cr("%s: " SIZE_FORMAT "," SIZE_FORMAT " " SIZE_FORMAT "," SIZE_FORMAT " " SIZE_FORMAT, str, _min_gen1_size / K, _max_gen1_size / K, _min_gen0_size / K, _max_gen0_size / K, _max_heap_byte_size / K); } } void GenerationSizer::initialize_alignments() { _space_alignment = _gen_alignment = default_gen_alignment(); _heap_alignment = compute_heap_alignment(); } void GenerationSizer::initialize_flags() { // Do basic sizing work TwoGenerationCollectorPolicy::initialize_flags(); assert(UseSerialGC || !FLAG_IS_DEFAULT(ParallelGCThreads) || (ParallelGCThreads > 0), "ParallelGCThreads should be set before flag initialization"); // The survivor ratio's are calculated "raw", unlike the // default gc, which adds 2 to the ratio value. We need to // make sure the values are valid before using them. if (MinSurvivorRatio < 3) { FLAG_SET_ERGO(uintx, MinSurvivorRatio, 3); } if (InitialSurvivorRatio < 3) { FLAG_SET_ERGO(uintx, InitialSurvivorRatio, 3); } } void GenerationSizer::initialize_size_info() { trace_gen_sizes("ps heap raw"); const size_t page_sz = os::page_size_for_region(_min_heap_byte_size, _max_heap_byte_size, 8); // Can a page size be something else than a power of two? assert(is_power_of_2((intptr_t)page_sz), "must be a power of 2"); size_t new_alignment = round_to(page_sz, _gen_alignment); if (new_alignment != _gen_alignment) { _gen_alignment = new_alignment; // Redo everything from the start initialize_flags(); } TwoGenerationCollectorPolicy::initialize_size_info(); trace_gen_sizes("ps heap rnd"); } <commit_msg>8027960: Assertion assert(end >= start) failed during nightly testing on solaris Summary: Needed to update _space_alignment in generation sizer to ensure correct sizing of spaces. Reviewed-by: jmasa, tschatzl<commit_after>/* * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "gc_implementation/parallelScavenge/generationSizer.hpp" #include "memory/collectorPolicy.hpp" void GenerationSizer::trace_gen_sizes(const char* const str) { if (TracePageSizes) { tty->print_cr("%s: " SIZE_FORMAT "," SIZE_FORMAT " " SIZE_FORMAT "," SIZE_FORMAT " " SIZE_FORMAT, str, _min_gen1_size / K, _max_gen1_size / K, _min_gen0_size / K, _max_gen0_size / K, _max_heap_byte_size / K); } } void GenerationSizer::initialize_alignments() { _space_alignment = _gen_alignment = default_gen_alignment(); _heap_alignment = compute_heap_alignment(); } void GenerationSizer::initialize_flags() { // Do basic sizing work TwoGenerationCollectorPolicy::initialize_flags(); assert(UseSerialGC || !FLAG_IS_DEFAULT(ParallelGCThreads) || (ParallelGCThreads > 0), "ParallelGCThreads should be set before flag initialization"); // The survivor ratio's are calculated "raw", unlike the // default gc, which adds 2 to the ratio value. We need to // make sure the values are valid before using them. if (MinSurvivorRatio < 3) { FLAG_SET_ERGO(uintx, MinSurvivorRatio, 3); } if (InitialSurvivorRatio < 3) { FLAG_SET_ERGO(uintx, InitialSurvivorRatio, 3); } } void GenerationSizer::initialize_size_info() { trace_gen_sizes("ps heap raw"); const size_t page_sz = os::page_size_for_region(_min_heap_byte_size, _max_heap_byte_size, 8); // Can a page size be something else than a power of two? assert(is_power_of_2((intptr_t)page_sz), "must be a power of 2"); size_t new_alignment = round_to(page_sz, _gen_alignment); if (new_alignment != _gen_alignment) { _gen_alignment = new_alignment; _space_alignment = new_alignment; // Redo everything from the start initialize_flags(); } TwoGenerationCollectorPolicy::initialize_size_info(); trace_gen_sizes("ps heap rnd"); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreViewport.h" #include "OgreLogManager.h" #include "OgreRenderTarget.h" #include "OgreCamera.h" #include "OgreMath.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" #include "OgreRenderSystem.h" #include "OgreRenderWindow.h" namespace Ogre { OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0; //--------------------------------------------------------------------- Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder) : mCamera(cam) , mTarget(target) , mRelLeft(left) , mRelTop(top) , mRelWidth(width) , mRelHeight(height) // Actual dimensions will update later , mZOrder(ZOrder) , mBackColour(ColourValue::Black) , mClearEveryFrame(true) , mClearBuffers(FBT_COLOUR | FBT_DEPTH) , mUpdated(false) , mShowOverlays(true) , mShowSkies(true) , mShowShadows(true) , mVisibilityMask(0xFFFFFFFF) , mRQSequence(0) , mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME) , mIsAutoUpdated(true) { #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Creating viewport on target '" << target->getName() << "'" << ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'" << ", relative dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << left << " T: " << top << " W: " << width << " H: " << height << " ZOrder: " << ZOrder; #endif // Set the default orientation mode mOrientationMode = mDefaultOrientationMode; // Calculate actual dimensions _updateDimensions(); // notify camera if(cam) cam->_notifyViewport(this); } //--------------------------------------------------------------------- Viewport::~Viewport() { } //--------------------------------------------------------------------- bool Viewport::_isUpdated(void) const { return mUpdated; } //--------------------------------------------------------------------- void Viewport::_clearUpdatedFlag(void) { mUpdated = false; } //--------------------------------------------------------------------- void Viewport::_updateDimensions(void) { Real height = (Real) mTarget->getHeight(); Real width = (Real) mTarget->getWidth(); mActLeft = (int) (mRelLeft * width); mActTop = (int) (mRelTop * height); mActWidth = (int) (mRelWidth * width); mActHeight = (int) (mRelHeight * height); // This will check if the cameras getAutoAspectRatio() property is set. // If it's true its aspect ratio is fit to the current viewport // If it's false the camera remains unchanged. // This allows cameras to be used to render to many viewports, // which can have their own dimensions and aspect ratios. if (mCamera) { if (mCamera->getAutoAspectRatio()) mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight); #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 mCamera->setOrientationMode(mOrientationMode); #endif } #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'" << ", actual dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight; #endif mUpdated = true; } //--------------------------------------------------------------------- int Viewport::getZOrder(void) const { return mZOrder; } //--------------------------------------------------------------------- RenderTarget* Viewport::getTarget(void) const { return mTarget; } //--------------------------------------------------------------------- Camera* Viewport::getCamera(void) const { return mCamera; } //--------------------------------------------------------------------- Real Viewport::getLeft(void) const { return mRelLeft; } //--------------------------------------------------------------------- Real Viewport::getTop(void) const { return mRelTop; } //--------------------------------------------------------------------- Real Viewport::getWidth(void) const { return mRelWidth; } //--------------------------------------------------------------------- Real Viewport::getHeight(void) const { return mRelHeight; } //--------------------------------------------------------------------- int Viewport::getActualLeft(void) const { return mActLeft; } //--------------------------------------------------------------------- int Viewport::getActualTop(void) const { return mActTop; } //--------------------------------------------------------------------- int Viewport::getActualWidth(void) const { return mActWidth; } //--------------------------------------------------------------------- int Viewport::getActualHeight(void) const { return mActHeight; } //--------------------------------------------------------------------- void Viewport::setDimensions(Real left, Real top, Real width, Real height) { mRelLeft = left; mRelTop = top; mRelWidth = width; mRelHeight = height; _updateDimensions(); } //--------------------------------------------------------------------- void Viewport::update(void) { if (mCamera) { // Tell Camera to render into me mCamera->_renderScene(this, mShowOverlays); } } //--------------------------------------------------------------------- void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting Viewport orientation mode is not supported", __FUNCTION__); #endif mOrientationMode = orientationMode; if (setDefault) { setDefaultOrientationMode(orientationMode); } if (mCamera) { mCamera->setOrientationMode(mOrientationMode); } // Update the render system config RenderSystem* rs = Root::getSingleton().getRenderSystem(); if(mOrientationMode == OR_LANDSCAPELEFT) rs->setConfigOption("Orientation", "Landscape Left"); else if(mOrientationMode == OR_LANDSCAPERIGHT) rs->setConfigOption("Orientation", "Landscape Right"); else if(mOrientationMode == OR_PORTRAIT) rs->setConfigOption("Orientation", "Portrait"); } //--------------------------------------------------------------------- OrientationMode Viewport::getOrientationMode() const { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting Viewport orientation mode is not supported", __FUNCTION__); #endif return mOrientationMode; } //--------------------------------------------------------------------- void Viewport::setDefaultOrientationMode(OrientationMode orientationMode) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting default Viewport orientation mode is not supported", __FUNCTION__); #endif mDefaultOrientationMode = orientationMode; } //--------------------------------------------------------------------- OrientationMode Viewport::getDefaultOrientationMode() { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting default Viewport orientation mode is not supported", __FUNCTION__); #endif return mDefaultOrientationMode; } //--------------------------------------------------------------------- void Viewport::setBackgroundColour(const ColourValue& colour) { mBackColour = colour; } //--------------------------------------------------------------------- const ColourValue& Viewport::getBackgroundColour(void) const { return mBackColour; } //--------------------------------------------------------------------- void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers) { mClearEveryFrame = inClear; mClearBuffers = inBuffers; } //--------------------------------------------------------------------- bool Viewport::getClearEveryFrame(void) const { return mClearEveryFrame; } //--------------------------------------------------------------------- unsigned int Viewport::getClearBuffers(void) const { return mClearBuffers; } //--------------------------------------------------------------------- void Viewport::clear(unsigned int buffers, const ColourValue& col, Real depth, unsigned short stencil) { RenderSystem* rs = Root::getSingleton().getRenderSystem(); if (rs) { Viewport* currentvp = rs->_getViewport(); rs->_setViewport(this); rs->clearFrameBuffer(buffers, col, depth, stencil); if (currentvp && currentvp != this) rs->_setViewport(currentvp); } } //--------------------------------------------------------------------- void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const { left = mActLeft; top = mActTop; width = mActWidth; height = mActHeight; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedFaces(void) const { return mCamera ? mCamera->_getNumRenderedFaces() : 0; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedBatches(void) const { return mCamera ? mCamera->_getNumRenderedBatches() : 0; } //--------------------------------------------------------------------- void Viewport::setCamera(Camera* cam) { if(mCamera) { if(mCamera->getViewport() == this) { mCamera->_notifyViewport(0); } } mCamera = cam; _updateDimensions(); if(cam) mCamera->_notifyViewport(this); } //--------------------------------------------------------------------- void Viewport::setAutoUpdated(bool inAutoUpdated) { mIsAutoUpdated = inAutoUpdated; } //--------------------------------------------------------------------- bool Viewport::isAutoUpdated() const { return mIsAutoUpdated; } //--------------------------------------------------------------------- void Viewport::setOverlaysEnabled(bool enabled) { mShowOverlays = enabled; } //--------------------------------------------------------------------- bool Viewport::getOverlaysEnabled(void) const { return mShowOverlays; } //--------------------------------------------------------------------- void Viewport::setSkiesEnabled(bool enabled) { mShowSkies = enabled; } //--------------------------------------------------------------------- bool Viewport::getSkiesEnabled(void) const { return mShowSkies; } //--------------------------------------------------------------------- void Viewport::setShadowsEnabled(bool enabled) { mShowShadows = enabled; } //--------------------------------------------------------------------- bool Viewport::getShadowsEnabled(void) const { return mShowShadows; } //----------------------------------------------------------------------- void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName) { mRQSequenceName = sequenceName; if (mRQSequenceName.empty()) { mRQSequence = 0; } else { mRQSequence = Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName); } } //----------------------------------------------------------------------- const String& Viewport::getRenderQueueInvocationSequenceName(void) const { return mRQSequenceName; } //----------------------------------------------------------------------- RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void) { return mRQSequence; } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv) { pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y); } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode, Real &screenX, Real &screenY) { Real orX = orientedX; Real orY = orientedY; switch (orientationMode) { case 1: screenX = orY; screenY = Real(1.0) - orX; break; case 2: screenX = Real(1.0) - orX; screenY = Real(1.0) - orY; break; case 3: screenX = Real(1.0) - orY; screenY = orX; break; default: screenX = orX; screenY = orY; break; } } //----------------------------------------------------------------------- } <commit_msg>Bug 340 - Viewport::clear() saves and re-sets the previous Viewport, even if that Viewport has since been deleted<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreViewport.h" #include "OgreLogManager.h" #include "OgreRenderTarget.h" #include "OgreCamera.h" #include "OgreMath.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" #include "OgreRenderSystem.h" #include "OgreRenderWindow.h" namespace Ogre { OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0; //--------------------------------------------------------------------- Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder) : mCamera(cam) , mTarget(target) , mRelLeft(left) , mRelTop(top) , mRelWidth(width) , mRelHeight(height) // Actual dimensions will update later , mZOrder(ZOrder) , mBackColour(ColourValue::Black) , mClearEveryFrame(true) , mClearBuffers(FBT_COLOUR | FBT_DEPTH) , mUpdated(false) , mShowOverlays(true) , mShowSkies(true) , mShowShadows(true) , mVisibilityMask(0xFFFFFFFF) , mRQSequence(0) , mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME) , mIsAutoUpdated(true) { #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Creating viewport on target '" << target->getName() << "'" << ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'" << ", relative dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << left << " T: " << top << " W: " << width << " H: " << height << " ZOrder: " << ZOrder; #endif // Set the default orientation mode mOrientationMode = mDefaultOrientationMode; // Calculate actual dimensions _updateDimensions(); // notify camera if(cam) cam->_notifyViewport(this); } //--------------------------------------------------------------------- Viewport::~Viewport() { } //--------------------------------------------------------------------- bool Viewport::_isUpdated(void) const { return mUpdated; } //--------------------------------------------------------------------- void Viewport::_clearUpdatedFlag(void) { mUpdated = false; } //--------------------------------------------------------------------- void Viewport::_updateDimensions(void) { Real height = (Real) mTarget->getHeight(); Real width = (Real) mTarget->getWidth(); mActLeft = (int) (mRelLeft * width); mActTop = (int) (mRelTop * height); mActWidth = (int) (mRelWidth * width); mActHeight = (int) (mRelHeight * height); // This will check if the cameras getAutoAspectRatio() property is set. // If it's true its aspect ratio is fit to the current viewport // If it's false the camera remains unchanged. // This allows cameras to be used to render to many viewports, // which can have their own dimensions and aspect ratios. if (mCamera) { if (mCamera->getAutoAspectRatio()) mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight); #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 mCamera->setOrientationMode(mOrientationMode); #endif } #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'" << ", actual dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight; #endif mUpdated = true; } //--------------------------------------------------------------------- int Viewport::getZOrder(void) const { return mZOrder; } //--------------------------------------------------------------------- RenderTarget* Viewport::getTarget(void) const { return mTarget; } //--------------------------------------------------------------------- Camera* Viewport::getCamera(void) const { return mCamera; } //--------------------------------------------------------------------- Real Viewport::getLeft(void) const { return mRelLeft; } //--------------------------------------------------------------------- Real Viewport::getTop(void) const { return mRelTop; } //--------------------------------------------------------------------- Real Viewport::getWidth(void) const { return mRelWidth; } //--------------------------------------------------------------------- Real Viewport::getHeight(void) const { return mRelHeight; } //--------------------------------------------------------------------- int Viewport::getActualLeft(void) const { return mActLeft; } //--------------------------------------------------------------------- int Viewport::getActualTop(void) const { return mActTop; } //--------------------------------------------------------------------- int Viewport::getActualWidth(void) const { return mActWidth; } //--------------------------------------------------------------------- int Viewport::getActualHeight(void) const { return mActHeight; } //--------------------------------------------------------------------- void Viewport::setDimensions(Real left, Real top, Real width, Real height) { mRelLeft = left; mRelTop = top; mRelWidth = width; mRelHeight = height; _updateDimensions(); } //--------------------------------------------------------------------- void Viewport::update(void) { if (mCamera) { // Tell Camera to render into me mCamera->_renderScene(this, mShowOverlays); } } //--------------------------------------------------------------------- void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting Viewport orientation mode is not supported", __FUNCTION__); #endif mOrientationMode = orientationMode; if (setDefault) { setDefaultOrientationMode(orientationMode); } if (mCamera) { mCamera->setOrientationMode(mOrientationMode); } // Update the render system config RenderSystem* rs = Root::getSingleton().getRenderSystem(); if(mOrientationMode == OR_LANDSCAPELEFT) rs->setConfigOption("Orientation", "Landscape Left"); else if(mOrientationMode == OR_LANDSCAPERIGHT) rs->setConfigOption("Orientation", "Landscape Right"); else if(mOrientationMode == OR_PORTRAIT) rs->setConfigOption("Orientation", "Portrait"); } //--------------------------------------------------------------------- OrientationMode Viewport::getOrientationMode() const { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting Viewport orientation mode is not supported", __FUNCTION__); #endif return mOrientationMode; } //--------------------------------------------------------------------- void Viewport::setDefaultOrientationMode(OrientationMode orientationMode) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting default Viewport orientation mode is not supported", __FUNCTION__); #endif mDefaultOrientationMode = orientationMode; } //--------------------------------------------------------------------- OrientationMode Viewport::getDefaultOrientationMode() { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting default Viewport orientation mode is not supported", __FUNCTION__); #endif return mDefaultOrientationMode; } //--------------------------------------------------------------------- void Viewport::setBackgroundColour(const ColourValue& colour) { mBackColour = colour; } //--------------------------------------------------------------------- const ColourValue& Viewport::getBackgroundColour(void) const { return mBackColour; } //--------------------------------------------------------------------- void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers) { mClearEveryFrame = inClear; mClearBuffers = inBuffers; } //--------------------------------------------------------------------- bool Viewport::getClearEveryFrame(void) const { return mClearEveryFrame; } //--------------------------------------------------------------------- unsigned int Viewport::getClearBuffers(void) const { return mClearBuffers; } //--------------------------------------------------------------------- void Viewport::clear(unsigned int buffers, const ColourValue& col, Real depth, unsigned short stencil) { RenderSystem* rs = Root::getSingleton().getRenderSystem(); if (rs) { Viewport* currentvp = rs->_getViewport(); if (currentvp && currentvp == this) rs->clearFrameBuffer(buffers, col, depth, stencil); else if (currentvp) { rs->_setViewport(this); rs->clearFrameBuffer(buffers, col, depth, stencil); rs->_setViewport(currentvp); } } } //--------------------------------------------------------------------- void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const { left = mActLeft; top = mActTop; width = mActWidth; height = mActHeight; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedFaces(void) const { return mCamera ? mCamera->_getNumRenderedFaces() : 0; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedBatches(void) const { return mCamera ? mCamera->_getNumRenderedBatches() : 0; } //--------------------------------------------------------------------- void Viewport::setCamera(Camera* cam) { if(mCamera) { if(mCamera->getViewport() == this) { mCamera->_notifyViewport(0); } } mCamera = cam; _updateDimensions(); if(cam) mCamera->_notifyViewport(this); } //--------------------------------------------------------------------- void Viewport::setAutoUpdated(bool inAutoUpdated) { mIsAutoUpdated = inAutoUpdated; } //--------------------------------------------------------------------- bool Viewport::isAutoUpdated() const { return mIsAutoUpdated; } //--------------------------------------------------------------------- void Viewport::setOverlaysEnabled(bool enabled) { mShowOverlays = enabled; } //--------------------------------------------------------------------- bool Viewport::getOverlaysEnabled(void) const { return mShowOverlays; } //--------------------------------------------------------------------- void Viewport::setSkiesEnabled(bool enabled) { mShowSkies = enabled; } //--------------------------------------------------------------------- bool Viewport::getSkiesEnabled(void) const { return mShowSkies; } //--------------------------------------------------------------------- void Viewport::setShadowsEnabled(bool enabled) { mShowShadows = enabled; } //--------------------------------------------------------------------- bool Viewport::getShadowsEnabled(void) const { return mShowShadows; } //----------------------------------------------------------------------- void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName) { mRQSequenceName = sequenceName; if (mRQSequenceName.empty()) { mRQSequence = 0; } else { mRQSequence = Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName); } } //----------------------------------------------------------------------- const String& Viewport::getRenderQueueInvocationSequenceName(void) const { return mRQSequenceName; } //----------------------------------------------------------------------- RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void) { return mRQSequence; } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv) { pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y); } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode, Real &screenX, Real &screenY) { Real orX = orientedX; Real orY = orientedY; switch (orientationMode) { case 1: screenX = orY; screenY = Real(1.0) - orX; break; case 2: screenX = Real(1.0) - orX; screenY = Real(1.0) - orY; break; case 3: screenX = Real(1.0) - orY; screenY = orX; break; default: screenX = orX; screenY = orY; break; } } //----------------------------------------------------------------------- } <|endoftext|>
<commit_before>/* Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Example main() function for Brotli library. */ #include <fcntl.h> #include <stdio.h> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "../dec/decode.h" #include "../enc/encode.h" #include "../enc/streams.h" static bool ParseQuality(const char* s, int* quality) { if (s[0] >= '0' && s[0] <= '9') { *quality = s[0] - '0'; if (s[1] >= '0' && s[1] <= '9') { *quality = *quality * 10 + s[1] - '0'; return s[2] == 0; } return s[1] == 0; } return false; } static void ParseArgv(int argc, char **argv, char **input_path, char **output_path, int *force, int *quality, int *decompress) { *force = 0; *input_path = 0; *output_path = 0; { size_t argv0_len = strlen(argv[0]); *decompress = argv0_len >= 5 && strcmp(&argv[0][argv0_len - 5], "unbro") == 0; } for (int k = 1; k < argc; ++k) { if (!strcmp("--force", argv[k]) || !strcmp("-f", argv[k])) { if (*force != 0) { goto error; } *force = 1; continue; } else if (!strcmp("--decompress", argv[k]) || !strcmp("--uncompress", argv[k]) || !strcmp("-d", argv[k])) { *decompress = 1; continue; } if (k < argc - 1) { if (!strcmp("--input", argv[k]) || !strcmp("--in", argv[k]) || !strcmp("-i", argv[k])) { if (*input_path != 0) { goto error; } *input_path = argv[k + 1]; ++k; continue; } else if (!strcmp("--output", argv[k]) || !strcmp("--out", argv[k]) || !strcmp("-o", argv[k])) { if (*output_path != 0) { goto error; } *output_path = argv[k + 1]; ++k; continue; } else if (!strcmp("--quality", argv[k]) || !strcmp("-q", argv[k])) { if (!ParseQuality(argv[k + 1], quality)) { goto error; } ++k; continue; } } goto error; } return; error: fprintf(stderr, "Usage: %s [--force] [--quality n] [--decompress]" " [--input filename] [--output filename]\n", argv[0]); exit(1); } static FILE* OpenInputFile(const char* input_path) { if (input_path == 0) { return fdopen(STDIN_FILENO, "rb"); } FILE* f = fopen(input_path, "rb"); if (f == 0) { perror("fopen"); exit(1); } return f; } static FILE *OpenOutputFile(const char *output_path, const int force) { if (output_path == 0) { return fdopen(STDOUT_FILENO, "wb"); } if (!force) { struct stat statbuf; if (stat(output_path, &statbuf) == 0) { fprintf(stderr, "output file exists\n"); exit(1); } } int fd = open(output_path, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { perror("open"); exit(1); } return fdopen(fd, "wb"); } int main(int argc, char** argv) { char *input_path = 0; char *output_path = 0; int force = 0; int quality = 11; int decompress = 0; ParseArgv(argc, argv, &input_path, &output_path, &force, &quality, &decompress); FILE* fin = OpenInputFile(input_path); FILE* fout = OpenOutputFile(output_path, force); if (decompress) { BrotliInput in = BrotliFileInput(fin); BrotliOutput out = BrotliFileOutput(fout); if (!BrotliDecompress(in, out)) { fprintf(stderr, "corrupt input\n"); exit(1); } } else { brotli::BrotliParams params; params.quality = quality; brotli::BrotliFileIn in(fin, 1 << 16); brotli::BrotliFileOut out(fout); if (!BrotliCompress(params, &in, &out)) { fprintf(stderr, "compression failed\n"); unlink(output_path); exit(1); } } if (fclose(fin) != 0) { perror("fclose"); exit(1); } if (fclose(fout) != 0) { perror("fclose"); exit(1); } return 0; } <commit_msg>Add "repeat" and "verbose" flags to "bro" tool.<commit_after>/* Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Example main() function for Brotli library. */ #include <fcntl.h> #include <stdio.h> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "../dec/decode.h" #include "../enc/encode.h" #include "../enc/streams.h" static bool ParseQuality(const char* s, int* quality) { if (s[0] >= '0' && s[0] <= '9') { *quality = s[0] - '0'; if (s[1] >= '0' && s[1] <= '9') { *quality = *quality * 10 + s[1] - '0'; return s[2] == 0; } return s[1] == 0; } return false; } static void ParseArgv(int argc, char **argv, char **input_path, char **output_path, int *force, int *quality, int *decompress, int *repeat, int *verbose) { *force = 0; *input_path = 0; *output_path = 0; *repeat = 1; *verbose = 0; { size_t argv0_len = strlen(argv[0]); *decompress = argv0_len >= 5 && strcmp(&argv[0][argv0_len - 5], "unbro") == 0; } for (int k = 1; k < argc; ++k) { if (!strcmp("--force", argv[k]) || !strcmp("-f", argv[k])) { if (*force != 0) { goto error; } *force = 1; continue; } else if (!strcmp("--decompress", argv[k]) || !strcmp("--uncompress", argv[k]) || !strcmp("-d", argv[k])) { *decompress = 1; continue; } else if (!strcmp("--verbose", argv[k]) || !strcmp("-v", argv[k])) { if (*verbose != 0) { goto error; } *verbose = 1; continue; } if (k < argc - 1) { if (!strcmp("--input", argv[k]) || !strcmp("--in", argv[k]) || !strcmp("-i", argv[k])) { if (*input_path != 0) { goto error; } *input_path = argv[k + 1]; ++k; continue; } else if (!strcmp("--output", argv[k]) || !strcmp("--out", argv[k]) || !strcmp("-o", argv[k])) { if (*output_path != 0) { goto error; } *output_path = argv[k + 1]; ++k; continue; } else if (!strcmp("--quality", argv[k]) || !strcmp("-q", argv[k])) { if (!ParseQuality(argv[k + 1], quality)) { goto error; } ++k; continue; } else if (!strcmp("--repeat", argv[k]) || !strcmp("-r", argv[k])) { if (!ParseQuality(argv[k + 1], repeat)) { goto error; } ++k; continue; } } goto error; } return; error: fprintf(stderr, "Usage: %s [--force] [--quality n] [--decompress]" " [--input filename] [--output filename] [--repeat iters]" " [--verbose]\n", argv[0]); exit(1); } static FILE* OpenInputFile(const char* input_path) { if (input_path == 0) { return fdopen(STDIN_FILENO, "rb"); } FILE* f = fopen(input_path, "rb"); if (f == 0) { perror("fopen"); exit(1); } return f; } static FILE *OpenOutputFile(const char *output_path, const int force) { if (output_path == 0) { return fdopen(STDOUT_FILENO, "wb"); } if (!force) { struct stat statbuf; if (stat(output_path, &statbuf) == 0) { fprintf(stderr, "output file exists\n"); exit(1); } } int fd = open(output_path, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { perror("open"); exit(1); } return fdopen(fd, "wb"); } int64_t FileSize(char *path) { FILE *f = fopen(path, "rb"); if (f == NULL) { return -1; } fseek(f, 0L, SEEK_END); int64_t retval = ftell(f); fclose(f); return retval; } int main(int argc, char** argv) { char *input_path = 0; char *output_path = 0; int force = 0; int quality = 11; int decompress = 0; int repeat = 1; int verbose = 0; ParseArgv(argc, argv, &input_path, &output_path, &force, &quality, &decompress, &repeat, &verbose); const clock_t clock_start = clock(); for (int i = 0; i < repeat; ++i) { FILE* fin = OpenInputFile(input_path); FILE* fout = OpenOutputFile(output_path, force); if (decompress) { BrotliInput in = BrotliFileInput(fin); BrotliOutput out = BrotliFileOutput(fout); if (!BrotliDecompress(in, out)) { fprintf(stderr, "corrupt input\n"); exit(1); } } else { brotli::BrotliParams params; params.quality = quality; brotli::BrotliFileIn in(fin, 1 << 16); brotli::BrotliFileOut out(fout); if (!BrotliCompress(params, &in, &out)) { fprintf(stderr, "compression failed\n"); unlink(output_path); exit(1); } } if (fclose(fin) != 0) { perror("fclose"); exit(1); } if (fclose(fout) != 0) { perror("fclose"); exit(1); } } if (verbose) { const clock_t clock_end = clock(); double duration = static_cast<double>(clock_end - clock_start) / CLOCKS_PER_SEC; if (duration < 1e-9) { duration = 1e-9; } int64_t uncompressed_bytes = repeat * FileSize(decompress ? output_path : input_path); double uncompressed_bytes_in_MB = uncompressed_bytes / (1024.0 * 1024.0); if (decompress) { printf("Brotli decompression speed: "); } else { printf("Brotli compression speed: "); } printf("%g MB/s\n", uncompressed_bytes_in_MB / duration); } return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "sal/config.h" #include <cstddef> #include <fstream> #include <iterator> #include <string> #include "common.hxx" #include "lngmerge.hxx" namespace { rtl::OString getBracketedContent(rtl::OString text) { return text.getToken(1, '[').getToken(0, ']'); } } // // class LngParser // LngParser::LngParser(const rtl::OString &rLngFile, sal_Bool bULFFormat) : nError( LNG_OK ) , pLines( NULL ) , sSource( rLngFile ) , bULF( bULFFormat ) { pLines = new LngLineList(); std::ifstream aStream(sSource.getStr()); if (aStream.is_open()) { bool bFirstLine = true; while (!aStream.eof()) { std::string s; std::getline(aStream, s); rtl::OString sLine(s.data(), s.length()); if( bFirstLine ) { // Always remove UTF8 BOM from the first line Export::RemoveUTF8ByteOrderMarker( sLine ); bFirstLine = false; } pLines->push_back( new rtl::OString(sLine) ); } } else nError = LNG_COULD_NOT_OPEN; } LngParser::~LngParser() { for ( size_t i = 0, n = pLines->size(); i < n; ++i ) delete (*pLines)[ i ]; pLines->clear(); delete pLines; } sal_Bool LngParser::CreateSDF(const rtl::OString &rSDFFile, const rtl::OString &rPrj, const rtl::OString &rRoot) { Export::InitLanguages( false ); aLanguages = Export::GetLanguages(); std::ofstream aSDFStream( rSDFFile.getStr(), std::ios_base::out | std::ios_base::trunc); if (!aSDFStream.is_open()) { nError = SDF_COULD_NOT_OPEN; } nError = SDF_OK; rtl::OString sActFileName( common::pathnameToken(sSource.getStr(), rRoot.getStr())); size_t nPos = 0; sal_Bool bStart = true; rtl::OString sGroup, sLine; OStringHashMap Text; rtl::OString sID; while( nPos < pLines->size() ) { sLine = *(*pLines)[ nPos++ ]; while( nPos < pLines->size() && !isNextGroup( sGroup , sLine ) ) { ReadLine( sLine , Text ); sID = sGroup; sLine = *(*pLines)[ nPos++ ]; }; if( bStart ) { bStart = false; sID = sGroup; } else { WriteSDF( aSDFStream , Text , rPrj , rRoot , sActFileName , sID ); } } aSDFStream.close(); return true; } void LngParser::WriteSDF(std::ofstream &aSDFStream, OStringHashMap &rText_inout, const rtl::OString &rPrj, const rtl::OString &rRoot, const rtl::OString &rActFileName, const rtl::OString &rID) { sal_Bool bExport = true; if ( bExport ) { rtl::OString sCur; for( unsigned int n = 0; n < aLanguages.size(); n++ ){ sCur = aLanguages[ n ]; rtl::OString sAct = rText_inout[ sCur ]; if ( sAct.isEmpty() && !sCur.isEmpty() ) sAct = rText_inout[ rtl::OString("en-US") ]; rtl::OString sOutput( rPrj ); sOutput += "\t"; if (rRoot.getLength()) sOutput += rActFileName; sOutput += "\t0\t"; sOutput += "LngText\t"; sOutput += rID; sOutput += "\t\t\t\t0\t"; sOutput += sCur; sOutput += "\t"; sOutput += sAct; sOutput += "\t\t\t\t"; aSDFStream << sOutput.getStr() << '\n'; } } } bool LngParser::isNextGroup(rtl::OString &sGroup_out, rtl::OString &sLine_in) { sLine_in = sLine_in.trim(); if ((sLine_in[0] == '[') && (sLine_in[sLine_in.getLength() - 1] == ']')) { sGroup_out = getBracketedContent(sLine_in).trim(); return true; } return false; } void LngParser::ReadLine(const rtl::OString &rLine_in, OStringHashMap &rText_inout) { rtl::OString sLang(rLine_in.getToken(0, '=').trim()); if (!sLang.isEmpty()) { rtl::OString sText(rLine_in.getToken(1, '"')); rText_inout[sLang] = sText; } } sal_Bool LngParser::Merge( const rtl::OString &rSDFFile, const rtl::OString &rDestinationFile) { Export::InitLanguages( true ); std::ofstream aDestination( rDestinationFile.getStr(), std::ios_base::out | std::ios_base::trunc); if (!aDestination.is_open()) { nError = LNG_COULD_NOT_OPEN; } nError = LNG_OK; MergeDataFile aMergeDataFile( rSDFFile, sSource, false ); rtl::OString sTmp( Export::sLanguages ); if( sTmp.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("ALL")) ) Export::SetLanguages( aMergeDataFile.GetLanguages() ); aLanguages = Export::GetLanguages(); size_t nPos = 0; sal_Bool bGroup = sal_False; rtl::OString sGroup; // seek to next group while ( nPos < pLines->size() && !bGroup ) { rtl::OString sLine( *(*pLines)[ nPos ] ); sLine = sLine.trim(); if (( sLine[0] == '[' ) && ( sLine[sLine.getLength() - 1] == ']' )) { sGroup = getBracketedContent(sLine).trim(); bGroup = sal_True; } nPos ++; } while ( nPos < pLines->size()) { OStringHashMap Text; rtl::OString sID( sGroup ); std::size_t nLastLangPos = 0; ResData *pResData = new ResData( "", sID , sSource ); pResData->sResTyp = "LngText"; PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); // read languages bGroup = sal_False; rtl::OString sLanguagesDone; while ( nPos < pLines->size() && !bGroup ) { rtl::OString sLine( *(*pLines)[ nPos ] ); sLine = sLine.trim(); if (( sLine[0] == '[' ) && ( sLine[sLine.getLength() - 1] == ']' )) { sGroup = getBracketedContent(sLine).trim(); bGroup = sal_True; nPos ++; sLanguagesDone = ""; } else { sal_Int32 n = 0; rtl::OString sLang(sLine.getToken(0, '=', n)); if (n == -1) { ++nPos; } else { sLang = sLang.trim(); rtl::OString sSearch( ";" ); sSearch += sLang; sSearch += ";"; if (( sLanguagesDone.indexOf( sSearch ) != -1 )) { LngLineList::iterator it = pLines->begin(); std::advance( it, nPos ); pLines->erase( it ); } if( bULF && pEntrys ) { if( !sLang.isEmpty() ) { rtl::OString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, sLang, sal_True ); if ( !sNewText.isEmpty()) { rtl::OString *pLine = (*pLines)[ nPos ]; rtl::OString sText1( sLang ); sText1 += " = \""; sText1 += sNewText; sText1 += "\""; *pLine = sText1; Text[ sLang ] = sNewText; } } nLastLangPos = nPos; nPos ++; sLanguagesDone += sSearch; } else { nLastLangPos = nPos; nPos ++; sLanguagesDone += sSearch; } } } } rtl::OString sCur; if ( nLastLangPos ) { for(size_t n = 0; n < aLanguages.size(); ++n) { sCur = aLanguages[ n ]; if( !sCur.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("en-US")) && Text[sCur].isEmpty() && pEntrys ) { rtl::OString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur, sal_True ); if (( !sNewText.isEmpty()) && !(( sCur.equalsL(RTL_CONSTASCII_STRINGPARAM("x-comment"))) && ( sNewText == "-" ))) { rtl::OString sLine; sLine += sCur; sLine += " = \""; sLine += sNewText; sLine += "\""; nLastLangPos++; nPos++; if ( nLastLangPos < pLines->size() ) { LngLineList::iterator it = pLines->begin(); std::advance( it, nLastLangPos ); pLines->insert( it, new rtl::OString(sLine) ); } else { pLines->push_back( new rtl::OString(sLine) ); } } } } } delete pResData; } for ( size_t i = 0; i < pLines->size(); ++i ) aDestination << (*pLines)[i]->getStr() << '\n'; aDestination.close(); return sal_True; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Correct ulfex to ignore comments<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "sal/config.h" #include <cstddef> #include <fstream> #include <iterator> #include <string> #include "common.hxx" #include "lngmerge.hxx" namespace { rtl::OString getBracketedContent(rtl::OString text) { return text.getToken(1, '[').getToken(0, ']'); } } // // class LngParser // LngParser::LngParser(const rtl::OString &rLngFile, sal_Bool bULFFormat) : nError( LNG_OK ) , pLines( NULL ) , sSource( rLngFile ) , bULF( bULFFormat ) { pLines = new LngLineList(); std::ifstream aStream(sSource.getStr()); if (aStream.is_open()) { bool bFirstLine = true; while (!aStream.eof()) { std::string s; std::getline(aStream, s); rtl::OString sLine(s.data(), s.length()); if( bFirstLine ) { // Always remove UTF8 BOM from the first line Export::RemoveUTF8ByteOrderMarker( sLine ); bFirstLine = false; } pLines->push_back( new rtl::OString(sLine) ); } } else nError = LNG_COULD_NOT_OPEN; } LngParser::~LngParser() { for ( size_t i = 0, n = pLines->size(); i < n; ++i ) delete (*pLines)[ i ]; pLines->clear(); delete pLines; } sal_Bool LngParser::CreateSDF(const rtl::OString &rSDFFile, const rtl::OString &rPrj, const rtl::OString &rRoot) { Export::InitLanguages( false ); aLanguages = Export::GetLanguages(); std::ofstream aSDFStream( rSDFFile.getStr(), std::ios_base::out | std::ios_base::trunc); if (!aSDFStream.is_open()) { nError = SDF_COULD_NOT_OPEN; } nError = SDF_OK; rtl::OString sActFileName( common::pathnameToken(sSource.getStr(), rRoot.getStr())); size_t nPos = 0; sal_Bool bStart = true; rtl::OString sGroup, sLine; OStringHashMap Text; rtl::OString sID; while( nPos < pLines->size() ) { sLine = *(*pLines)[ nPos++ ]; while( nPos < pLines->size() && !isNextGroup( sGroup , sLine ) ) { ReadLine( sLine , Text ); sID = sGroup; sLine = *(*pLines)[ nPos++ ]; }; if( bStart ) { bStart = false; sID = sGroup; } else { WriteSDF( aSDFStream , Text , rPrj , rRoot , sActFileName , sID ); } } aSDFStream.close(); return true; } void LngParser::WriteSDF(std::ofstream &aSDFStream, OStringHashMap &rText_inout, const rtl::OString &rPrj, const rtl::OString &rRoot, const rtl::OString &rActFileName, const rtl::OString &rID) { sal_Bool bExport = true; if ( bExport ) { rtl::OString sCur; for( unsigned int n = 0; n < aLanguages.size(); n++ ){ sCur = aLanguages[ n ]; rtl::OString sAct = rText_inout[ sCur ]; if ( sAct.isEmpty() && !sCur.isEmpty() ) sAct = rText_inout[ rtl::OString("en-US") ]; rtl::OString sOutput( rPrj ); sOutput += "\t"; if (rRoot.getLength()) sOutput += rActFileName; sOutput += "\t0\t"; sOutput += "LngText\t"; sOutput += rID; sOutput += "\t\t\t\t0\t"; sOutput += sCur; sOutput += "\t"; sOutput += sAct; sOutput += "\t\t\t\t"; aSDFStream << sOutput.getStr() << '\n'; } } } bool LngParser::isNextGroup(rtl::OString &sGroup_out, rtl::OString &sLine_in) { sLine_in = sLine_in.trim(); if ((sLine_in[0] == '[') && (sLine_in[sLine_in.getLength() - 1] == ']')) { sGroup_out = getBracketedContent(sLine_in).trim(); return true; } return false; } void LngParser::ReadLine(const rtl::OString &rLine_in, OStringHashMap &rText_inout) { rtl::OString sLang(rLine_in.getToken(0, '=').trim()); if (!sLang.isEmpty()) { rtl::OString sText(rLine_in.getToken(1, '"')); rText_inout[sLang] = sText; } } sal_Bool LngParser::Merge( const rtl::OString &rSDFFile, const rtl::OString &rDestinationFile) { Export::InitLanguages( true ); std::ofstream aDestination( rDestinationFile.getStr(), std::ios_base::out | std::ios_base::trunc); if (!aDestination.is_open()) { nError = LNG_COULD_NOT_OPEN; } nError = LNG_OK; MergeDataFile aMergeDataFile( rSDFFile, sSource, false ); rtl::OString sTmp( Export::sLanguages ); if( sTmp.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("ALL")) ) Export::SetLanguages( aMergeDataFile.GetLanguages() ); aLanguages = Export::GetLanguages(); size_t nPos = 0; sal_Bool bGroup = sal_False; rtl::OString sGroup; // seek to next group while ( nPos < pLines->size() && !bGroup ) { rtl::OString sLine( *(*pLines)[ nPos ] ); sLine = sLine.trim(); if (( sLine[0] == '[' ) && ( sLine[sLine.getLength() - 1] == ']' )) { sGroup = getBracketedContent(sLine).trim(); bGroup = sal_True; } nPos ++; } while ( nPos < pLines->size()) { OStringHashMap Text; rtl::OString sID( sGroup ); std::size_t nLastLangPos = 0; ResData *pResData = new ResData( "", sID , sSource ); pResData->sResTyp = "LngText"; PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); // read languages bGroup = sal_False; rtl::OString sLanguagesDone; while ( nPos < pLines->size() && !bGroup ) { rtl::OString sLine( *(*pLines)[ nPos ] ); sLine = sLine.trim(); if (( sLine[0] == '[' ) && ( sLine[sLine.getLength() - 1] == ']' )) { sGroup = getBracketedContent(sLine).trim(); bGroup = sal_True; nPos ++; sLanguagesDone = ""; } else { sal_Int32 n = 0; rtl::OString sLang(sLine.getToken(0, '=', n)); if (n == -1 || static_cast<bool>(sLine.match("/*"))) { ++nPos; } else { sLang = sLang.trim(); rtl::OString sSearch( ";" ); sSearch += sLang; sSearch += ";"; if (( sLanguagesDone.indexOf( sSearch ) != -1 )) { LngLineList::iterator it = pLines->begin(); std::advance( it, nPos ); pLines->erase( it ); } if( bULF && pEntrys ) { if( !sLang.isEmpty() ) { rtl::OString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, sLang, sal_True ); if ( !sNewText.isEmpty()) { rtl::OString *pLine = (*pLines)[ nPos ]; rtl::OString sText1( sLang ); sText1 += " = \""; sText1 += sNewText; sText1 += "\""; *pLine = sText1; Text[ sLang ] = sNewText; } } nLastLangPos = nPos; nPos ++; sLanguagesDone += sSearch; } else { nLastLangPos = nPos; nPos ++; sLanguagesDone += sSearch; } } } } rtl::OString sCur; if ( nLastLangPos ) { for(size_t n = 0; n < aLanguages.size(); ++n) { sCur = aLanguages[ n ]; if( !sCur.equalsIgnoreAsciiCaseL(RTL_CONSTASCII_STRINGPARAM("en-US")) && Text[sCur].isEmpty() && pEntrys ) { rtl::OString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur, sal_True ); if (( !sNewText.isEmpty()) && !(( sCur.equalsL(RTL_CONSTASCII_STRINGPARAM("x-comment"))) && ( sNewText == "-" ))) { rtl::OString sLine; sLine += sCur; sLine += " = \""; sLine += sNewText; sLine += "\""; nLastLangPos++; nPos++; if ( nLastLangPos < pLines->size() ) { LngLineList::iterator it = pLines->begin(); std::advance( it, nLastLangPos ); pLines->insert( it, new rtl::OString(sLine) ); } else { pLines->push_back( new rtl::OString(sLine) ); } } } } } delete pResData; } for ( size_t i = 0; i < pLines->size(); ++i ) aDestination << (*pLines)[i]->getStr() << '\n'; aDestination.close(); return sal_True; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * OXT - OS eXtensions for boosT * Provides important functionality necessary for writing robust server software. * * Copyright (c) 2010-2017 Phusion Holding B.V. * * 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 _OXT_DYNAMIC_THREAD_GROUP_HPP_ #define _OXT_DYNAMIC_THREAD_GROUP_HPP_ #include <vector> #include <list> #include <memory> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <oxt/thread.hpp> #include <oxt/system_calls.hpp> namespace oxt { using namespace std; using namespace boost; /** * A thread group is a collection of threads. One can run aggregate * operations on it, such as interrupting and joining all threads * in the thread group. * * Unlike boost::thread_group, an oxt::dynamic_thread_group * supports oxt::thread, and automatically removes terminated threads * from its collection, hence 'dynamic' in the name. * * Threads in the group are guaranteed to have a shorter life time * than the group itself: upon destruction, all threads in the group * will be interrupted and joined by calling interrupt_and_join_all(). */ class dynamic_thread_group { private: struct thread_handle; typedef boost::shared_ptr<thread_handle> thread_handle_ptr; /** A container which aggregates a thread object * as well as the its own iterator in the 'thread_handles' * member. The latter is used for removing itself from * 'thread_handles'. */ struct thread_handle { list<thread_handle_ptr>::iterator iterator; thread *thr; bool removed_from_list; thread_handle() { thr = NULL; removed_from_list = false; } ~thread_handle() { delete thr; } }; /** A mutex which protects thread_handles and nthreads. */ mutable boost::mutex lock; /** The internal list of threads. */ list<thread_handle_ptr> thread_handles; /** The number of threads in this thread group. */ unsigned int nthreads; struct thread_func_data { boost::function<void ()> entry_point; thread_handle *handle; }; struct thread_func_data_guard { thread_func_data *data; thread_func_data_guard(thread_func_data *_data) : data(_data) { } ~thread_func_data_guard() { delete data; } void clear() { data = NULL; } }; struct thread_cleanup { dynamic_thread_group *thread_group; thread_handle *handle; thread_cleanup(dynamic_thread_group *g, thread_handle *h) { thread_group = g; handle = h; } ~thread_cleanup() { boost::this_thread::disable_interruption di; boost::this_thread::disable_syscall_interruption dsi; boost::lock_guard<boost::mutex> l(thread_group->lock); if (!handle->removed_from_list) { thread_group->thread_handles.erase(handle->iterator); thread_group->nthreads--; } } }; void thread_main(thread_func_data *data) { thread_func_data_guard guard(data); thread_cleanup c(this, data->handle); data->entry_point(); // Clear the entry point object now because it may contain bound objects. // We want to run the destructor for these objects now, before this thread // is removed from the thread group list, so that if anybody calls // dynamic_thread_group::join_all() the caller can be sure that the // threads are really done. data->entry_point = boost::function<void ()>(); } public: dynamic_thread_group() { nthreads = 0; } ~dynamic_thread_group() { interrupt_and_join_all(); } /** * Create a new thread that belongs to this thread group. * * @param func The thread main function. * @param name A name for this thread. If the empty string is passed, * then an auto-generated name will be used. * @param stack_size The stack size for this thread. A value of 0 means * that the system's default stack size should be used. * @throws thread_resource_error Cannot create a thread. * @post this->num_threads() == old->num_threads() + 1 */ void create_thread(const boost::function<void ()> &func, const string &name = "", unsigned int stack_size = 0) { boost::lock_guard<boost::mutex> l(lock); thread_handle_ptr handle(new thread_handle()); thread_handles.push_back(handle); handle->iterator = thread_handles.end(); handle->iterator--; try { thread_func_data *data = new thread_func_data(); thread_func_data_guard guard(data); data->entry_point = func; data->handle = handle.get(); handle->thr = new thread( boost::bind(&dynamic_thread_group::thread_main, this, data), name, stack_size ); guard.clear(); nthreads++; } catch (...) { thread_handles.erase(handle->iterator); throw; } } void interrupt_all() { boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr>::iterator it; for (it = thread_handles.begin(); it != thread_handles.end(); it++) { (*it)->thr->interrupt(); } } /** * Interrupt and join all threads in this group. * * @post num_threads() == 0 */ void interrupt_and_join_all(bool interruptSyscalls = true) { /* While interrupting and joining the threads, each thread * will try to lock the mutex and remove itself from * 'thread_handles'. We want to avoid deadlocks so we * empty 'thread_handles' in the critical section and * join the threads outside the critical section. */ boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr> thread_handles_copy; list<thread_handle_ptr>::iterator it; thread_handle_ptr handle; unsigned int nthreads_copy = nthreads; vector<thread *> threads; unsigned int i = 0; // We make a copy so that the handles aren't destroyed prematurely. threads.reserve(nthreads); thread_handles_copy = thread_handles; for (it = thread_handles.begin(); it != thread_handles.end(); it++, i++) { handle = *it; handle->removed_from_list = true; threads[i] = handle->thr; } thread_handles.clear(); nthreads = 0; l.unlock(); thread::interrupt_and_join_multiple(&threads[0], nthreads_copy, interruptSyscalls); } void join_all() { // See comments from interrupt_and_join_all(). boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr> thread_handles_copy; list<thread_handle_ptr>::iterator it; thread_handle_ptr handle; unsigned int nthreads_copy = nthreads; vector<thread *> threads; unsigned int i = 0; // We make a copy so that the handles aren't destroyed prematurely. threads.reserve(nthreads); thread_handles_copy = thread_handles; for (it = thread_handles.begin(); it != thread_handles.end(); it++, i++) { handle = *it; handle->removed_from_list = true; threads[i] = handle->thr; } thread_handles.clear(); nthreads = 0; l.unlock(); for (i = 0; i < nthreads_copy; i++) { threads[i]->join(); } } /** * Returns the number of threads currently in this thread group. */ unsigned int num_threads() const { boost::lock_guard<boost::mutex> l(lock); return nthreads; } }; } // namespace oxt #endif /* _OXT_DYNAMIC_THREAD_GROUP_HPP_ */ <commit_msg>oxt/dynamic_thread_group: fix invalid use of std::vector<commit_after>/* * OXT - OS eXtensions for boosT * Provides important functionality necessary for writing robust server software. * * Copyright (c) 2010-2017 Phusion Holding B.V. * * 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 _OXT_DYNAMIC_THREAD_GROUP_HPP_ #define _OXT_DYNAMIC_THREAD_GROUP_HPP_ #include <vector> #include <list> #include <memory> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <oxt/thread.hpp> #include <oxt/system_calls.hpp> namespace oxt { using namespace std; using namespace boost; /** * A thread group is a collection of threads. One can run aggregate * operations on it, such as interrupting and joining all threads * in the thread group. * * Unlike boost::thread_group, an oxt::dynamic_thread_group * supports oxt::thread, and automatically removes terminated threads * from its collection, hence 'dynamic' in the name. * * Threads in the group are guaranteed to have a shorter life time * than the group itself: upon destruction, all threads in the group * will be interrupted and joined by calling interrupt_and_join_all(). */ class dynamic_thread_group { private: struct thread_handle; typedef boost::shared_ptr<thread_handle> thread_handle_ptr; /** A container which aggregates a thread object * as well as the its own iterator in the 'thread_handles' * member. The latter is used for removing itself from * 'thread_handles'. */ struct thread_handle { list<thread_handle_ptr>::iterator iterator; thread *thr; bool removed_from_list; thread_handle() { thr = NULL; removed_from_list = false; } ~thread_handle() { delete thr; } }; /** A mutex which protects thread_handles and nthreads. */ mutable boost::mutex lock; /** The internal list of threads. */ list<thread_handle_ptr> thread_handles; /** The number of threads in this thread group. */ unsigned int nthreads; struct thread_func_data { boost::function<void ()> entry_point; thread_handle *handle; }; struct thread_func_data_guard { thread_func_data *data; thread_func_data_guard(thread_func_data *_data) : data(_data) { } ~thread_func_data_guard() { delete data; } void clear() { data = NULL; } }; struct thread_cleanup { dynamic_thread_group *thread_group; thread_handle *handle; thread_cleanup(dynamic_thread_group *g, thread_handle *h) { thread_group = g; handle = h; } ~thread_cleanup() { boost::this_thread::disable_interruption di; boost::this_thread::disable_syscall_interruption dsi; boost::lock_guard<boost::mutex> l(thread_group->lock); if (!handle->removed_from_list) { thread_group->thread_handles.erase(handle->iterator); thread_group->nthreads--; } } }; void thread_main(thread_func_data *data) { thread_func_data_guard guard(data); thread_cleanup c(this, data->handle); data->entry_point(); // Clear the entry point object now because it may contain bound objects. // We want to run the destructor for these objects now, before this thread // is removed from the thread group list, so that if anybody calls // dynamic_thread_group::join_all() the caller can be sure that the // threads are really done. data->entry_point = boost::function<void ()>(); } public: dynamic_thread_group() { nthreads = 0; } ~dynamic_thread_group() { interrupt_and_join_all(); } /** * Create a new thread that belongs to this thread group. * * @param func The thread main function. * @param name A name for this thread. If the empty string is passed, * then an auto-generated name will be used. * @param stack_size The stack size for this thread. A value of 0 means * that the system's default stack size should be used. * @throws thread_resource_error Cannot create a thread. * @post this->num_threads() == old->num_threads() + 1 */ void create_thread(const boost::function<void ()> &func, const string &name = "", unsigned int stack_size = 0) { boost::lock_guard<boost::mutex> l(lock); thread_handle_ptr handle(new thread_handle()); thread_handles.push_back(handle); handle->iterator = thread_handles.end(); handle->iterator--; try { thread_func_data *data = new thread_func_data(); thread_func_data_guard guard(data); data->entry_point = func; data->handle = handle.get(); handle->thr = new thread( boost::bind(&dynamic_thread_group::thread_main, this, data), name, stack_size ); guard.clear(); nthreads++; } catch (...) { thread_handles.erase(handle->iterator); throw; } } void interrupt_all() { boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr>::iterator it; for (it = thread_handles.begin(); it != thread_handles.end(); it++) { (*it)->thr->interrupt(); } } /** * Interrupt and join all threads in this group. * * @post num_threads() == 0 */ void interrupt_and_join_all(bool interruptSyscalls = true) { /* While interrupting and joining the threads, each thread * will try to lock the mutex and remove itself from * 'thread_handles'. We want to avoid deadlocks so we * empty 'thread_handles' in the critical section and * join the threads outside the critical section. */ boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr> thread_handles_copy; list<thread_handle_ptr>::iterator it; thread_handle_ptr handle; unsigned int nthreads_copy = nthreads; vector<thread *> threads; unsigned int i = 0; // We make a copy so that the handles aren't destroyed prematurely. threads.resize(nthreads); thread_handles_copy = thread_handles; for (it = thread_handles.begin(); it != thread_handles.end(); it++, i++) { handle = *it; handle->removed_from_list = true; threads[i] = handle->thr; } thread_handles.clear(); nthreads = 0; l.unlock(); thread::interrupt_and_join_multiple(&threads[0], nthreads_copy, interruptSyscalls); } void join_all() { // See comments from interrupt_and_join_all(). boost::unique_lock<boost::mutex> l(lock); list<thread_handle_ptr> thread_handles_copy; list<thread_handle_ptr>::iterator it; thread_handle_ptr handle; unsigned int nthreads_copy = nthreads; vector<thread *> threads; unsigned int i = 0; // We make a copy so that the handles aren't destroyed prematurely. threads.resize(nthreads); thread_handles_copy = thread_handles; for (it = thread_handles.begin(); it != thread_handles.end(); it++, i++) { handle = *it; handle->removed_from_list = true; threads[i] = handle->thr; } thread_handles.clear(); nthreads = 0; l.unlock(); for (i = 0; i < nthreads_copy; i++) { threads[i]->join(); } } /** * Returns the number of threads currently in this thread group. */ unsigned int num_threads() const { boost::lock_guard<boost::mutex> l(lock); return nthreads; } }; } // namespace oxt #endif /* _OXT_DYNAMIC_THREAD_GROUP_HPP_ */ <|endoftext|>
<commit_before><commit_msg>Only escape double-quotes for ulf files.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2020 PaddlePaddle 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. */ #ifdef PADDLE_WITH_XPU #include "paddle/fluid/operators/sum_op.h" #include <vector> #include "paddle/fluid/platform/xpu_header.h" namespace paddle { namespace operators { using framework::Tensor; template <typename DeviceContext, typename T> class SumXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext &context) const override { auto in_vars = context.MultiInputVar("X"); auto out_var = context.OutputVar("Out"); auto *out = context.Output<LoDTensor>("Out"); bool in_place = out_var == in_vars[0]; int N = in_vars.size(); PADDLE_ENFORCE_EQ( out_var->IsType<framework::LoDTensor>(), true, platform::errors::InvalidArgument("XPU only surpport LodTensor")); if (!in_place) { out->mutable_data<T>(context.GetPlace()); } auto &dev_ctx = context.template device_context<DeviceContext>(); std::vector<const float *> ptrs(N, nullptr); int valid_count = 0; for (int i = 0; i < N; ++i) { PADDLE_ENFORCE_EQ( in_vars[i]->IsType<framework::LoDTensor>(), true, platform::errors::InvalidArgument("XPU only surpport LodTensor")); auto &in_t = in_vars[i]->Get<framework::LoDTensor>(); if (in_t.numel() == 0) { continue; } ptrs[valid_count] = reinterpret_cast<const float *>(in_t.data<T>()); valid_count++; } int r = xpu::sum_batch(dev_ctx.x_context(), ptrs.data(), out->data<T>(), valid_count, out->numel()); PADDLE_ENFORCE_EQ(r, xpu::Error_t::SUCCESS, platform::errors::Fatal("XPU sum kernel error!")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_XPU_KERNEL( sum, ops::SumXPUKernel<paddle::platform::XPUDeviceContext, float>); #endif <commit_msg>fix enforce msg of sum xpu op (#30113)<commit_after>/* Copyright (c) 2020 PaddlePaddle 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. */ #ifdef PADDLE_WITH_XPU #include "paddle/fluid/operators/sum_op.h" #include <vector> #include "paddle/fluid/platform/xpu_header.h" namespace paddle { namespace operators { using framework::Tensor; template <typename DeviceContext, typename T> class SumXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext &context) const override { auto in_vars = context.MultiInputVar("X"); auto out_var = context.OutputVar("Out"); auto *out = context.Output<LoDTensor>("Out"); bool in_place = out_var == in_vars[0]; int N = in_vars.size(); PADDLE_ENFORCE_EQ( out_var->IsType<framework::LoDTensor>(), true, platform::errors::InvalidArgument("XPU only surpport LodTensor")); if (!in_place) { out->mutable_data<T>(context.GetPlace()); } auto &dev_ctx = context.template device_context<DeviceContext>(); std::vector<const float *> ptrs(N, nullptr); int valid_count = 0; for (int i = 0; i < N; ++i) { PADDLE_ENFORCE_EQ( in_vars[i]->IsType<framework::LoDTensor>(), true, platform::errors::InvalidArgument("XPU only surpport LodTensor")); auto &in_t = in_vars[i]->Get<framework::LoDTensor>(); if (in_t.numel() == 0) { continue; } ptrs[valid_count] = reinterpret_cast<const float *>(in_t.data<T>()); valid_count++; } int r = xpu::sum_batch(dev_ctx.x_context(), ptrs.data(), out->data<T>(), valid_count, out->numel()); if (r == xpu::Error_t::INVALID_PARAM) { PADDLE_ENFORCE_EQ( r, xpu::Error_t::SUCCESS, platform::errors::InvalidArgument( "XPU kernel error of SumOp, error message: INVALID_PARAM, " "please check your input & output.")); } else if (r == xpu::Error_t::RUNTIME_ERROR) { PADDLE_ENFORCE_EQ(r, xpu::Error_t::SUCCESS, platform::errors::Unavailable( "XPU kernel error of SumOp, error message: " "RUNTIME_ERROR, please check whether Baidu " "Kunlun Card is properly installed.")); } else if (r == xpu::Error_t::NO_ENOUGH_WORKSPACE) { PADDLE_ENFORCE_EQ(r, xpu::Error_t::SUCCESS, platform::errors::ResourceExhausted( "XPU kernel error of SumOp, error " "message: NO_ENOUGH_WORKSPACE, XPU " "has no enough memory.")); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_XPU_KERNEL( sum, ops::SumXPUKernel<paddle::platform::XPUDeviceContext, float>); #endif <|endoftext|>
<commit_before>//===-- ThreadPlanShouldStopHere.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Log.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanShouldStopHere.h" using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // ThreadPlanShouldStopHere constructor //---------------------------------------------------------------------- ThreadPlanShouldStopHere::ThreadPlanShouldStopHere(ThreadPlan *owner) : m_callbacks(), m_baton(nullptr), m_owner(owner), m_flags(ThreadPlanShouldStopHere::eNone) { m_callbacks.should_stop_here_callback = ThreadPlanShouldStopHere::DefaultShouldStopHereCallback; m_callbacks.step_from_here_callback = ThreadPlanShouldStopHere::DefaultStepFromHereCallback; } ThreadPlanShouldStopHere::ThreadPlanShouldStopHere(ThreadPlan *owner, const ThreadPlanShouldStopHereCallbacks *callbacks, void *baton) : m_callbacks (), m_baton (), m_owner (owner), m_flags (ThreadPlanShouldStopHere::eNone) { SetShouldStopHereCallbacks(callbacks, baton); } ThreadPlanShouldStopHere::~ThreadPlanShouldStopHere() = default; bool ThreadPlanShouldStopHere::InvokeShouldStopHereCallback (FrameComparison operation) { bool should_stop_here = true; if (m_callbacks.should_stop_here_callback) { should_stop_here = m_callbacks.should_stop_here_callback (m_owner, m_flags, operation, m_baton); Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); if (log) { lldb::addr_t current_addr = m_owner->GetThread().GetRegisterContext()->GetPC(0); log->Printf ("ShouldStopHere callback returned %u from 0x%" PRIx64 ".", should_stop_here, current_addr); } } return should_stop_here; } bool ThreadPlanShouldStopHere::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, FrameComparison operation, void *baton) { bool should_stop_here = true; StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get(); if (!frame) return true; Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); if ((operation == eFrameCompareOlder && flags.Test(eStepOutAvoidNoDebug)) || (operation == eFrameCompareYounger && flags.Test(eStepInAvoidNoDebug)) || (operation == eFrameCompareSameParent && flags.Test(eStepInAvoidNoDebug))) { if (!frame->HasDebugInformation()) { if (log) log->Printf ("Stepping out of frame with no debug info"); should_stop_here = false; } } // Always avoid code with line number 0. // FIXME: At present the ShouldStop and the StepFromHere calculate this independently. If this ever // becomes expensive (this one isn't) we can try to have this set a state that the StepFromHere can use. if (frame) { SymbolContext sc; sc = frame->GetSymbolContext (eSymbolContextLineEntry); if (sc.line_entry.line == 0) should_stop_here = false; } return should_stop_here; } ThreadPlanSP ThreadPlanShouldStopHere::DefaultStepFromHereCallback (ThreadPlan *current_plan, Flags &flags, FrameComparison operation, void *baton) { const bool stop_others = false; const size_t frame_index = 0; ThreadPlanSP return_plan_sp; // If we are stepping through code at line number 0, then we need to step over this range. Otherwise // we will step out. Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get(); if (!frame) return return_plan_sp; SymbolContext sc; sc = frame->GetSymbolContext (eSymbolContextLineEntry); sc = frame->GetSymbolContext (eSymbolContextLineEntry|eSymbolContextSymbol); if (sc.line_entry.line == 0) { AddressRange range = sc.line_entry.range; // If the whole function is marked line 0 just step out, that's easier & faster than continuing // to step through it. bool just_step_out = false; if (sc.symbol && sc.symbol->ValueIsAddress()) { Address symbol_end = sc.symbol->GetAddress(); symbol_end.Slide(sc.symbol->GetByteSize() - 1); if (range.ContainsFileAddress(sc.symbol->GetAddress()) && range.ContainsFileAddress(symbol_end)) { if (log) log->Printf("Stopped in a function with only line 0 lines, just stepping out."); just_step_out = true; } } if (!just_step_out) { if (log) log->Printf ("ThreadPlanShouldStopHere::DefaultStepFromHereCallback Queueing StepInRange plan to step through line 0 code."); return_plan_sp = current_plan->GetThread().QueueThreadPlanForStepInRange(false, range, sc, NULL, eOnlyDuringStepping, eLazyBoolCalculate, eLazyBoolNo); } } if (!return_plan_sp) return_plan_sp = current_plan->GetThread().QueueThreadPlanForStepOutNoShouldStop(false, nullptr, true, stop_others, eVoteNo, eVoteNoOpinion, frame_index, true); return return_plan_sp; } ThreadPlanSP ThreadPlanShouldStopHere::QueueStepOutFromHerePlan(lldb_private::Flags &flags, lldb::FrameComparison operation) { ThreadPlanSP return_plan_sp; if (m_callbacks.step_from_here_callback) { return_plan_sp = m_callbacks.step_from_here_callback (m_owner, flags, operation, m_baton); } return return_plan_sp; } lldb::ThreadPlanSP ThreadPlanShouldStopHere::CheckShouldStopHereAndQueueStepOut (lldb::FrameComparison operation) { if (!InvokeShouldStopHereCallback(operation)) return QueueStepOutFromHerePlan(m_flags, operation); else return ThreadPlanSP(); } <commit_msg>Remove a should have been deleted extra assignment to a variable. Also fix up the formatting a bit, it looks like something was inserting actual tabs. Replace with 4 spaces.<commit_after>//===-- ThreadPlanShouldStopHere.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Log.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanShouldStopHere.h" using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // ThreadPlanShouldStopHere constructor //---------------------------------------------------------------------- ThreadPlanShouldStopHere::ThreadPlanShouldStopHere(ThreadPlan *owner) : m_callbacks(), m_baton(nullptr), m_owner(owner), m_flags(ThreadPlanShouldStopHere::eNone) { m_callbacks.should_stop_here_callback = ThreadPlanShouldStopHere::DefaultShouldStopHereCallback; m_callbacks.step_from_here_callback = ThreadPlanShouldStopHere::DefaultStepFromHereCallback; } ThreadPlanShouldStopHere::ThreadPlanShouldStopHere(ThreadPlan *owner, const ThreadPlanShouldStopHereCallbacks *callbacks, void *baton) : m_callbacks (), m_baton (), m_owner (owner), m_flags (ThreadPlanShouldStopHere::eNone) { SetShouldStopHereCallbacks(callbacks, baton); } ThreadPlanShouldStopHere::~ThreadPlanShouldStopHere() = default; bool ThreadPlanShouldStopHere::InvokeShouldStopHereCallback (FrameComparison operation) { bool should_stop_here = true; if (m_callbacks.should_stop_here_callback) { should_stop_here = m_callbacks.should_stop_here_callback (m_owner, m_flags, operation, m_baton); Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); if (log) { lldb::addr_t current_addr = m_owner->GetThread().GetRegisterContext()->GetPC(0); log->Printf ("ShouldStopHere callback returned %u from 0x%" PRIx64 ".", should_stop_here, current_addr); } } return should_stop_here; } bool ThreadPlanShouldStopHere::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, FrameComparison operation, void *baton) { bool should_stop_here = true; StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get(); if (!frame) return true; Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); if ((operation == eFrameCompareOlder && flags.Test(eStepOutAvoidNoDebug)) || (operation == eFrameCompareYounger && flags.Test(eStepInAvoidNoDebug)) || (operation == eFrameCompareSameParent && flags.Test(eStepInAvoidNoDebug))) { if (!frame->HasDebugInformation()) { if (log) log->Printf ("Stepping out of frame with no debug info"); should_stop_here = false; } } // Always avoid code with line number 0. // FIXME: At present the ShouldStop and the StepFromHere calculate this independently. If this ever // becomes expensive (this one isn't) we can try to have this set a state that the StepFromHere can use. if (frame) { SymbolContext sc; sc = frame->GetSymbolContext (eSymbolContextLineEntry); if (sc.line_entry.line == 0) should_stop_here = false; } return should_stop_here; } ThreadPlanSP ThreadPlanShouldStopHere::DefaultStepFromHereCallback (ThreadPlan *current_plan, Flags &flags, FrameComparison operation, void *baton) { const bool stop_others = false; const size_t frame_index = 0; ThreadPlanSP return_plan_sp; // If we are stepping through code at line number 0, then we need to step over this range. Otherwise // we will step out. Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get(); if (!frame) return return_plan_sp; SymbolContext sc; sc = frame->GetSymbolContext (eSymbolContextLineEntry|eSymbolContextSymbol); if (sc.line_entry.line == 0) { AddressRange range = sc.line_entry.range; // If the whole function is marked line 0 just step out, that's easier & faster than continuing // to step through it. bool just_step_out = false; if (sc.symbol && sc.symbol->ValueIsAddress()) { Address symbol_end = sc.symbol->GetAddress(); symbol_end.Slide(sc.symbol->GetByteSize() - 1); if (range.ContainsFileAddress(sc.symbol->GetAddress()) && range.ContainsFileAddress(symbol_end)) { if (log) log->Printf("Stopped in a function with only line 0 lines, just stepping out."); just_step_out = true; } } if (!just_step_out) { if (log) log->Printf ("ThreadPlanShouldStopHere::DefaultStepFromHereCallback Queueing StepInRange plan to step through line 0 code."); return_plan_sp = current_plan->GetThread().QueueThreadPlanForStepInRange(false, range, sc, NULL, eOnlyDuringStepping, eLazyBoolCalculate, eLazyBoolNo); } } if (!return_plan_sp) return_plan_sp = current_plan->GetThread().QueueThreadPlanForStepOutNoShouldStop(false, nullptr, true, stop_others, eVoteNo, eVoteNoOpinion, frame_index, true); return return_plan_sp; } ThreadPlanSP ThreadPlanShouldStopHere::QueueStepOutFromHerePlan(lldb_private::Flags &flags, lldb::FrameComparison operation) { ThreadPlanSP return_plan_sp; if (m_callbacks.step_from_here_callback) { return_plan_sp = m_callbacks.step_from_here_callback (m_owner, flags, operation, m_baton); } return return_plan_sp; } lldb::ThreadPlanSP ThreadPlanShouldStopHere::CheckShouldStopHereAndQueueStepOut (lldb::FrameComparison operation) { if (!InvokeShouldStopHereCallback(operation)) return QueueStepOutFromHerePlan(m_flags, operation); else return ThreadPlanSP(); } <|endoftext|>
<commit_before>#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Libraries/glm/gtx/vector_angle.hpp" #include "Vajra/Common/Messages/CustomMessageDatas/MessageData1S1I1F.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" #include "Vajra/Engine/SceneGraph/SceneGraph3D.h" #include "Vajra/Engine/Tween/Tween.h" #include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h" #include "Vajra/Engine/DebugDrawer/DebugDrawer.h" #define TOUCH_SCALE_TIME .3f void playerUnitNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float currentNumber, std::string tweenClipName, MessageData1S1I1F* userParams) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i); //ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { PlayerUnit* pUnit = go->GetComponent<PlayerUnit>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { if(tweenClipName == "pulse") { float scaleValue = sinf(currentNumber); pUnit->touchIndicatorRef->GetTransform()->SetScale(scaleValue, scaleValue, scaleValue); } } } } PlayerUnit::PlayerUnit() : BaseUnit() { this->init(); } PlayerUnit::PlayerUnit(Object* object_) : BaseUnit(object_) { this->init(); } PlayerUnit::~PlayerUnit() { this->destroy(); } void PlayerUnit::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; this->inputState = InputState::INPUT_STATE_NONE; this->touchNearUnit = false; this->unitHasTouchFocus = false; this->gridNavRef->SetMovementSpeed(MOVE_SPEED); this->gridNavRef->SetTurnSpeedDegrees(TURN_SPEED_DEG); this->gridNavRef->SetMaxNavigableUnitType(LAST_PLAYER_UNIT_TYPE); this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false); this->touchIndicatorRef = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->touchIndicatorRef->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Touch_Indicator_03.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Touch_Fail_01.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_Arrow_05.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_cyan.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->touchIndicatorRef->SetVisible(false); this->touchIndicatorRef->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->currentTouchedCell = NULL; this->SwitchActionState(UNIT_ACTION_STATE_IDLE); } void PlayerUnit::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } void PlayerUnit::HandleMessage(MessageChunk messageChunk) { BaseUnit::HandleMessage(messageChunk); switch(messageChunk->GetMessageType()) { case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION: if(this->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL) { this->onSpecialEnd(); } else { this->SwitchActionState(UNIT_ACTION_STATE_IDLE); if(this->inputState == InputState::INPUT_STATE_WAIT || this->inputState == InputState::INPUT_STATE_NONE) { ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), this->touchIndicatorRef->GetTransform()->GetScale(), glm::vec3(0), TOUCH_SCALE_TIME); } } break; default: break; } } void PlayerUnit::OnTouch(int touchId, GridCell* touchedCell) { bool touchBegan = ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Began; if(touchBegan) { this->unitHasTouchFocus = true; } if(this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_DOING_SPECIAL || this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_POST_SPECIAL) { this->unitHasTouchFocus = false; return; } // only handle a touch that was started when the unit has focus if(this->unitHasTouchFocus) { if(this->currentTouchedCell != touchedCell || touchBegan) { GridCell* prevTouchedCell = this->currentTouchedCell; this->currentTouchedCell = touchedCell; this->touchedCellChanged(prevTouchedCell); } if(touchBegan) { this->touchStartPos = ENGINE->GetInput()->GetTouch(touchId).pos; this->setTouchNearUnit(); } switch(this->inputState) { case InputState::INPUT_STATE_NONE: this->onSelectedTouch(); case InputState::INPUT_STATE_WAIT: case InputState::INPUT_STATE_NAV: this->onNavTouch(touchId, touchedCell); break; case InputState::INPUT_STATE_SPECIAL: this->onSpecialTouch(touchId); break; default: break; } } } void PlayerUnit::OnDeselect() { this->inputState = InputState::INPUT_STATE_NONE; ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); this->SetTouchIndicatorVisible(false); } void PlayerUnit::OnTransitionZoneEntered(GridCell* newTarget) { if(this->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL || this->GetUnitActionState() == UNIT_ACTION_STATE_POST_SPECIAL) { this->cancelSpecial(); } this->SetTouchIndicatorCell(newTarget); this->SwitchActionState(UNIT_ACTION_STATE_WALKING); this->startTouchIndicatorPulse(); this->gridNavRef->SetDestination(newTarget); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(true); } void PlayerUnit::onSelectedTouch() { this->inputState = InputState::INPUT_STATE_WAIT; } void PlayerUnit::startSpecial() { this->SwitchActionState(UNIT_ACTION_STATE_DOING_SPECIAL); this->specialStartPos = this->GetObject()->GetComponent<Transform>()->GetPositionWorld(); } void PlayerUnit::onSpecialEnd() { this->inputState = InputState::INPUT_STATE_NONE; this->SwitchActionState(UNIT_ACTION_STATE_POST_SPECIAL); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(false); } void PlayerUnit::cancelSpecial() { this->inputState = InputState::INPUT_STATE_NONE; this->SwitchActionState(UNIT_ACTION_STATE_IDLE); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(false); } void PlayerUnit::onNavTouch(int touchId, GridCell* touchedCell) { if(this->isSpecialTouch(touchId)) { this->inputState = InputState::INPUT_STATE_SPECIAL; this->onSpecialTouch(touchId); this->SwitchActionState(UNIT_ACTION_STATE_PRE_SPECIAL); } else { switch(ENGINE->GetInput()->GetTouch(touchId).phase) { case TouchPhase::Began: this->inputState = InputState::INPUT_STATE_NAV; this->touchIndicatorRef->GetTransform()->SetPosition(this->currentTouchedCell->center); this->touchIndicatorRef->GetTransform()->Translate(0.01f, YAXIS); ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), glm::vec3(0), glm::vec3(1),TOUCH_SCALE_TIME); break; case TouchPhase::Ended: this->currentTouchedCell = nullptr; this->inputState = InputState::INPUT_STATE_WAIT; if(this->gridNavRef->SetDestination(touchedCell->x, touchedCell->z) && touchedCell != this->gridNavRef->GetCurrentCell()) { this->SwitchActionState(UNIT_ACTION_STATE_WALKING); this->startTouchIndicatorPulse(); } else { ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), glm::vec3(1), glm::vec3(0), TOUCH_SCALE_TIME * 2.0f); } if(touchedCell == this->gridNavRef->GetCurrentCell()) { ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), this->touchIndicatorRef->GetTransform()->GetScale(), glm::vec3(0), TOUCH_SCALE_TIME); } break; case TouchPhase::Cancelled: this->inputState = InputState::INPUT_STATE_WAIT; this->currentTouchedCell = nullptr; this->touchIndicatorRef->SetVisible(false); break; default: break; } } } void PlayerUnit::touchedCellChanged(GridCell* /*prevTouchedCell*/) { this->SetTouchIndicatorCell(this->currentTouchedCell); if(this->inputState == InputState::INPUT_STATE_NAV || this->inputState == InputState::INPUT_STATE_WAIT) { if(this->gridNavRef->CanReachDestination(this->currentTouchedCell)) { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); } else { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(BAD_TOUCH); } // Toggle the touch indicator visibility bool standable; for(int i = 0; i < NUM_ELEVATIONS; ++i) { standable = SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(this->currentTouchedCell->x, this->currentTouchedCell->z, i); if(standable) { break; } } this->touchIndicatorRef->SetVisible(standable); } } void PlayerUnit::TouchIndicatorLookAt(GridCell* target) { this->GridPlaneLookAt(this->touchIndicatorRef, target); } void PlayerUnit::GridPlaneLookAt(GameObject* plane, GridCell* target) { Transform* trans = plane->GetComponent<Transform>(); glm::vec3 direction = target->center - this->gridNavRef->GetCurrentCell()->center; direction = glm::normalize(direction); float angle = acos(glm::dot(direction, ZAXIS)); if(direction.x < 0) { angle = -angle; } if(glm::isnan(angle)) { return; } // Since the plane is normally facing the the -ZAXIS we have to do this trans->SetOrientation(0, YAXIS); trans->Rotate(90.0f inRadians, XAXIS); trans->Rotate(angle, YAXIS); } void PlayerUnit::setTouchNearUnit() { glm::vec3 gridPos = SINGLETONS->GetGridManager()->TouchPositionToGridPosition(touchStartPos); if(glm::distance(gridPos, this->gridNavRef->GetCurrentCell()->center) < NEAR_TOUCH_DIST) { this->touchNearUnit = true; } else { this->touchNearUnit = false; } } void PlayerUnit::startTouchIndicatorPulse() { MessageData1S1I1F* userParams = new MessageData1S1I1F(); userParams->i = this->GetObject()->GetId(); ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->TweenToNumber(45.0f inRadians, 135.0f inRadians, 1.0f, true, true, true, "pulse", NUMBER_TWEEN_AFFILIATION_SCENEGRAPH_3D, userParams, playerUnitNumberTweenCallback); } void PlayerUnit::SetTouchIndicatorSprite(int index) { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(index); } void PlayerUnit::SetTouchIndicatorCell(GridCell* c) { this->touchIndicatorRef->GetTransform()->SetPosition(c->center); this->touchIndicatorRef->GetTransform()->Translate(0.01f + (c->y * 0.05), YAXIS); } void PlayerUnit::SetTouchIndicatorVisible(bool visibility) { this->touchIndicatorRef->SetVisible(visibility); } <commit_msg>Fixed bug with units being put in wrong input state<commit_after>#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Libraries/glm/gtx/vector_angle.hpp" #include "Vajra/Common/Messages/CustomMessageDatas/MessageData1S1I1F.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" #include "Vajra/Engine/SceneGraph/SceneGraph3D.h" #include "Vajra/Engine/Tween/Tween.h" #include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h" #include "Vajra/Engine/DebugDrawer/DebugDrawer.h" #define TOUCH_SCALE_TIME .3f void playerUnitNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float currentNumber, std::string tweenClipName, MessageData1S1I1F* userParams) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i); //ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { PlayerUnit* pUnit = go->GetComponent<PlayerUnit>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { if(tweenClipName == "pulse") { float scaleValue = sinf(currentNumber); pUnit->touchIndicatorRef->GetTransform()->SetScale(scaleValue, scaleValue, scaleValue); } } } } PlayerUnit::PlayerUnit() : BaseUnit() { this->init(); } PlayerUnit::PlayerUnit(Object* object_) : BaseUnit(object_) { this->init(); } PlayerUnit::~PlayerUnit() { this->destroy(); } void PlayerUnit::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; this->inputState = InputState::INPUT_STATE_NONE; this->touchNearUnit = false; this->unitHasTouchFocus = false; this->gridNavRef->SetMovementSpeed(MOVE_SPEED); this->gridNavRef->SetTurnSpeedDegrees(TURN_SPEED_DEG); this->gridNavRef->SetMaxNavigableUnitType(LAST_PLAYER_UNIT_TYPE); this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false); this->touchIndicatorRef = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->touchIndicatorRef->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Touch_Indicator_03.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Touch_Fail_01.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_Arrow_05.png"); pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_cyan.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->touchIndicatorRef->SetVisible(false); this->touchIndicatorRef->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->currentTouchedCell = NULL; this->SwitchActionState(UNIT_ACTION_STATE_IDLE); } void PlayerUnit::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } void PlayerUnit::HandleMessage(MessageChunk messageChunk) { BaseUnit::HandleMessage(messageChunk); switch(messageChunk->GetMessageType()) { case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION: if(this->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL) { this->onSpecialEnd(); } else { this->SwitchActionState(UNIT_ACTION_STATE_IDLE); if(this->inputState == InputState::INPUT_STATE_WAIT || this->inputState == InputState::INPUT_STATE_NONE) { ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), this->touchIndicatorRef->GetTransform()->GetScale(), glm::vec3(0), TOUCH_SCALE_TIME); } } break; default: break; } } void PlayerUnit::OnTouch(int touchId, GridCell* touchedCell) { bool touchBegan = ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Began; if(touchBegan) { this->unitHasTouchFocus = true; } if(this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_DOING_SPECIAL || this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_POST_SPECIAL) { this->unitHasTouchFocus = false; return; } // only handle a touch that was started when the unit has focus if(this->unitHasTouchFocus) { if(this->currentTouchedCell != touchedCell || touchBegan) { GridCell* prevTouchedCell = this->currentTouchedCell; this->currentTouchedCell = touchedCell; this->touchedCellChanged(prevTouchedCell); } if(touchBegan) { this->touchStartPos = ENGINE->GetInput()->GetTouch(touchId).pos; this->setTouchNearUnit(); } switch(this->inputState) { case InputState::INPUT_STATE_NONE: this->onSelectedTouch(); case InputState::INPUT_STATE_WAIT: case InputState::INPUT_STATE_NAV: this->onNavTouch(touchId, touchedCell); break; case InputState::INPUT_STATE_SPECIAL: this->onSpecialTouch(touchId); break; default: break; } } } void PlayerUnit::OnDeselect() { this->inputState = InputState::INPUT_STATE_NONE; ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); this->SetTouchIndicatorVisible(false); } void PlayerUnit::OnTransitionZoneEntered(GridCell* newTarget) { if(this->GetUnitActionState() == UNIT_ACTION_STATE_DOING_SPECIAL || this->GetUnitActionState() == UNIT_ACTION_STATE_POST_SPECIAL) { this->cancelSpecial(); } this->SetTouchIndicatorCell(newTarget); this->SwitchActionState(UNIT_ACTION_STATE_WALKING); this->startTouchIndicatorPulse(); this->gridNavRef->SetDestination(newTarget); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(true); } void PlayerUnit::onSelectedTouch() { this->inputState = InputState::INPUT_STATE_WAIT; } void PlayerUnit::startSpecial() { this->SwitchActionState(UNIT_ACTION_STATE_DOING_SPECIAL); this->specialStartPos = this->GetObject()->GetComponent<Transform>()->GetPositionWorld(); } void PlayerUnit::onSpecialEnd() { this->inputState = InputState::INPUT_STATE_WAIT; this->SwitchActionState(UNIT_ACTION_STATE_POST_SPECIAL); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(false); } void PlayerUnit::cancelSpecial() { this->inputState = InputState::INPUT_STATE_WAIT; this->SwitchActionState(UNIT_ACTION_STATE_IDLE); this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); this->touchIndicatorRef->SetVisible(false); } void PlayerUnit::onNavTouch(int touchId, GridCell* touchedCell) { if(this->isSpecialTouch(touchId)) { this->inputState = InputState::INPUT_STATE_SPECIAL; this->onSpecialTouch(touchId); this->SwitchActionState(UNIT_ACTION_STATE_PRE_SPECIAL); } else { switch(ENGINE->GetInput()->GetTouch(touchId).phase) { case TouchPhase::Began: this->inputState = InputState::INPUT_STATE_NAV; this->touchIndicatorRef->GetTransform()->SetPosition(this->currentTouchedCell->center); this->touchIndicatorRef->GetTransform()->Translate(0.01f, YAXIS); ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), glm::vec3(0), glm::vec3(1),TOUCH_SCALE_TIME); break; case TouchPhase::Ended: this->currentTouchedCell = nullptr; this->inputState = InputState::INPUT_STATE_WAIT; if(this->gridNavRef->SetDestination(touchedCell->x, touchedCell->z) && touchedCell != this->gridNavRef->GetCurrentCell()) { this->SwitchActionState(UNIT_ACTION_STATE_WALKING); this->startTouchIndicatorPulse(); } else { ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), glm::vec3(1), glm::vec3(0), TOUCH_SCALE_TIME * 2.0f); } if(touchedCell == this->gridNavRef->GetCurrentCell()) { ENGINE->GetTween()->CancelNumberTween("pulse"); ENGINE->GetTween()->TweenScale(this->touchIndicatorRef->GetId(), this->touchIndicatorRef->GetTransform()->GetScale(), glm::vec3(0), TOUCH_SCALE_TIME); } break; case TouchPhase::Cancelled: this->inputState = InputState::INPUT_STATE_WAIT; this->currentTouchedCell = nullptr; this->touchIndicatorRef->SetVisible(false); break; default: break; } } } void PlayerUnit::touchedCellChanged(GridCell* /*prevTouchedCell*/) { this->SetTouchIndicatorCell(this->currentTouchedCell); if(this->inputState == InputState::INPUT_STATE_NAV || this->inputState == InputState::INPUT_STATE_WAIT) { if(this->gridNavRef->CanReachDestination(this->currentTouchedCell)) { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(GOOD_TOUCH); } else { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(BAD_TOUCH); } // Toggle the touch indicator visibility bool standable; for(int i = 0; i < NUM_ELEVATIONS; ++i) { standable = SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(this->currentTouchedCell->x, this->currentTouchedCell->z, i); if(standable) { break; } } this->touchIndicatorRef->SetVisible(standable); } } void PlayerUnit::TouchIndicatorLookAt(GridCell* target) { this->GridPlaneLookAt(this->touchIndicatorRef, target); } void PlayerUnit::GridPlaneLookAt(GameObject* plane, GridCell* target) { Transform* trans = plane->GetComponent<Transform>(); glm::vec3 direction = target->center - this->gridNavRef->GetCurrentCell()->center; direction = glm::normalize(direction); float angle = acos(glm::dot(direction, ZAXIS)); if(direction.x < 0) { angle = -angle; } if(glm::isnan(angle)) { return; } // Since the plane is normally facing the the -ZAXIS we have to do this trans->SetOrientation(0, YAXIS); trans->Rotate(90.0f inRadians, XAXIS); trans->Rotate(angle, YAXIS); } void PlayerUnit::setTouchNearUnit() { glm::vec3 gridPos = SINGLETONS->GetGridManager()->TouchPositionToGridPosition(touchStartPos); if(glm::distance(gridPos, this->gridNavRef->GetCurrentCell()->center) < NEAR_TOUCH_DIST) { this->touchNearUnit = true; } else { this->touchNearUnit = false; } } void PlayerUnit::startTouchIndicatorPulse() { MessageData1S1I1F* userParams = new MessageData1S1I1F(); userParams->i = this->GetObject()->GetId(); ENGINE->GetTween()->CancelScaleTween(this->touchIndicatorRef->GetId()); ENGINE->GetTween()->TweenToNumber(45.0f inRadians, 135.0f inRadians, 1.0f, true, true, true, "pulse", NUMBER_TWEEN_AFFILIATION_SCENEGRAPH_3D, userParams, playerUnitNumberTweenCallback); } void PlayerUnit::SetTouchIndicatorSprite(int index) { this->touchIndicatorRef->GetComponent<SpriteRenderer>()->SetCurrentTextureIndex(index); } void PlayerUnit::SetTouchIndicatorCell(GridCell* c) { this->touchIndicatorRef->GetTransform()->SetPosition(c->center); this->touchIndicatorRef->GetTransform()->Translate(0.01f + (c->y * 0.05), YAXIS); } void PlayerUnit::SetTouchIndicatorVisible(bool visibility) { this->touchIndicatorRef->SetVisible(visibility); } <|endoftext|>
<commit_before>#include "list.h" #include "list.cpp" #include "queue.h" #include "queue.cpp" #include "public_queue.h" #include <iostream> #include <cassert> #include <exception> #include <cstdlib> using namespace std; using namespace NP_ADT; //--------------------------------------------------------------------------- // driver to test list //--------------------------------------------------------------------------- int main(void) { try { CDLL<char> mylist(3, 'X'); CDLL<char> mylist2; CDLL<char> mylist3(mylist); CDLL<char> mylist4(mylist.begin(), mylist.end()); cout << "mylist: " << mylist << endl; cout << "mylist2: " << mylist2 << endl; cout << "mylist3: " << mylist3 << endl; cout << "mylist4: " << mylist4 << endl; mylist.push_front('Y'); mylist.push_front('Z'); cout << mylist.pop_front() << endl; mylist2 = mylist; // a copy cout << "mylist: " << mylist << endl; // create a new iterator pointing to the beginning of mylist CDLL<char>::iterator listit(mylist.begin()); cout << listit++->data << " "; cout << listit->data << endl; cout << "mylist: "; for (unsigned int i = 0; i < mylist.getSize(); i++) cout << mylist[i] << " "; cout << endl; cout << "mylist[1] = 'N';" << endl; mylist[1] = 'N'; cout << "mylist: " << mylist << endl; mylist.release(); cout << "mylist: " << mylist << endl; cout << "mylist2: " << mylist2 << endl; // Queue Pointer Tests PublicQueue<char> * myqueue = &PublicQueue<char>(3, 'X'); cout << "myqueue: " << *myqueue << endl; CDLL<char> * myqueue2 = &PublicQueue<char>(); cout << "myqueue2: " << *myqueue2 << endl; CDLL<char> * myqueue3 = &PublicQueue<char>(*myqueue); cout << "myqueue3: " << *myqueue3 << endl; CDLL<char> * myqueue4 = &PublicQueue<char>(myqueue->begin(), myqueue->end()); cout << "myqueue4: " << *myqueue4 << endl; char Y = 'Y', Z = 'Z'; myqueue->push(Y); myqueue->push(Z); cout << myqueue->pop() << endl; *myqueue2 = *myqueue; // a copy cout << "myqueue: " << myqueue << endl; // create a new iterator pointing to the beginning of mylist PublicQueue<char>::iterator queueit(mylist.begin()); cout << queueit++->data << " "; cout << queueit->data << endl; cout << "myqueue: "; for (unsigned int i = 0; i < myqueue->getSize(); i++) cout << (*myqueue)[i] << " "; cout << endl; cout << "myqueue[1] = 'N';" << endl; (*myqueue)[1] = 'N'; cout << "myqueue: " << myqueue << endl; mylist.release(); cout << "myqueue: " << myqueue << endl; cout << "myqueue2: " << myqueue2 << endl; } catch (exception e) { cerr << "program terminated: " << e.what() << endl; cin.get(); return EXIT_FAILURE; } cin.get(); // keep window open return EXIT_SUCCESS; }<commit_msg>comment header for main<commit_after>#include "list.h" #include "list.cpp" #include "queue.h" #include "queue.cpp" #include "public_queue.h" #include <iostream> #include <cassert> #include <exception> #include <cstdlib> using namespace std; using namespace NP_ADT; //------------------------------------------------------------------------- // Function: main // Description: show case of Queue/CDLL // Calls: All CDLL/Queue methods // Throws: catches all exceptions // History Log: // https://github.com/qwergram/CS133Assignment/blame/master/Project2/main.cpp // ------------------------------------------------------------------------ int main(void) { try { CDLL<char> mylist(3, 'X'); CDLL<char> mylist2; CDLL<char> mylist3(mylist); CDLL<char> mylist4(mylist.begin(), mylist.end()); cout << "mylist: " << mylist << endl; cout << "mylist2: " << mylist2 << endl; cout << "mylist3: " << mylist3 << endl; cout << "mylist4: " << mylist4 << endl; mylist.push_front('Y'); mylist.push_front('Z'); cout << mylist.pop_front() << endl; mylist2 = mylist; // a copy cout << "mylist: " << mylist << endl; // create a new iterator pointing to the beginning of mylist CDLL<char>::iterator listit(mylist.begin()); cout << listit++->data << " "; cout << listit->data << endl; cout << "mylist: "; for (unsigned int i = 0; i < mylist.getSize(); i++) cout << mylist[i] << " "; cout << endl; cout << "mylist[1] = 'N';" << endl; mylist[1] = 'N'; cout << "mylist: " << mylist << endl; mylist.release(); cout << "mylist: " << mylist << endl; cout << "mylist2: " << mylist2 << endl; // Queue Pointer Tests PublicQueue<char> * myqueue = &PublicQueue<char>(3, 'X'); cout << "myqueue: " << *myqueue << endl; CDLL<char> * myqueue2 = &PublicQueue<char>(); cout << "myqueue2: " << *myqueue2 << endl; CDLL<char> * myqueue3 = &PublicQueue<char>(*myqueue); cout << "myqueue3: " << *myqueue3 << endl; CDLL<char> * myqueue4 = &PublicQueue<char>(myqueue->begin(), myqueue->end()); cout << "myqueue4: " << *myqueue4 << endl; char Y = 'Y', Z = 'Z'; myqueue->push(Y); myqueue->push(Z); cout << myqueue->pop() << endl; *myqueue2 = *myqueue; // a copy cout << "myqueue: " << myqueue << endl; // create a new iterator pointing to the beginning of mylist PublicQueue<char>::iterator queueit(mylist.begin()); cout << queueit++->data << " "; cout << queueit->data << endl; cout << "myqueue: "; for (unsigned int i = 0; i < myqueue->getSize(); i++) cout << (*myqueue)[i] << " "; cout << endl; cout << "myqueue[1] = 'N';" << endl; (*myqueue)[1] = 'N'; cout << "myqueue: " << myqueue << endl; mylist.release(); cout << "myqueue: " << myqueue << endl; cout << "myqueue2: " << myqueue2 << endl; } catch (exception e) { cerr << "program terminated: " << e.what() << endl; cin.get(); return EXIT_FAILURE; } cin.get(); // keep window open return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tolayoutanchoredobjectposition.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-16 21:26:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _TOLAYOUTANCHOREDOBJECTPOSITION_HXX #include <tolayoutanchoredobjectposition.hxx> #endif #ifndef _ANCHOREDOBJECT_HXX #include <anchoredobject.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _SVX_SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FMTORNT_HXX #include <fmtornt.hxx> #endif #ifndef _FMTSRND_HXX #include <fmtsrnd.hxx> #endif #ifndef IDOCUMENTSETTINGACCESS_HXX_INCLUDED #include <IDocumentSettingAccess.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif using namespace objectpositioning; SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj ) : SwAnchoredObjectPosition( _rDrawObj ), maRelPos( Point() ), // --> OD 2004-06-17 #i26791# maOffsetToFrmAnchorPos( Point() ) {} SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition() {} /** calculate position for object position type TO_LAYOUT @author OD */ void SwToLayoutAnchoredObjectPosition::CalcPosition() { const SwRect aObjBoundRect( GetAnchoredObj().GetObjRect() ); SWRECTFN( (&GetAnchorFrm()) ); const SwFrmFmt& rFrmFmt = GetFrmFmt(); const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace(); const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace(); const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId(); // determine position. // 'vertical' and 'horizontal' position are calculated separately Point aRelPos; // calculate 'vertical' position SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() ); { // to-frame anchored objects are *only* vertical positioned centered or // bottom, if its wrap mode is 'throught' and its anchor frame has fixed // size. Otherwise, it's positioned top. SwVertOrient eVertOrient = aVert.GetVertOrient(); if ( ( bFlyAtFly && ( eVertOrient == VERT_CENTER || eVertOrient == VERT_BOTTOM ) && SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() && !GetAnchorFrm().HasFixSize() ) ) { eVertOrient = VERT_TOP; } // --> OD 2004-06-17 #i26791# - get vertical offset to frame anchor position. SwTwips nVertOffsetToFrmAnchorPos( 0L ); SwTwips nRelPosY = _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient, aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL, nVertOffsetToFrmAnchorPos ); // keep the calculated relative vertical position - needed for filters // (including the xml-filter) { SwTwips nAttrRelPosY = nRelPosY - nVertOffsetToFrmAnchorPos; if ( aVert.GetVertOrient() != VERT_NONE && aVert.GetPos() != nAttrRelPosY ) { aVert.SetPos( nAttrRelPosY ); const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } // determine absolute 'vertical' position, depending on layout-direction // --> OD 2004-06-17 #i26791# - determine offset to 'vertical' frame // anchor position, depending on layout-direction if( bVert ) { ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." ); aRelPos.X() = -nRelPosY - aObjBoundRect.Width(); maOffsetToFrmAnchorPos.X() = nVertOffsetToFrmAnchorPos; } else { aRelPos.Y() = nRelPosY; maOffsetToFrmAnchorPos.Y() = nVertOffsetToFrmAnchorPos; } // if in online-layout the bottom of to-page anchored object is beyond // the page bottom, the page frame has to grow by growing its body frame. if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() && rFrmFmt.getIDocumentSettingAccess()->get(IDocumentSettingAccess::BROWSE_MODE) ) { const long nAnchorBottom = GetAnchorFrm().Frm().Bottom(); const long nBottom = GetAnchorFrm().Frm().Top() + aRelPos.Y() + aObjBoundRect.Height(); if ( nAnchorBottom < nBottom ) { static_cast<SwPageFrm&>(GetAnchorFrm()). FindBodyCont()->Grow( nBottom - nAnchorBottom ); } } } // end of determination of vertical position // calculate 'horizontal' position SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() ); { // consider toggle of horizontal position for even pages. const bool bToggle = aHori.IsPosToggle() && !GetAnchorFrm().FindPageFrm()->OnRightPage(); SwHoriOrient eHoriOrient = aHori.GetHoriOrient(); SwRelationOrient eRelOrient = aHori.GetRelationOrient(); // toggle orientation _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient ); // determine alignment values: // <nWidth>: 'width' of the alignment area // <nOffset>: offset of alignment area, relative to 'left' of // frame anchor position SwTwips nWidth, nOffset; { bool bDummy; // in this context irrelevant output parameter _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(), eRelOrient, false, nWidth, nOffset, bDummy ); } SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)(); // determine relative horizontal position SwTwips nRelPosX; if ( HORI_NONE == eHoriOrient ) { if( bToggle || ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) ) { nRelPosX = nWidth - nObjWidth - aHori.GetPos(); } else { nRelPosX = aHori.GetPos(); } } else if ( HORI_CENTER == eHoriOrient ) nRelPosX = (nWidth / 2) - (nObjWidth / 2); else if ( HORI_RIGHT == eHoriOrient ) nRelPosX = nWidth - ( nObjWidth + ( bVert ? rUL.GetLower() : rLR.GetRight() ) ); else nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft(); nRelPosX += nOffset; // no 'negative' relative horizontal position // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for // to frame anchored objects. if ( !bFlyAtFly && nRelPosX < 0 ) { nRelPosX = 0; } // determine absolute 'horizontal' position, depending on layout-direction // --> OD 2004-06-17 #i26791# - determine offset to 'horizontal' frame // anchor position, depending on layout-direction if ( bVert ) { aRelPos.Y() = nRelPosX; maOffsetToFrmAnchorPos.Y() = nOffset; } else { aRelPos.X() = nRelPosX; maOffsetToFrmAnchorPos.X() = nOffset; } // keep the calculated relative horizontal position - needed for filters // (including the xml-filter) { SwTwips nAttrRelPosX = nRelPosX - nOffset; if ( HORI_NONE != aHori.GetHoriOrient() && aHori.GetPos() != nAttrRelPosX ) { aHori.SetPos( nAttrRelPosX ); const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } } // end of determination of horizontal position // keep calculate relative position maRelPos = aRelPos; } /** calculated relative position for object position @author OD */ Point SwToLayoutAnchoredObjectPosition::GetRelPos() const { return maRelPos; } /** determined offset to frame anchor position --> OD 2004-06-17 #i26791# @author OD */ Point SwToLayoutAnchoredObjectPosition::GetOffsetToFrmAnchorPos() const { return maOffsetToFrmAnchorPos; } <commit_msg>INTEGRATION: CWS os94 (1.9.246); FILE MERGED 2007/03/12 08:10:44 os 1.9.246.1: #i75235# unused methods removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tolayoutanchoredobjectposition.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-25 09:09:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _TOLAYOUTANCHOREDOBJECTPOSITION_HXX #include <tolayoutanchoredobjectposition.hxx> #endif #ifndef _ANCHOREDOBJECT_HXX #include <anchoredobject.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _SVX_SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FMTORNT_HXX #include <fmtornt.hxx> #endif #ifndef _FMTSRND_HXX #include <fmtsrnd.hxx> #endif #ifndef IDOCUMENTSETTINGACCESS_HXX_INCLUDED #include <IDocumentSettingAccess.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef _SVX_ULSPITEM_HXX #include <svx/ulspitem.hxx> #endif using namespace objectpositioning; SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj ) : SwAnchoredObjectPosition( _rDrawObj ), maRelPos( Point() ), // --> OD 2004-06-17 #i26791# maOffsetToFrmAnchorPos( Point() ) {} SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition() {} /** calculate position for object position type TO_LAYOUT @author OD */ void SwToLayoutAnchoredObjectPosition::CalcPosition() { const SwRect aObjBoundRect( GetAnchoredObj().GetObjRect() ); SWRECTFN( (&GetAnchorFrm()) ); const SwFrmFmt& rFrmFmt = GetFrmFmt(); const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace(); const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace(); const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId(); // determine position. // 'vertical' and 'horizontal' position are calculated separately Point aRelPos; // calculate 'vertical' position SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() ); { // to-frame anchored objects are *only* vertical positioned centered or // bottom, if its wrap mode is 'throught' and its anchor frame has fixed // size. Otherwise, it's positioned top. SwVertOrient eVertOrient = aVert.GetVertOrient(); if ( ( bFlyAtFly && ( eVertOrient == VERT_CENTER || eVertOrient == VERT_BOTTOM ) && SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() && !GetAnchorFrm().HasFixSize() ) ) { eVertOrient = VERT_TOP; } // --> OD 2004-06-17 #i26791# - get vertical offset to frame anchor position. SwTwips nVertOffsetToFrmAnchorPos( 0L ); SwTwips nRelPosY = _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient, aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL, nVertOffsetToFrmAnchorPos ); // keep the calculated relative vertical position - needed for filters // (including the xml-filter) { SwTwips nAttrRelPosY = nRelPosY - nVertOffsetToFrmAnchorPos; if ( aVert.GetVertOrient() != VERT_NONE && aVert.GetPos() != nAttrRelPosY ) { aVert.SetPos( nAttrRelPosY ); const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } // determine absolute 'vertical' position, depending on layout-direction // --> OD 2004-06-17 #i26791# - determine offset to 'vertical' frame // anchor position, depending on layout-direction if( bVert ) { ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." ); aRelPos.X() = -nRelPosY - aObjBoundRect.Width(); maOffsetToFrmAnchorPos.X() = nVertOffsetToFrmAnchorPos; } else { aRelPos.Y() = nRelPosY; maOffsetToFrmAnchorPos.Y() = nVertOffsetToFrmAnchorPos; } // if in online-layout the bottom of to-page anchored object is beyond // the page bottom, the page frame has to grow by growing its body frame. if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() && rFrmFmt.getIDocumentSettingAccess()->get(IDocumentSettingAccess::BROWSE_MODE) ) { const long nAnchorBottom = GetAnchorFrm().Frm().Bottom(); const long nBottom = GetAnchorFrm().Frm().Top() + aRelPos.Y() + aObjBoundRect.Height(); if ( nAnchorBottom < nBottom ) { static_cast<SwPageFrm&>(GetAnchorFrm()). FindBodyCont()->Grow( nBottom - nAnchorBottom ); } } } // end of determination of vertical position // calculate 'horizontal' position SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() ); { // consider toggle of horizontal position for even pages. const bool bToggle = aHori.IsPosToggle() && !GetAnchorFrm().FindPageFrm()->OnRightPage(); SwHoriOrient eHoriOrient = aHori.GetHoriOrient(); SwRelationOrient eRelOrient = aHori.GetRelationOrient(); // toggle orientation _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient ); // determine alignment values: // <nWidth>: 'width' of the alignment area // <nOffset>: offset of alignment area, relative to 'left' of // frame anchor position SwTwips nWidth, nOffset; { bool bDummy; // in this context irrelevant output parameter _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(), eRelOrient, false, nWidth, nOffset, bDummy ); } SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)(); // determine relative horizontal position SwTwips nRelPosX; if ( HORI_NONE == eHoriOrient ) { if( bToggle || ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) ) { nRelPosX = nWidth - nObjWidth - aHori.GetPos(); } else { nRelPosX = aHori.GetPos(); } } else if ( HORI_CENTER == eHoriOrient ) nRelPosX = (nWidth / 2) - (nObjWidth / 2); else if ( HORI_RIGHT == eHoriOrient ) nRelPosX = nWidth - ( nObjWidth + ( bVert ? rUL.GetLower() : rLR.GetRight() ) ); else nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft(); nRelPosX += nOffset; // no 'negative' relative horizontal position // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for // to frame anchored objects. if ( !bFlyAtFly && nRelPosX < 0 ) { nRelPosX = 0; } // determine absolute 'horizontal' position, depending on layout-direction // --> OD 2004-06-17 #i26791# - determine offset to 'horizontal' frame // anchor position, depending on layout-direction if ( bVert ) { aRelPos.Y() = nRelPosX; maOffsetToFrmAnchorPos.Y() = nOffset; } else { aRelPos.X() = nRelPosX; maOffsetToFrmAnchorPos.X() = nOffset; } // keep the calculated relative horizontal position - needed for filters // (including the xml-filter) { SwTwips nAttrRelPosX = nRelPosX - nOffset; if ( HORI_NONE != aHori.GetHoriOrient() && aHori.GetPos() != nAttrRelPosX ) { aHori.SetPos( nAttrRelPosX ); const_cast<SwFrmFmt&>(rFrmFmt).LockModify(); const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori ); const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify(); } } } // end of determination of horizontal position // keep calculate relative position maRelPos = aRelPos; } /** calculated relative position for object position @author OD */ Point SwToLayoutAnchoredObjectPosition::GetRelPos() const { return maRelPos; } <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvbonjoureventloop.h" #ifdef HAVE_BONJOUR #include "vvdebugmsg.h" #include "vvpthread.h" #include "vvsocketmonitor.h" #include "vvtcpsocket.h" struct Thread { pthread_t _pthread; }; vvBonjourEventLoop::vvBonjourEventLoop(DNSServiceRef service) { _thread = new Thread; _dnsServiceRef = service; } vvBonjourEventLoop::~vvBonjourEventLoop() { if(_dnsServiceRef) DNSServiceRefDeallocate(_dnsServiceRef); delete _thread; } void vvBonjourEventLoop::run(bool inThread, double timeout) { _timeout = timeout; _noMoreFlags = false; if(inThread == false) { loop(this); _dnsServiceRef = NULL; } else { pthread_create(&(_thread->_pthread), NULL, loop, this); } } void * vvBonjourEventLoop::loop(void * attrib) { vvDebugMsg::msg(3, "vvBonjourEventLoop::loop()"); vvBonjourEventLoop *instance = reinterpret_cast<vvBonjourEventLoop*>(attrib); instance->_run = true; int dns_sd_fd = DNSServiceRefSockFD(instance->_dnsServiceRef); vvTcpSocket sock = vvTcpSocket(); sock.setSockfd(dns_sd_fd); std::vector<vvSocket*> sockets; sockets.push_back(&sock); vvSocketMonitor socketMonitor; socketMonitor.setReadFds(sockets); while (instance->_run) { vvSocket *ready; double to = instance->_timeout; vvSocketMonitor::ErrorType smErr = socketMonitor.wait(&ready, &to); if (smErr == vvSocketMonitor::VV_OK) { DNSServiceErrorType err = DNSServiceProcessResult(instance->_dnsServiceRef); switch(err) { case kDNSServiceErr_NoError: continue; break; case kDNSServiceErr_NoSuchName: vvDebugMsg::msg(1, "DNSServiceProcessResult() Given name does not exist"); break; case kDNSServiceErr_NoMemory: vvDebugMsg::msg(1, "DNSServiceProcessResult() Out of memory"); break; case kDNSServiceErr_BadParam: vvDebugMsg::msg(1, "DNSServiceProcessResult() Parameter contains invalid data"); break; case kDNSServiceErr_BadReference: vvDebugMsg::msg(1, "DNSServiceProcessResult() Reference being passed is invalid"); break; case kDNSServiceErr_BadState: vvDebugMsg::msg(1, "DNSServiceProcessResult() Internal error"); break; case kDNSServiceErr_BadFlags: vvDebugMsg::msg(1, "DNSServiceProcessResult() Invalid values for flags"); break; case kDNSServiceErr_Unsupported: vvDebugMsg::msg(1, "DNSServiceProcessResult() Operation not supported"); break; case kDNSServiceErr_NotInitialized: vvDebugMsg::msg(1, "DNSServiceProcessResult() Reference not initialized"); break; case kDNSServiceErr_AlreadyRegistered: vvDebugMsg::msg(1, "DNSServiceProcessResult() Attempt to register a service that is registered"); break; case kDNSServiceErr_NameConflict: vvDebugMsg::msg(1, "DNSServiceProcessResult() Attempt to register a service with an already used name"); break; case kDNSServiceErr_Invalid: vvDebugMsg::msg(1, "DNSServiceProcessResult() Certain invalid parameter data, such as domain name more than 255 bytes long"); break; case kDNSServiceErr_Incompatible: vvDebugMsg::msg(1, "DNSServiceProcessResult() Client library incompatible with daemon"); break; case kDNSServiceErr_BadInterfaceIndex: vvDebugMsg::msg(1, "DNSServiceProcessResult() Specified interface does not exist"); break; case kDNSServiceErr_Unknown: default: vvDebugMsg::msg(1, "DNSServiceProcessResult() unknown error"); break; } // did not "continue", so error occured -> break! break; } else if(smErr == vvSocketMonitor::VV_TIMEOUT) { vvDebugMsg::msg(1, "vvBonjourEventLoop::loop() timeout reached"); break; } else { vvDebugMsg::msg(1, "vvBonjourEventLoop::loop() socketmonitor returned error"); break; } } return NULL; } void vvBonjourEventLoop::stop() { vvDebugMsg::msg(3, "vvBonjourEventLoop::stop()"); _run = false; } #endif // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>bugfixes bonjoureventloop<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvbonjoureventloop.h" #ifdef HAVE_BONJOUR #include "vvdebugmsg.h" #include "vvpthread.h" #include "vvsocketmonitor.h" #include "vvtcpsocket.h" struct Thread { pthread_t _pthread; }; vvBonjourEventLoop::vvBonjourEventLoop(DNSServiceRef service) { _thread = new Thread; _thread->_pthread = NULL; _dnsServiceRef = service; } vvBonjourEventLoop::~vvBonjourEventLoop() { if(_thread->_pthread) { pthread_join(_thread->_pthread, NULL); } delete _thread; } void vvBonjourEventLoop::run(bool inThread, double timeout) { _timeout = timeout; _noMoreFlags = false; if(inThread == false) { loop(this); _dnsServiceRef = NULL; } else { pthread_create(&(_thread->_pthread), NULL, loop, this); } } void * vvBonjourEventLoop::loop(void * attrib) { vvDebugMsg::msg(3, "vvBonjourEventLoop::loop()"); vvBonjourEventLoop *instance = reinterpret_cast<vvBonjourEventLoop*>(attrib); instance->_run = true; int dns_sd_fd = DNSServiceRefSockFD(instance->_dnsServiceRef); vvTcpSocket sock = vvTcpSocket(); sock.setSockfd(dns_sd_fd); std::vector<vvSocket*> sockets; sockets.push_back(&sock); vvSocketMonitor socketMonitor; socketMonitor.setReadFds(sockets); while (instance->_run) { vvSocket *ready; double to = instance->_timeout; vvSocketMonitor::ErrorType smErr = socketMonitor.wait(&ready, &to); if (smErr == vvSocketMonitor::VV_OK) { DNSServiceErrorType err = DNSServiceProcessResult(instance->_dnsServiceRef); switch(err) { case kDNSServiceErr_NoError: continue; break; case kDNSServiceErr_NoSuchName: vvDebugMsg::msg(1, "DNSServiceProcessResult() Given name does not exist"); break; case kDNSServiceErr_NoMemory: vvDebugMsg::msg(1, "DNSServiceProcessResult() Out of memory"); break; case kDNSServiceErr_BadParam: vvDebugMsg::msg(1, "DNSServiceProcessResult() Parameter contains invalid data"); break; case kDNSServiceErr_BadReference: vvDebugMsg::msg(1, "DNSServiceProcessResult() Reference being passed is invalid"); break; case kDNSServiceErr_BadState: vvDebugMsg::msg(1, "DNSServiceProcessResult() Internal error"); break; case kDNSServiceErr_BadFlags: vvDebugMsg::msg(1, "DNSServiceProcessResult() Invalid values for flags"); break; case kDNSServiceErr_Unsupported: vvDebugMsg::msg(1, "DNSServiceProcessResult() Operation not supported"); break; case kDNSServiceErr_NotInitialized: vvDebugMsg::msg(1, "DNSServiceProcessResult() Reference not initialized"); break; case kDNSServiceErr_AlreadyRegistered: vvDebugMsg::msg(1, "DNSServiceProcessResult() Attempt to register a service that is registered"); break; case kDNSServiceErr_NameConflict: vvDebugMsg::msg(1, "DNSServiceProcessResult() Attempt to register a service with an already used name"); break; case kDNSServiceErr_Invalid: vvDebugMsg::msg(1, "DNSServiceProcessResult() Certain invalid parameter data, such as domain name more than 255 bytes long"); break; case kDNSServiceErr_Incompatible: vvDebugMsg::msg(1, "DNSServiceProcessResult() Client library incompatible with daemon"); break; case kDNSServiceErr_BadInterfaceIndex: vvDebugMsg::msg(1, "DNSServiceProcessResult() Specified interface does not exist"); break; case kDNSServiceErr_Unknown: default: vvDebugMsg::msg(1, "DNSServiceProcessResult() unknown error"); break; } // did not "continue", so error occured -> break! break; } else if(smErr == vvSocketMonitor::VV_TIMEOUT) { vvDebugMsg::msg(1, "vvBonjourEventLoop::loop() timeout reached"); break; } else { vvDebugMsg::msg(1, "vvBonjourEventLoop::loop() socketmonitor returned error"); break; } } return NULL; } void vvBonjourEventLoop::stop() { vvDebugMsg::msg(3, "vvBonjourEventLoop::stop()"); _run = false; } #endif // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDirector // // // // This class is used to 'drive' and hold a serie of TBranchProxy objects // // which represent and give access to the content of TTree object. // // This is intended to be used as part of a generate Selector class // // which will hold the directory and its associate // // // //////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDirector.h" #include "TBranchProxy.h" #include "TFriendProxy.h" #include "TTree.h" #include "TEnv.h" #include "TH1F.h" #include "TPad.h" #include "TList.h" #include <algorithm> namespace std {} using namespace std; ClassImp(ROOT::TBranchProxyDirector); namespace ROOT { // Helper function to call Reset on each TBranchProxy void Reset(TBranchProxy *x) { x->Reset(); } // Helper function to call SetReadEntry on all TFriendProxy void ResetReadEntry(TFriendProxy *x) { x->ResetReadEntry(); } // Helper class to call Update on all TFriendProxy struct Update { Update(TTree *newtree) : fNewTree(newtree) {} TTree *fNewTree; void operator()(TFriendProxy *x) { x->Update(fNewTree); } }; TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Long64_t i) : fTree(tree), fEntry(i) { // Simple constructor } TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Int_t i) : // cint has a problem casting int to long long fTree(tree), fEntry(i) { // Simple constructor } void TBranchProxyDirector::Attach(TBranchProxy* p) { // Attach a TBranchProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fDirected.push_back(p); } void TBranchProxyDirector::Attach(TFriendProxy* p) { // Attach a TFriendProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fFriends.push_back(p); } TH1F* TBranchProxyDirector::CreateHistogram(const char *options) { // Create a temporary 1D histogram. Int_t nbins = gEnv->GetValue("Hist.Binning.1D.x",100); Double_t vmin=0, vmax=0; Double_t xmin=0, xmax=0; Bool_t canRebin = kFALSE; TString opt( options ); Bool_t optSame = opt.Contains("same"); if (gPad && optSame) { TListIter np(gPad->GetListOfPrimitives()); TObject *op; TH1 *oldhtemp = 0; while ((op = np()) && !oldhtemp) { if (op->InheritsFrom(TH1::Class())) oldhtemp = (TH1 *)op; } if (oldhtemp) { nbins = oldhtemp->GetXaxis()->GetNbins(); vmin = oldhtemp->GetXaxis()->GetXmin(); vmax = oldhtemp->GetXaxis()->GetXmax(); } else { vmin = gPad->GetUxmin(); vmax = gPad->GetUxmax(); } } else { vmin = xmin; vmax = xmax; if (xmin < xmax) canRebin = kFALSE; } TH1F *hist = new TH1F("htemp","htemp",nbins,vmin,vmax); hist->SetLineColor(fTree->GetLineColor()); hist->SetLineWidth(fTree->GetLineWidth()); hist->SetLineStyle(fTree->GetLineStyle()); hist->SetFillColor(fTree->GetFillColor()); hist->SetFillStyle(fTree->GetFillStyle()); hist->SetMarkerStyle(fTree->GetMarkerStyle()); hist->SetMarkerColor(fTree->GetMarkerColor()); hist->SetMarkerSize(fTree->GetMarkerSize()); if (canRebin) hist->SetBit(TH1::kCanRebin); hist->GetXaxis()->SetTitle("var"); hist->SetBit(kCanDelete); hist->SetDirectory(0); if (opt.Length() && opt.Contains("e")) hist->Sumw2(); return hist; } void TBranchProxyDirector::SetReadEntry(Long64_t entry) { // move to a new entry to read fEntry = entry; if (!fFriends.empty()) { for_each(fFriends.begin(),fFriends.end(),ResetReadEntry); } } TTree* TBranchProxyDirector::SetTree(TTree *newtree) { // Set the BranchProxy to be looking at a new tree. // Reset all. // Return the old tree. TTree* oldtree = fTree; fTree = newtree; fEntry = -1; //if (fInitialized) fInitialized = setup(); //fprintf(stderr,"calling SetTree for %p\n",this); for_each(fDirected.begin(),fDirected.end(),Reset); Update update(fTree); for_each(fFriends.begin(),fFriends.end(),update); return oldtree; } } // namespace ROOT <commit_msg>Fix cov 11532 (deadcode) by turning on the auto-rebinning of the default histogram in MakeProxy<commit_after>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDirector // // // // This class is used to 'drive' and hold a serie of TBranchProxy objects // // which represent and give access to the content of TTree object. // // This is intended to be used as part of a generate Selector class // // which will hold the directory and its associate // // // //////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDirector.h" #include "TBranchProxy.h" #include "TFriendProxy.h" #include "TTree.h" #include "TEnv.h" #include "TH1F.h" #include "TPad.h" #include "TList.h" #include <algorithm> namespace std {} using namespace std; ClassImp(ROOT::TBranchProxyDirector); namespace ROOT { // Helper function to call Reset on each TBranchProxy void Reset(TBranchProxy *x) { x->Reset(); } // Helper function to call SetReadEntry on all TFriendProxy void ResetReadEntry(TFriendProxy *x) { x->ResetReadEntry(); } // Helper class to call Update on all TFriendProxy struct Update { Update(TTree *newtree) : fNewTree(newtree) {} TTree *fNewTree; void operator()(TFriendProxy *x) { x->Update(fNewTree); } }; TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Long64_t i) : fTree(tree), fEntry(i) { // Simple constructor } TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Int_t i) : // cint has a problem casting int to long long fTree(tree), fEntry(i) { // Simple constructor } void TBranchProxyDirector::Attach(TBranchProxy* p) { // Attach a TBranchProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fDirected.push_back(p); } void TBranchProxyDirector::Attach(TFriendProxy* p) { // Attach a TFriendProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fFriends.push_back(p); } TH1F* TBranchProxyDirector::CreateHistogram(const char *options) { // Create a temporary 1D histogram. Int_t nbins = gEnv->GetValue("Hist.Binning.1D.x",100); Double_t vmin=0, vmax=0; Double_t xmin=0, xmax=0; Bool_t canRebin = kTRUE; TString opt( options ); Bool_t optSame = opt.Contains("same"); if (optSame) canRebin = kFALSE; if (gPad && optSame) { TListIter np(gPad->GetListOfPrimitives()); TObject *op; TH1 *oldhtemp = 0; while ((op = np()) && !oldhtemp) { if (op->InheritsFrom(TH1::Class())) oldhtemp = (TH1 *)op; } if (oldhtemp) { nbins = oldhtemp->GetXaxis()->GetNbins(); vmin = oldhtemp->GetXaxis()->GetXmin(); vmax = oldhtemp->GetXaxis()->GetXmax(); } else { vmin = gPad->GetUxmin(); vmax = gPad->GetUxmax(); } } else { vmin = xmin; vmax = xmax; if (xmin < xmax) canRebin = kFALSE; } TH1F *hist = new TH1F("htemp","htemp",nbins,vmin,vmax); hist->SetLineColor(fTree->GetLineColor()); hist->SetLineWidth(fTree->GetLineWidth()); hist->SetLineStyle(fTree->GetLineStyle()); hist->SetFillColor(fTree->GetFillColor()); hist->SetFillStyle(fTree->GetFillStyle()); hist->SetMarkerStyle(fTree->GetMarkerStyle()); hist->SetMarkerColor(fTree->GetMarkerColor()); hist->SetMarkerSize(fTree->GetMarkerSize()); if (canRebin) hist->SetBit(TH1::kCanRebin); hist->GetXaxis()->SetTitle("var"); hist->SetBit(kCanDelete); hist->SetDirectory(0); if (opt.Length() && opt.Contains("e")) hist->Sumw2(); return hist; } void TBranchProxyDirector::SetReadEntry(Long64_t entry) { // move to a new entry to read fEntry = entry; if (!fFriends.empty()) { for_each(fFriends.begin(),fFriends.end(),ResetReadEntry); } } TTree* TBranchProxyDirector::SetTree(TTree *newtree) { // Set the BranchProxy to be looking at a new tree. // Reset all. // Return the old tree. TTree* oldtree = fTree; fTree = newtree; fEntry = -1; //if (fInitialized) fInitialized = setup(); //fprintf(stderr,"calling SetTree for %p\n",this); for_each(fDirected.begin(),fDirected.end(),Reset); Update update(fTree); for_each(fFriends.begin(),fFriends.end(),update); return oldtree; } } // namespace ROOT <|endoftext|>
<commit_before>/** * This file is part of stsw_proxy_source, which belongs to StreamSwitch * project. * * Copyright (C) 2014 OpenSight (www.opensight.cn) * * StreamSwitch is an extensible and scalable media stream server for * multi-protocol environment. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero 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, see <http://www.gnu.org/licenses/>. **/ /** * stsw_main.cc * stsw_proxy_source program main entry file * * author: jamken * date: 2015-7-8 **/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stream_switch.h> #include "stsw_stream_proxy.h" #include "stsw_log.h" /////////////////////////////////////////////////////////////// //Type ////////////////////////////////////////////////////////////// //global variables /////////////////////////////////////////////////////////////// //macro /////////////////////////////////////////////////////////////// //functions void ParseArgv(int argc, char *argv[], stream_switch::ArgParser *parser) { int ret = 0; std::string err_info; parser->RegisterBasicOptions(); parser->RegisterSourceOptions(); parser->UnregisterOption("queue-size"); parser->RegisterOption("url", 'u', OPTION_FLAG_REQUIRED | OPTION_FLAG_WITH_ARG, "URL", "URL is the stsw url (begin wiht stsw://) of the back-end source which this proxy to read from", NULL, NULL); parser->RegisterOption("pub-queue-size", 0, OPTION_FLAG_WITH_ARG | OPTION_FLAG_LONG, "NUM", "the size of the message queue for Publisher, 0 means no limit." "Default is an internal value determined when compiling", NULL, NULL); parser->RegisterOption("sub-queue-size", 0, OPTION_FLAG_WITH_ARG | OPTION_FLAG_LONG, "NUM", "the size of the message queue for Subscriber, 0 means no limit." "Default is an internal value determined when compiling", NULL, NULL); parser->RegisterOption("debug-flags", 'd', OPTION_FLAG_LONG | OPTION_FLAG_WITH_ARG, "FLAG", "debug flag for stream_switch core library. " "Default is 0, means no debug dump" , NULL, NULL); ret = parser->Parse(argc, argv, &err_info);//parse the cmd args if(ret){ fprintf(stderr, "Option Parsing Error:%s\n", err_info.c_str()); exit(-1); } //check options correct if(parser->CheckOption("help")){ std::string option_help; option_help = parser->GetOptionsHelp(); fprintf(stderr, "A proxy source which is used to relay the media stream from the other live source\n" "Usange: %s [options]\n" "\n" "Option list:\n" "%s" "\n" "User can send SIGINT/SIGTERM signal to terminate this proxy\n" "\n", "stsw_proxy_source", option_help.c_str()); exit(0); }else if(parser->CheckOption("version")){ fprintf(stderr, PACKAGE_VERSION"\n"); exit(0); } if(parser->CheckOption("log-file")){ if(!parser->CheckOption("log-size")){ fprintf(stderr, "log-size must be set if log-file is enabled\n"); exit(-1); } } } /////////////////////////////////////////////////////////////// //main entry int main(int argc, char *argv[]) { using namespace stream_switch; int ret = 0; StreamProxySource * proxy = NULL; int pub_queue_size = STSW_PUBLISH_SOCKET_HWM; int sub_queue_size = STSW_SUBSCRIBE_SOCKET_HWM; GlobalInit(); //parse the cmd line ArgParser parser; ParseArgv(argc, argv, &parser); // parse the cmd line // // init global logger if(parser.CheckOption(std::string("log-file"))){ //init the global logger std::string log_file = parser.OptionValue("log-file", ""); int log_size = strtol(parser.OptionValue("log-size", "0").c_str(), NULL, 0); int rotate_num = strtol(parser.OptionValue("log-rotate", "0").c_str(), NULL, 0); int log_level = LOG_LEVEL_DEBUG; ret = InitGlobalLogger(log_file, log_size, rotate_num, log_level); if(ret){ fprintf(stderr, "Init Logger failed, exit\n"); goto exit_1; } } // //init source proxy = StreamProxySource::Instance(); if(parser.CheckOption("pub-queue-size")){ pub_queue_size = (int)strtol(parser.OptionValue("pub-queue-size", "60").c_str(), NULL, 0); } if(parser.CheckOption("sub-queue-size")){ sub_queue_size = (int)strtol(parser.OptionValue("sub-queue-size", "120").c_str(), NULL, 0); } ret = proxy->Init( parser.OptionValue("url", ""), parser.OptionValue("stream-name", ""), (int)strtol(parser.OptionValue("port", "0").c_str(), NULL, 0), sub_queue_size, pub_queue_size, (int)strtol(parser.OptionValue("debug-flags", "0").c_str(), NULL, 0)); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy init error, exit\n"); goto exit_2; } //setup metadata ret = proxy->UpdateStreamMetaData(5000, NULL); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy UpdateStreamMetaData error, exit\n"); goto exit_3; } //start proxy ret = proxy->Start(); if(ret){ goto exit_3; } //drive the proxy heartbeat while(1){ if(isGlobalInterrupt()){ STDERR_LOG(stream_switch::LOG_LEVEL_INFO, "Receive Terminate Signal, exit\n"); ret = 0; break; } ret = proxy->Hearbeat(); if(ret){ //error STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy hearbeat error, exit\n"); break; } usleep(100000); //100 ms } //stop proxy proxy->Stop(); exit_3: //uninit proxy proxy->Uninit(); //uninstance StreamProxySource::Uninstance(); exit_2: //uninit logger UninitGlobalLogger(); exit_1: //streamswitch library uninit GlobalUninit(); return ret; } <commit_msg>use nanosleep instead of usleep, nanosleep can be interrupted by a signal, so that can exit more quickly<commit_after>/** * This file is part of stsw_proxy_source, which belongs to StreamSwitch * project. * * Copyright (C) 2014 OpenSight (www.opensight.cn) * * StreamSwitch is an extensible and scalable media stream server for * multi-protocol environment. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero 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, see <http://www.gnu.org/licenses/>. **/ /** * stsw_main.cc * stsw_proxy_source program main entry file * * author: jamken * date: 2015-7-8 **/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <stream_switch.h> #include "stsw_stream_proxy.h" #include "stsw_log.h" /////////////////////////////////////////////////////////////// //Type ////////////////////////////////////////////////////////////// //global variables /////////////////////////////////////////////////////////////// //macro /////////////////////////////////////////////////////////////// //functions void ParseArgv(int argc, char *argv[], stream_switch::ArgParser *parser) { int ret = 0; std::string err_info; parser->RegisterBasicOptions(); parser->RegisterSourceOptions(); parser->UnregisterOption("queue-size"); parser->RegisterOption("url", 'u', OPTION_FLAG_REQUIRED | OPTION_FLAG_WITH_ARG, "URL", "URL is the stsw url (begin wiht stsw://) of the back-end source which this proxy to read from", NULL, NULL); parser->RegisterOption("pub-queue-size", 0, OPTION_FLAG_WITH_ARG | OPTION_FLAG_LONG, "NUM", "the size of the message queue for Publisher, 0 means no limit." "Default is an internal value determined when compiling", NULL, NULL); parser->RegisterOption("sub-queue-size", 0, OPTION_FLAG_WITH_ARG | OPTION_FLAG_LONG, "NUM", "the size of the message queue for Subscriber, 0 means no limit." "Default is an internal value determined when compiling", NULL, NULL); parser->RegisterOption("debug-flags", 'd', OPTION_FLAG_LONG | OPTION_FLAG_WITH_ARG, "FLAG", "debug flag for stream_switch core library. " "Default is 0, means no debug dump" , NULL, NULL); ret = parser->Parse(argc, argv, &err_info);//parse the cmd args if(ret){ fprintf(stderr, "Option Parsing Error:%s\n", err_info.c_str()); exit(-1); } //check options correct if(parser->CheckOption("help")){ std::string option_help; option_help = parser->GetOptionsHelp(); fprintf(stderr, "A proxy source which is used to relay the media stream from the other live source\n" "Usange: %s [options]\n" "\n" "Option list:\n" "%s" "\n" "User can send SIGINT/SIGTERM signal to terminate this proxy\n" "\n", "stsw_proxy_source", option_help.c_str()); exit(0); }else if(parser->CheckOption("version")){ fprintf(stderr, PACKAGE_VERSION"\n"); exit(0); } if(parser->CheckOption("log-file")){ if(!parser->CheckOption("log-size")){ fprintf(stderr, "log-size must be set if log-file is enabled\n"); exit(-1); } } } /////////////////////////////////////////////////////////////// //main entry int main(int argc, char *argv[]) { using namespace stream_switch; int ret = 0; StreamProxySource * proxy = NULL; int pub_queue_size = STSW_PUBLISH_SOCKET_HWM; int sub_queue_size = STSW_SUBSCRIBE_SOCKET_HWM; GlobalInit(); //parse the cmd line ArgParser parser; ParseArgv(argc, argv, &parser); // parse the cmd line // // init global logger if(parser.CheckOption(std::string("log-file"))){ //init the global logger std::string log_file = parser.OptionValue("log-file", ""); int log_size = strtol(parser.OptionValue("log-size", "0").c_str(), NULL, 0); int rotate_num = strtol(parser.OptionValue("log-rotate", "0").c_str(), NULL, 0); int log_level = LOG_LEVEL_DEBUG; ret = InitGlobalLogger(log_file, log_size, rotate_num, log_level); if(ret){ fprintf(stderr, "Init Logger failed, exit\n"); goto exit_1; } } // //init source proxy = StreamProxySource::Instance(); if(parser.CheckOption("pub-queue-size")){ pub_queue_size = (int)strtol(parser.OptionValue("pub-queue-size", "60").c_str(), NULL, 0); } if(parser.CheckOption("sub-queue-size")){ sub_queue_size = (int)strtol(parser.OptionValue("sub-queue-size", "120").c_str(), NULL, 0); } ret = proxy->Init( parser.OptionValue("url", ""), parser.OptionValue("stream-name", ""), (int)strtol(parser.OptionValue("port", "0").c_str(), NULL, 0), sub_queue_size, pub_queue_size, (int)strtol(parser.OptionValue("debug-flags", "0").c_str(), NULL, 0)); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy init error, exit\n"); goto exit_2; } //setup metadata ret = proxy->UpdateStreamMetaData(5000, NULL); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy UpdateStreamMetaData error, exit\n"); goto exit_3; } //start proxy ret = proxy->Start(); if(ret){ goto exit_3; } //drive the proxy heartbeat while(1){ if(isGlobalInterrupt()){ STDERR_LOG(stream_switch::LOG_LEVEL_INFO, "Receive Terminate Signal, exit\n"); ret = 0; break; } ret = proxy->Hearbeat(); if(ret){ //error STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Proxy hearbeat error, exit\n"); break; } { struct timespec req; req.tv_sec = 0; req.tv_nsec = 100000000; //10ms nanosleep(&req, NULL); } } //stop proxy proxy->Stop(); exit_3: //uninit proxy proxy->Uninit(); //uninstance StreamProxySource::Uninstance(); exit_2: //uninit logger UninitGlobalLogger(); exit_1: //streamswitch library uninit GlobalUninit(); return ret; } <|endoftext|>
<commit_before>#ifndef __PBF_HPP__ #define __PBF_HPP__ /* * Some parts are from upb - a minimalist implementation of protocol buffers. * * Copyright (c) 2008-2011 Google Inc. See LICENSE for details. * Author: Josh Haberman <jhaberman@gmail.com> */ #include <stdint.h> #include <stdexcept> #include <string> #include <cstring> #include <cassert> #undef LIKELY #undef UNLIKELY #if defined(__GNUC__) && __GNUC__ >= 4 #define LIKELY(x) (__builtin_expect((x), 1)) #define UNLIKELY(x) (__builtin_expect((x), 0)) #else #define LIKELY(x) (x) #define UNLIKELY(x) (x) #endif namespace protobuf { #define FORCEINLINE inline __attribute__((always_inline)) #define NOINLINE __attribute__((noinline)) #define PBF_INLINE FORCEINLINE class message { typedef const char * value_type; value_type data_; value_type end_; public: uint64_t value; uint32_t tag; PBF_INLINE message(value_type data, std::size_t length); PBF_INLINE bool next(); PBF_INLINE uint64_t varint(); PBF_INLINE uint64_t varint2(); PBF_INLINE int64_t svarint(); PBF_INLINE std::string string(); PBF_INLINE float float32(); PBF_INLINE double float64(); PBF_INLINE int64_t int64(); PBF_INLINE bool boolean(); PBF_INLINE void skip(); PBF_INLINE void skipValue(uint64_t val); PBF_INLINE void skipBytes(uint64_t bytes); PBF_INLINE value_type getData(); }; message::message(value_type data, std::size_t length) : data_(data), end_(data + length) { } bool message::next() { if (data_ < end_) { value = varint(); tag = static_cast<uint32_t>(value >> 3); return true; } return false; } uint64_t message::varint() { int8_t byte = static_cast<int8_t>(0x80); uint64_t result = 0; int bitpos; for (bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) { if (data_ >= end_) { throw std::runtime_error("unterminated varint, unexpected end of buffer"); } result |= ((uint64_t)(byte = *data_) & 0x7F) << bitpos; data_++; } if (bitpos == 70 && (byte & 0x80)) { throw std::runtime_error("unterminated varint (too long)"); } return result; } static const int8_t kMaxVarintLength64 = 10; uint64_t message::varint2() { const int8_t* begin = reinterpret_cast<const int8_t*>(data_); const int8_t* iend = reinterpret_cast<const int8_t*>(end_); const int8_t* p = begin; uint64_t val = 0; if (LIKELY(iend - begin >= kMaxVarintLength64)) { // fast path int64_t b; do { b = *p++; val = static_cast<uint64_t>((b & 0x7f) ); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 7); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 14); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 21); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 28); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 35); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 42); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 49); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 56); if (b >= 0) break; b = *p++; val |= static_cast<uint64_t>((b & 0x7f) << 63); if (b >= 0) break; throw std::invalid_argument("Invalid varint value"); // too big } while (false); } else { int shift = 0; while (p != iend && *p < 0) { val |= static_cast<uint64_t>(*p++ & 0x7f) << shift; shift += 7; } if (p == iend) throw std::invalid_argument("Invalid varint value"); val |= static_cast<uint64_t>(*p++) << shift; } data_ = reinterpret_cast<value_type>(p); return val; } int64_t message::svarint() { uint64_t n = varint(); return (n >> 1) ^ -static_cast<int64_t>((n & 1)); } std::string message::string() { uint64_t len = varint(); value_type string = static_cast<value_type>(data_); skipBytes(len); return std::string(string, len); } float message::float32() { skipBytes(4); float result; std::memcpy(&result, data_ - 4, 4); return result; } double message::float64() { skipBytes(8); double result; std::memcpy(&result, data_ - 8, 8); return result; } int64_t message::int64() { return (int64_t)varint(); } bool message::boolean() { skipBytes(1); return *(bool *)(data_ - 1); } void message::skip() { skipValue(value); } void message::skipValue(uint64_t val) { switch (val & 0x7) { case 0: // varint varint(); break; case 1: // 64 bit skipBytes(8); break; case 2: // string/message skipBytes(varint()); break; case 5: // 32 bit skipBytes(4); break; default: char msg[80]; snprintf(msg, 80, "cannot skip unknown type %lld", val & 0x7); throw std::runtime_error(msg); } } void message::skipBytes(uint64_t bytes) { data_ += bytes; if (data_ > end_) { throw std::runtime_error("unexpected end of buffer"); } } message::value_type message::getData() { return data_; } } #endif // __PBF_HPP__<commit_msg>remove duplicate/uneeded alternative varint impl<commit_after>#ifndef __PBF_HPP__ #define __PBF_HPP__ /* * Some parts are from upb - a minimalist implementation of protocol buffers. * * Copyright (c) 2008-2011 Google Inc. See LICENSE for details. * Author: Josh Haberman <jhaberman@gmail.com> */ #include <stdint.h> #include <stdexcept> #include <string> #include <cstring> #include <cassert> #undef LIKELY #undef UNLIKELY #if defined(__GNUC__) && __GNUC__ >= 4 #define LIKELY(x) (__builtin_expect((x), 1)) #define UNLIKELY(x) (__builtin_expect((x), 0)) #else #define LIKELY(x) (x) #define UNLIKELY(x) (x) #endif namespace protobuf { #define FORCEINLINE inline __attribute__((always_inline)) #define NOINLINE __attribute__((noinline)) #define PBF_INLINE FORCEINLINE class message { typedef const char * value_type; value_type data_; value_type end_; public: uint64_t value; uint32_t tag; PBF_INLINE message(value_type data, std::size_t length); PBF_INLINE bool next(); PBF_INLINE uint64_t varint(); PBF_INLINE int64_t svarint(); PBF_INLINE std::string string(); PBF_INLINE float float32(); PBF_INLINE double float64(); PBF_INLINE int64_t int64(); PBF_INLINE bool boolean(); PBF_INLINE void skip(); PBF_INLINE void skipValue(uint64_t val); PBF_INLINE void skipBytes(uint64_t bytes); PBF_INLINE value_type getData(); }; message::message(value_type data, std::size_t length) : data_(data), end_(data + length) { } bool message::next() { if (data_ < end_) { value = varint(); tag = static_cast<uint32_t>(value >> 3); return true; } return false; } uint64_t message::varint() { int8_t byte = static_cast<int8_t>(0x80); uint64_t result = 0; int bitpos; for (bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) { if (data_ >= end_) { throw std::runtime_error("unterminated varint, unexpected end of buffer"); } result |= ((uint64_t)(byte = *data_) & 0x7F) << bitpos; data_++; } if (bitpos == 70 && (byte & 0x80)) { throw std::runtime_error("unterminated varint (too long)"); } return result; } int64_t message::svarint() { uint64_t n = varint(); return (n >> 1) ^ -static_cast<int64_t>((n & 1)); } std::string message::string() { uint64_t len = varint(); value_type string = static_cast<value_type>(data_); skipBytes(len); return std::string(string, len); } float message::float32() { skipBytes(4); float result; std::memcpy(&result, data_ - 4, 4); return result; } double message::float64() { skipBytes(8); double result; std::memcpy(&result, data_ - 8, 8); return result; } int64_t message::int64() { return (int64_t)varint(); } bool message::boolean() { skipBytes(1); return *(bool *)(data_ - 1); } void message::skip() { skipValue(value); } void message::skipValue(uint64_t val) { switch (val & 0x7) { case 0: // varint varint(); break; case 1: // 64 bit skipBytes(8); break; case 2: // string/message skipBytes(varint()); break; case 5: // 32 bit skipBytes(4); break; default: char msg[80]; snprintf(msg, 80, "cannot skip unknown type %lld", val & 0x7); throw std::runtime_error(msg); } } void message::skipBytes(uint64_t bytes) { data_ += bytes; if (data_ > end_) { throw std::runtime_error("unexpected end of buffer"); } } message::value_type message::getData() { return data_; } } #endif // __PBF_HPP__<|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <functional> // In C++17, the function adapters mem_fun/mem_fun_ref, etc have been removed. // However, for backwards compatibility, if _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS // is defined before including <functional>, then they will be restored. // MODULES_DEFINES: _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS #define _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS #include <functional> #include <cassert> int identity(int v) { return v; } int sum(int a, int b) { return a + b; } struct Foo { int zero() { return 0; } int zero_const() const { return 1; } int identity(int v) const { return v; } int sum(int a, int b) const { return a + b; } }; int main() { typedef std::pointer_to_unary_function<int, int> PUF; typedef std::pointer_to_binary_function<int, int, int> PBF; static_assert( (std::is_same<PUF, decltype(std::ptr_fun<int, int>(identity))>::value), ""); static_assert( (std::is_same<PBF, decltype(std::ptr_fun<int, int, int>(sum))>::value), ""); assert((std::ptr_fun<int, int>(identity)(4) == 4)); assert((std::ptr_fun<int, int, int>(sum)(4, 5) == 9)); Foo f; assert((std::mem_fn(&Foo::identity)(f, 5) == 5)); assert((std::mem_fn(&Foo::sum)(f, 5, 6) == 11)); typedef std::mem_fun_ref_t<int, Foo> MFR; typedef std::const_mem_fun_ref_t<int, Foo> CMFR; static_assert( (std::is_same<MFR, decltype(std::mem_fun_ref(&Foo::zero))>::value), ""); static_assert((std::is_same<CMFR, decltype(std::mem_fun_ref( &Foo::zero_const))>::value), ""); assert((std::mem_fun_ref(&Foo::zero)(f) == 0)); assert((std::mem_fun_ref(&Foo::identity)(f, 5) == 5)); } <commit_msg>Work around C++03 decltype limitations<commit_after>//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <functional> // In C++17, the function adapters mem_fun/mem_fun_ref, etc have been removed. // However, for backwards compatibility, if _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS // is defined before including <functional>, then they will be restored. // MODULES_DEFINES: _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS #define _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS #include <functional> #include <cassert> int identity(int v) { return v; } int sum(int a, int b) { return a + b; } struct Foo { int zero() { return 0; } int zero_const() const { return 1; } int identity(int v) const { return v; } int sum(int a, int b) const { return a + b; } }; int main() { typedef std::pointer_to_unary_function<int, int> PUF; typedef std::pointer_to_binary_function<int, int, int> PBF; static_assert( (std::is_same<PUF, decltype((std::ptr_fun<int, int>(identity)))>::value), ""); static_assert( (std::is_same<PBF, decltype((std::ptr_fun<int, int, int>(sum)))>::value), ""); assert((std::ptr_fun<int, int>(identity)(4) == 4)); assert((std::ptr_fun<int, int, int>(sum)(4, 5) == 9)); Foo f; assert((std::mem_fn(&Foo::identity)(f, 5) == 5)); assert((std::mem_fn(&Foo::sum)(f, 5, 6) == 11)); typedef std::mem_fun_ref_t<int, Foo> MFR; typedef std::const_mem_fun_ref_t<int, Foo> CMFR; static_assert( (std::is_same<MFR, decltype((std::mem_fun_ref(&Foo::zero)))>::value), ""); static_assert((std::is_same<CMFR, decltype((std::mem_fun_ref( &Foo::zero_const)))>::value), ""); assert((std::mem_fun_ref(&Foo::zero)(f) == 0)); assert((std::mem_fun_ref(&Foo::identity)(f, 5) == 5)); } <|endoftext|>
<commit_before>#include "store.h" #include <QtGui/QGuiApplication> Store::Store(QQuickItem* parent):QQuickItem(parent) { _loaded = false; //_autoLoad = true; //_autoSave = true; _name = ""; QString sub; if(QGuiApplication::organizationName() != "") sub += QGuiApplication::organizationName() + QDir::separator(); if(QGuiApplication::organizationDomain() != "") sub += QGuiApplication::organizationDomain() + QDir::separator(); if(QGuiApplication::applicationName() != "") sub += QGuiApplication::applicationName() + QDir::separator(); if(QGuiApplication::applicationVersion() != "") sub += QGuiApplication::applicationVersion() + QDir::separator() ; if(sub == "") { qWarning() << "Store warning: Couldn't resolve" << sub << "for storing values. Using generic directory: \"Qak\""; sub = "Qak"; } while(sub.endsWith( QDir::separator() )) sub.chop(1); _store_path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QDir::separator()+sub; _ensureStorePath(); #ifdef QT_DEBUG qDebug() << "Store using" << _store_path; #endif //qDebug() << "Setting objectName"; //this->setObjectName(QString("Store")); QQuickItem *qi = new QQuickItem(); // Run through all the properties // This is done to get a list of the QuickItems normal attributes which we don't want to save _blacklist.append("name"); //_blacklist.append("autoLoad"); //_blacklist.append("autoSave"); _blacklist.append("isLoaded"); const QMetaObject *metaobject = qi->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); _blacklist.append(name); } delete qi; qi = 0; } /* Store::~Store() { if( _autoSave ) { #ifdef QT_DEBUG qDebug() << "Store auto saving"; #endif save(); } } */ QString Store::name() { return _name; } /* bool Store::autoLoad() { return _autoLoad; } bool Store::autoSave() { return _autoSave; } */ bool Store::isLoaded() { return _loaded; } void Store::setName(const QString &n) { if (n != _name) { _name = n; emit nameChanged(); /* if( _autoLoad ) { #ifdef QT_DEBUG qDebug() << "Store auto loading" << _name; #endif load(); } */ } } /* void Store::setAutoLoad(const bool &v) { if (v != _autoLoad) { _autoLoad = v; emit autoLoadChanged(); } } void Store::setAutoSave(const bool &v) { if (v != _autoSave) { _autoSave = v; emit autoSaveChanged(); } } */ void Store::save() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Store error: Property \"name\" not set"); return; } _ensureStorePath(); QString path = _store_path + QDir::separator() + _name; QJsonDocument json = QJsonDocument(); QJsonObject rootItem = QJsonObject(); emit saving(); // Run through all the properties const QMetaObject *metaobject = this->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); bool blacklisted = false; for (int i = 0; i < _blacklist.size(); ++i) { //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData(); if(_blacklist.at(i).toLocal8Bit().constData() == QString(name)) blacklisted = true; } if(!blacklisted) { QVariant value = this->property(name); #ifdef QT_DEBUG qDebug() << "Store" << _name << "property" << name << "stored" << value.typeName() << ":" << value; #endif QJsonValue jValue; jValue = jValue.fromVariant(value); rootItem.insert(name,jValue); } } json.setObject(rootItem); QByteArray bJson = json.toJson(QJsonDocument::Indented); QFile file(path); if(file.open(QIODevice::WriteOnly)) file.write(bJson); else qWarning() << "Store" << _name << "warning: Couldn't save to" << path; file.close(); //qDebug() << "Store saved" << bJson << "in" << path; emit saved(); } void Store::load() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Store error: Property \"name\" not set"); return; } QString path = _store_path + QDir::separator() + _name; QString bJson; QFile file; file.setFileName(path); if(file.exists()) { file.open(QIODevice::ReadOnly | QIODevice::Text); bJson = file.readAll(); file.close(); } else { #ifdef QT_DEBUG qWarning() << "Store" << _name << "warning: Couldn't load" << path; #endif //_loaded = true; //emit isLoadedChanged(); //emit loaded(); return; } QJsonDocument json = QJsonDocument::fromJson(bJson.toUtf8()); QJsonObject rootItem = json.object(); // Run through all the properties const QMetaObject *metaobject = this->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); //QVariant value = this->property(name); bool blacklisted = false; for (int i = 0; i < _blacklist.size(); ++i) { //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData(); if(_blacklist.at(i).toLocal8Bit().constData() == QString(name)) blacklisted = true; } if(!blacklisted) { QJsonValue value = rootItem.value(QString(name)); if(value != QJsonValue::Undefined) { this->setProperty(name,value.toVariant()); #ifdef QT_DEBUG qDebug() << "Store" << _name << "property" << name << "loaded" << value; #endif } else qWarning() << "Store" << _name << "warning: Property" << name << "not found"; } } //qDebug() << "Store loaded" << bJson << "from" << path; _loaded = true; emit isLoadedChanged(); emit loaded(); } void Store::clear() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Store error: Property \"name\" not set"); return; } QString path = _store_path + QDir::separator() + _name; bool result = QFile::remove(path); if(!result) emit error("Failed removing store directory "+path); #ifdef QT_DEBUG else qDebug() << "Store clear" << path << result; #endif emit cleared(); } void Store::clear(const QString &name) { if(name == "") { qCritical() << "Store error: Argument \"name\" not set"; emit error("Store error: Argument \"name\" not set"); return; } QString path = _store_path + QDir::separator() + name; bool result = QFile::remove(path); if(!result) emit error("Failed removing store directory "+path); #ifdef QT_DEBUG else qDebug() << "Store" << name << "clear" << path << result; #endif emit cleared(); } void Store::clearAll() { QDir dir(_store_path); if (dir.exists()) { dir.removeRecursively(); #ifdef QT_DEBUG qDebug() << "Store clearAll" << _store_path; #endif emit cleared(); } } void Store::_ensureStorePath() { // TODO fix silent fail? // This function is used in object constructor where _name is not yet set if(_name == "") return; QDir dir(_store_path); if (!dir.exists()) { if(!dir.mkpath(".")) emit error("Failed creating store directory "+_store_path); #ifdef QT_DEBUG else qDebug() << "Store created directory" << _store_path; #endif } } <commit_msg>Minor debug output fixes<commit_after>#include "store.h" #include <QtGui/QGuiApplication> Store::Store(QQuickItem* parent):QQuickItem(parent) { _loaded = false; //_autoLoad = true; //_autoSave = true; _name = ""; QString sub; if(QGuiApplication::organizationName() != "") sub += QGuiApplication::organizationName() + QDir::separator(); if(QGuiApplication::organizationDomain() != "") sub += QGuiApplication::organizationDomain() + QDir::separator(); if(QGuiApplication::applicationName() != "") sub += QGuiApplication::applicationName() + QDir::separator(); if(QGuiApplication::applicationVersion() != "") sub += QGuiApplication::applicationVersion() + QDir::separator() ; if(sub == "") { qWarning() << "Store warning: Couldn't resolve" << sub << "for storing values. Using generic directory: \"Qak\""; sub = "Qak"; } while(sub.endsWith( QDir::separator() )) sub.chop(1); _store_path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)+QDir::separator()+sub; _ensureStorePath(); #ifdef QT_DEBUG qDebug() << "Store using" << _store_path; #endif //qDebug() << "Setting objectName"; //this->setObjectName(QString("Store")); QQuickItem *qi = new QQuickItem(); // Run through all the properties // This is done to get a list of the QuickItems normal attributes which we don't want to save _blacklist.append("name"); //_blacklist.append("autoLoad"); //_blacklist.append("autoSave"); _blacklist.append("isLoaded"); const QMetaObject *metaobject = qi->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); _blacklist.append(name); } delete qi; qi = 0; } /* Store::~Store() { if( _autoSave ) { #ifdef QT_DEBUG qDebug() << "Store auto saving"; #endif save(); } } */ QString Store::name() { return _name; } /* bool Store::autoLoad() { return _autoLoad; } bool Store::autoSave() { return _autoSave; } */ bool Store::isLoaded() { return _loaded; } void Store::setName(const QString &n) { if (n != _name) { _name = n; emit nameChanged(); /* if( _autoLoad ) { #ifdef QT_DEBUG qDebug() << "Store auto loading" << _name; #endif load(); } */ } } /* void Store::setAutoLoad(const bool &v) { if (v != _autoLoad) { _autoLoad = v; emit autoLoadChanged(); } } void Store::setAutoSave(const bool &v) { if (v != _autoSave) { _autoSave = v; emit autoSaveChanged(); } } */ void Store::save() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Store error: Property \"name\" not set"); return; } _ensureStorePath(); QString path = _store_path + QDir::separator() + _name; QJsonDocument json = QJsonDocument(); QJsonObject rootItem = QJsonObject(); emit saving(); // Run through all the properties const QMetaObject *metaobject = this->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); bool blacklisted = false; for (int i = 0; i < _blacklist.size(); ++i) { //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData(); if(_blacklist.at(i).toLocal8Bit().constData() == QString(name)) blacklisted = true; } if(!blacklisted) { QVariant value = this->property(name); #ifdef QT_DEBUG qDebug() << "Store" << _name << "property" << name << "stored" << value.typeName() << ":" << value; #endif QJsonValue jValue; jValue = jValue.fromVariant(value); rootItem.insert(name,jValue); } } json.setObject(rootItem); QByteArray bJson = json.toJson(QJsonDocument::Indented); QFile file(path); if(file.open(QIODevice::WriteOnly)) file.write(bJson); else qWarning() << "Store" << _name << "warning: Couldn't save to" << path; file.close(); //qDebug() << "Store saved" << bJson << "in" << path; emit saved(); } void Store::load() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Store error: Property \"name\" not set"); return; } QString path = _store_path + QDir::separator() + _name; QString bJson; QFile file; file.setFileName(path); if(file.exists()) { file.open(QIODevice::ReadOnly | QIODevice::Text); bJson = file.readAll(); file.close(); } else { #ifdef QT_DEBUG qWarning() << "Store" << _name << "warning: Couldn't load" << path; #endif emit error("Could not load store from: \""+path+"\""); //_loaded = true; //emit isLoadedChanged(); //emit loaded(); return; } QJsonDocument json = QJsonDocument::fromJson(bJson.toUtf8()); QJsonObject rootItem = json.object(); // Run through all the properties const QMetaObject *metaobject = this->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); //QVariant value = this->property(name); bool blacklisted = false; for (int i = 0; i < _blacklist.size(); ++i) { //qDebug() << _quick_item_names.at(i).toLocal8Bit().constData(); if(_blacklist.at(i).toLocal8Bit().constData() == QString(name)) blacklisted = true; } if(!blacklisted) { QJsonValue value = rootItem.value(QString(name)); if(value != QJsonValue::Undefined) { this->setProperty(name,value.toVariant()); #ifdef QT_DEBUG qDebug() << "Store" << _name << "property" << name << "loaded" << value; #endif } else qWarning() << "Store" << _name << "warning: Property" << name << "not found"; } } //qDebug() << "Store loaded" << bJson << "from" << path; _loaded = true; emit isLoadedChanged(); emit loaded(); } void Store::clear() { if(_name == "") { qCritical() << "Store error: Property \"name\" not set"; emit error("Property \"name\" not set"); return; } QString path = _store_path + QDir::separator() + _name; bool result = QFile::remove(path); if(!result) emit error("Failed removing store directory "+path); #ifdef QT_DEBUG else qDebug() << "Store clear" << path << result; #endif emit cleared(); } void Store::clear(const QString &name) { if(name == "") { qCritical() << "Store error: Argument \"name\" not set"; emit error("Argument \"name\" not set"); return; } QString path = _store_path + QDir::separator() + name; bool result = QFile::remove(path); if(!result) emit error("Failed removing store directory "+path); #ifdef QT_DEBUG else qDebug() << "Store" << name << "clear" << path << result; #endif emit cleared(); } void Store::clearAll() { QDir dir(_store_path); if (dir.exists()) { dir.removeRecursively(); #ifdef QT_DEBUG qDebug() << "Store clearAll" << _store_path; #endif emit cleared(); } } void Store::_ensureStorePath() { // TODO fix silent fail? // This function is used in object constructor where _name is not yet set if(_name == "") return; QDir dir(_store_path); if (!dir.exists()) { if(!dir.mkpath(".")) emit error("Failed creating store directory "+_store_path); #ifdef QT_DEBUG else qDebug() << "Store created directory" << _store_path; #endif } } <|endoftext|>
<commit_before> #include "utils.h" using namespace Rcpp; using namespace RcppEigen; //port faster cross product RcppExport SEXP crossprodcpp(SEXP X) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; using Eigen::Lower; const Eigen::Map<MatrixXd> A(as<Map<MatrixXd> >(X)); const int n(A.cols()); MatrixXd AtA(MatrixXd(n, n).setZero(). selfadjointView<Lower>().rankUpdate(A.adjoint())); return wrap(AtA); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster cross product RcppExport SEXP xpwx(SEXP X, SEXP W) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; using Eigen::Lower; const Eigen::Map<MatrixXd> A(as<Map<MatrixXd> >(X)); const Eigen::Map<MatrixXd> diag(as<Map<MatrixXd> >(W)); const int n(A.cols()); MatrixXd AtA(MatrixXd(n, n).setZero(). selfadjointView<Lower>().rankUpdate(A.adjoint() * diag.sqrt())); return wrap(AtA); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subtract RcppExport SEXP subcpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; typedef Eigen::Map<Eigen::MatrixXd> MapMatd; const MapMatd B(as<MapMatd>(BB)); const MapMatd C(as<MapMatd>(CC)); return wrap(B - C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster add RcppExport SEXP addcpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; typedef Eigen::Map<Eigen::MatrixXd> MapMatd; const MapMatd B(as<MapMatd>(BB)); const MapMatd C(as<MapMatd>(CC)); return wrap(B + C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subtract sparse matrices RcppExport SEXP subSparsecpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::MappedSparseMatrix; using Eigen::SparseMatrix; typedef Eigen::MappedSparseMatrix<double> MSpMat; typedef Eigen::SparseMatrix<double> SpMat; const SpMat B(as<MSpMat>(BB)); const SpMat C(as<MSpMat>(CC)); return wrap(B - C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subaddtract sparse matrices RcppExport SEXP addSparsecpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::MappedSparseMatrix; using Eigen::SparseMatrix; typedef Eigen::MappedSparseMatrix<double> MSpMat; typedef Eigen::SparseMatrix<double> SpMat; const SpMat B(as<MSpMat>(BB)); const SpMat C(as<MSpMat>(CC)); return wrap(B + C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } <commit_msg>fixed xpwx C++ function<commit_after> #include "utils.h" using namespace Rcpp; using namespace RcppEigen; //port faster cross product RcppExport SEXP crossprodcpp(SEXP X) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; using Eigen::Lower; const Eigen::Map<MatrixXd> A(as<Map<MatrixXd> >(X)); const int n(A.cols()); MatrixXd AtA(MatrixXd(n, n).setZero(). selfadjointView<Lower>().rankUpdate(A.adjoint())); return wrap(AtA); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster cross product RcppExport SEXP xpwx(SEXP X, SEXP W) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::Lower; const Eigen::Map<MatrixXd> A(as<Map<MatrixXd> >(X)); const Eigen::Map<VectorXd> diag(as<Map<VectorXd> >(W)); const int n(A.cols()); MatrixXd AtA(MatrixXd(n, n).setZero(). selfadjointView<Lower>().rankUpdate(A.adjoint() * diag.array().sqrt().matrix().asDiagonal())); return wrap(AtA); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subtract RcppExport SEXP subcpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; typedef Eigen::Map<Eigen::MatrixXd> MapMatd; const MapMatd B(as<MapMatd>(BB)); const MapMatd C(as<MapMatd>(CC)); return wrap(B - C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster add RcppExport SEXP addcpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::Map; using Eigen::MatrixXd; typedef Eigen::Map<Eigen::MatrixXd> MapMatd; const MapMatd B(as<MapMatd>(BB)); const MapMatd C(as<MapMatd>(CC)); return wrap(B + C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subtract sparse matrices RcppExport SEXP subSparsecpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::MappedSparseMatrix; using Eigen::SparseMatrix; typedef Eigen::MappedSparseMatrix<double> MSpMat; typedef Eigen::SparseMatrix<double> SpMat; const SpMat B(as<MSpMat>(BB)); const SpMat C(as<MSpMat>(CC)); return wrap(B - C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } //port faster subaddtract sparse matrices RcppExport SEXP addSparsecpp(SEXP BB, SEXP CC) { using namespace Rcpp; using namespace RcppEigen; try { using Eigen::MappedSparseMatrix; using Eigen::SparseMatrix; typedef Eigen::MappedSparseMatrix<double> MSpMat; typedef Eigen::SparseMatrix<double> SpMat; const SpMat B(as<MSpMat>(BB)); const SpMat C(as<MSpMat>(CC)); return wrap(B + C); } catch (std::exception &ex) { forward_exception_to_r(ex); } catch (...) { ::Rf_error("C++ exception (unknown reason)"); } return R_NilValue; //-Wall } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <vexcl/vexcl.hpp> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { //set some default values for when no commandline arguments are given int accuracy = 90; int polygons = 50; int vertices = 6; //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = ; } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = ; } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = ; } } // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //initialise variables const size_t n = 1024 * 1024; std::vector<double> leaderDNA(ctx, n); std::vector<double> mutatedDNA(ctx, n); std::vector<double> leaderDNArender(ctx, n); std::vector<double> mutatedDNArender(ctx, n); std::vector<double> originalimage(ctx, n); //load image into gpu memory // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); //initialise variables class DNA { public: string genome; int polygons; int vertices; polygon[polygons]; } class polygon; { public: int x[vertices]; int y[vertices]; int R; int G; int B; int alpha; } //initialise DNA with a random seed leaderDNA = seedDNA(); //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //mutate from the leaderDNA mutatedDNA = mutateDNA(leaderDNA) //compute fitness of mutation vs leaderDNA //check if it is fitter, if so overwrite leaderDNA if (computefitness(leaderDNA,mutatedDNA) == 1) { //overwrite leaderDNA leaderDNA = mutatedDNA; } //compute accuracy percent computefitnesspercent(leaderDNA, originalimage) } //perform final render, output svg and raster image saverender(leaderDNA); } int computefitnesspercent (DNA, originalimage) { //compute what % match DNA is to original image } int computefitness (DNA0, DNA1) { //compute the fitness of input DNA, i.e. how close is it to original image? boost::compute::function<int (int)> computefitness = boost::compute::make_function_from_source<int (int)>( "computefitness", "int computefitness(int x) { return x + 4; }" ); //read leader dna //compare input dna to leader dna to find changed polygons compareDNA(leaderDNA,DNA); //create bounding box containing changed polygons //render leader dna within bounding box leaderrender = renderDNA(leaderDNA,boundx,boundy); //render input dna within bounding box inputrender = renderDNA(DNA,boundx,boundy); //compare leader and input dna rendered bounding boxes compareimage(leaderrender,inputrender); //returns 1 if dna1 is fitter than dna0, else returns 0 } int seedDNA() { //create a random seed dna //create random leader dna // generate random dna vector on the host std::vector<float> host_vector(1000000); std::generate(host_vector.begin(), host_vector.end(), rand); // create vector on the device compute::vector<float> device_vector(1000000, ctx); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } int compareDNA(DNA0,DNA1) { //compare DNA0 to DNA1 to find changed polygons boost::compute::function<int (int)> compareDNA = boost::compute::make_function_from_source<int (int)>( "compareDNA", "int compareDNA(int x) { return x + 4; }" ); } int compareimage(image0,image1) { //compare two raster images, return 1 if image1 fitter than image0, else return 0 char *img1data, *img2data, fname[15]; int s, n = 0, y = 0; sprintf(fname, "photo%d.bmp", p - 1); cout << "\n" << fname; ifstream img1(fname, ios::in|ios::binary|ios::ate); sprintf(fname, "photo%d.bmp", p); cout << "\n" << fname; ifstream img2(fname, ios::in|ios::binary|ios::ate); if (img1.is_open() && img2.is_open()) { s = (int)img1.tellg(); img1data = new char [s]; img1.seekg (0, ios::beg); img1.read (img1data, s); img1.close(); img2data = new char [s]; img2.seekg (0, ios::beg); img2.read (img2data, s); img2.close(); } for(int i=0; i<s; i++) if (img1data[i]==img2data[i]) y++; return (y); } int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1) { //render input DNA to a raster image and svg boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { return x + 4; }" ); //render to raster image //read DNA from gpu memory //initialise a new opengl image and render the dna within bounding box into it cairo_set_source_rgb(cr, 1, 1, 1); cairo_rectangle(cr, 0, 0, WIDTH, HEIGHT); cairo_fill(cr); for(int i = 0; i < NUM_SHAPES; i++) draw_shape(dna, cr, i); //render to svg } void draw_shape(shape_t * dna, cairo_t * cr, int i) { // Set variables that define the boundary of the bounding box in // computefitness and renderDNA int xmax = 0, xmin = 0, ymax = 0, ymin = 0; //render an individual shape within a DNA strand using opengl cairo_set_line_width(cr, 0); shape_t * shape = &dna[i]; cairo_set_source_rgba(cr, shape->r, shape->g, shape->b, shape->a); cairo_move_to(cr, shape->points[0].x, shape->points[0].y); for(int j = 1; j < NUM_POINTS; j++) // Check the X and Y values of the boundary box & the polygon // Expand the bounding box edges if necessary xmax = (shape->points[j].x > xmax) ? shape->points[j].x : xmax ; xmin = (shape->points[j].x < xmin) ? shape->points[j].x : xmin ; ymax = (shape->points[j].y > ymax) ? shape->points[j].y : ymax ; ymin = (shape->points[j].y < ymin) ? shape->points[j].y : ymin ; cairo_line_to(cr, shape->points[j].x, shape->points[j].y); cairo_fill(cr); } } int mutateDNA (DNA) { //mutate dna boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(2.8); double drastic = RANDDOUBLE(2); // mutate color if(roulette<1) { if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid || roulette<0.25) { if(drastic < 1) { dna_test[mutated_shape].a += RANDDOUBLE(0.1); dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0); } else dna_test[mutated_shape].a = RANDDOUBLE(1.0); } else if(roulette<0.50) { if(drastic < 1) { dna_test[mutated_shape].r += RANDDOUBLE(0.1); dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0); } else dna_test[mutated_shape].r = RANDDOUBLE(1.0); } else if(roulette<0.75) { if(drastic < 1) { dna_test[mutated_shape].g += RANDDOUBLE(0.1); dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0); } else dna_test[mutated_shape].g = RANDDOUBLE(1.0); } else { if(drastic < 1) { dna_test[mutated_shape].b += RANDDOUBLE(0.1); dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0); } else dna_test[mutated_shape].b = RANDDOUBLE(1.0); } } // mutate shape else if(roulette < 2.0) { int point_i = RANDINT(NUM_POINTS); if(roulette<1.5) { if(drastic < 1) { dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0); dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1); } else dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH); } else { if(drastic < 1) { dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0); dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1); } else dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT); } } // mutate stacking else { int destination = RANDINT(NUM_SHAPES); shape_t s = dna_test[mutated_shape]; dna_test[mutated_shape] = dna_test[destination]; dna_test[destination] = s; return destination; } return -1; }" ); } int saveDNA(DNA) { int result; while(1) { // start by writing a temp file. pFile = fopen ("volution.dna.temp","w"); fprintf (pFile, DNA); fclose (pFile); // Then rename the real backup to a secondary backup. result = rename("volution.dna","volution_2.dna"); // Then rename the temp file to the primary backup result = rename("volution.dna.temp","volution.dna"); // Then delete the temp file result = remove("volution.dna.temp"); } } int saverender(DNA) { //render DNA and save resulting image to disk as .svg file and raster image (.png) //render image from DNA renderDNA(DNA); //save resultant image to disk as svg and png files } int importimage(image) { //import specified image into the gpu memory // Load input image from file and load it into // an OpenCL image object int width, height; imageObjects[0] = LoadImage(context, argv[1], width, height); if (imageObjects[0] == 0) { std::cerr << "Error loading: " << std::string(argv[1]) << std::endl; Cleanup(context, commandQueue, program, kernel, imageObjects, sampler); return 1; } } int drawshape() { //user draws shape from ui //start drawing shape vertex by vertex //until max number of vertices reached or user closes polygon by clicking on initial vertex //check if drawn shape gives a better fitness //if it does update the leaderDNA } int dragvertex() { //user drags vertex from ui //user stops dragging vertex //check if dragged vertex improves fitness //if it does update the leaderDNA } <commit_msg>tidying<commit_after>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <vexcl/vexcl.hpp> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { //set some default values for when no commandline arguments are given int accuracy = 90; int polygons = 50; int vertices = 6; //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = ; } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = ; } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = ; } } // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //initialise variables const size_t n = 1024 * 1024; std::vector<double> leaderDNA(ctx, n); std::vector<double> mutatedDNA(ctx, n); std::vector<double> leaderDNArender(ctx, n); std::vector<double> mutatedDNArender(ctx, n); std::vector<double> originalimage(ctx, n); //load image into gpu memory // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); //initialise variables class DNA { public: string genome; int polygons; int vertices; polygon[polygons]; } class polygon; { public: int x[vertices]; int y[vertices]; int R; int G; int B; int alpha; } //initialise DNA with a random seed leaderDNA = seedDNA(); //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //mutate from the leaderDNA mutatedDNA = mutateDNA(leaderDNA) //compute fitness of mutation vs leaderDNA //check if it is fitter, if so overwrite leaderDNA if (computefitness(leaderDNA,mutatedDNA) == 1) { //overwrite leaderDNA leaderDNA = mutatedDNA; } //compute accuracy percent computefitnesspercent(leaderDNA, originalimage) } //perform final render, output svg and raster image saverender(leaderDNA); } int computefitnesspercent (DNA, originalimage) { //compute what % match DNA is to original image } int computefitness (DNA0, DNA1) { //compute the fitness of input DNA, i.e. how close is it to original image? boost::compute::function<int (int)> computefitness = boost::compute::make_function_from_source<int (int)>( "computefitness", "int computefitness(int x) { return x + 4; }" ); //read leader dna //compare input dna to leader dna to find changed polygons compareDNA(leaderDNA,DNA); //create bounding box containing changed polygons //render leader dna within bounding box leaderrender = renderDNA(leaderDNA,boundx,boundy); //render input dna within bounding box inputrender = renderDNA(DNA,boundx,boundy); //compare leader and input dna rendered bounding boxes compareimage(leaderrender,inputrender); //returns 1 if dna1 is fitter than dna0, else returns 0 } int seedDNA() { //create a random seed dna //create random leader dna // generate random dna vector on the host std::vector<float> host_vector(1000000); std::generate(host_vector.begin(), host_vector.end(), rand); // create vector on the device compute::vector<float> device_vector(1000000, ctx); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } int compareDNA(DNA0,DNA1) { //compare DNA0 to DNA1 to find changed polygons boost::compute::function<int (int)> compareDNA = boost::compute::make_function_from_source<int (int)>( "compareDNA", "int compareDNA(int x) { return x + 4; }" ); } int compareimage(image0,image1) { //compare two raster images, return 1 if image1 fitter than image0, else return 0 char *img1data, *img2data, fname[15]; int s, n = 0, y = 0; sprintf(fname, "photo%d.bmp", p - 1); cout << "\n" << fname; ifstream img1(fname, ios::in|ios::binary|ios::ate); sprintf(fname, "photo%d.bmp", p); cout << "\n" << fname; ifstream img2(fname, ios::in|ios::binary|ios::ate); if (img1.is_open() && img2.is_open()) { s = (int)img1.tellg(); img1data = new char [s]; img1.seekg (0, ios::beg); img1.read (img1data, s); img1.close(); img2data = new char [s]; img2.seekg (0, ios::beg); img2.read (img2data, s); img2.close(); } for(int i=0; i<s; i++) if (img1data[i]==img2data[i]) y++; return (y); } int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1) { //render input DNA to a raster image boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); } int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1) { //render input DNA to a vector image boost::compute::function<int (int)> renderSVG = boost::compute::make_function_from_source<int (int)>( "renderSVG", "int renderSVG(int x) { //for each shape in dna { } }" ); } } int mutateDNA (DNA) { //mutate dna boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(2.8); double drastic = RANDDOUBLE(2); // mutate color if(roulette<1) { if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid || roulette<0.25) { if(drastic < 1) { dna_test[mutated_shape].a += RANDDOUBLE(0.1); dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0); } else dna_test[mutated_shape].a = RANDDOUBLE(1.0); } else if(roulette<0.50) { if(drastic < 1) { dna_test[mutated_shape].r += RANDDOUBLE(0.1); dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0); } else dna_test[mutated_shape].r = RANDDOUBLE(1.0); } else if(roulette<0.75) { if(drastic < 1) { dna_test[mutated_shape].g += RANDDOUBLE(0.1); dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0); } else dna_test[mutated_shape].g = RANDDOUBLE(1.0); } else { if(drastic < 1) { dna_test[mutated_shape].b += RANDDOUBLE(0.1); dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0); } else dna_test[mutated_shape].b = RANDDOUBLE(1.0); } } // mutate shape else if(roulette < 2.0) { int point_i = RANDINT(NUM_POINTS); if(roulette<1.5) { if(drastic < 1) { dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0); dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1); } else dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH); } else { if(drastic < 1) { dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0); dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1); } else dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT); } } // mutate stacking else { int destination = RANDINT(NUM_SHAPES); shape_t s = dna_test[mutated_shape]; dna_test[mutated_shape] = dna_test[destination]; dna_test[destination] = s; return destination; } return -1; }" ); } int saveDNA(DNA) { int result; while(1) { // start by writing a temp file. pFile = fopen ("volution.dna.temp","w"); fprintf (pFile, DNA); fclose (pFile); // Then rename the real backup to a secondary backup. result = rename("volution.dna","volution_2.dna"); // Then rename the temp file to the primary backup result = rename("volution.dna.temp","volution.dna"); // Then delete the temp file result = remove("volution.dna.temp"); } } int saverender(DNA) { //render DNA and save resulting image to disk as .svg file and raster image (.png) //render image from DNA renderDNA(DNA); //save resultant image to disk as svg and png files } int importimage(image) { //import specified image into the gpu memory // Load input image from file and load it into // an OpenCL image object int width, height; imageObjects[0] = LoadImage(context, argv[1], width, height); if (imageObjects[0] == 0) { std::cerr << "Error loading: " << std::string(argv[1]) << std::endl; Cleanup(context, commandQueue, program, kernel, imageObjects, sampler); return 1; } //load image into gpu memory // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } int drawshape() { //user draws shape from ui //start drawing shape vertex by vertex //until max number of vertices reached or user closes polygon by clicking on initial vertex //check if drawn shape gives a better fitness //if it does update the leaderDNA } int dragvertex() { //user drags vertex from ui //user stops dragging vertex //check if dragged vertex improves fitness //if it does update the leaderDNA } <|endoftext|>
<commit_before>/** * MegaMol * Copyright (c) 2021, MegaMol Dev Team * All rights reserved. */ #include "mmcore/utility/platform/RuntimeInfo.h" #include <array> #include <filesystem> #include <sstream> #include <stdexcept> #include <vector> #ifdef _WIN32 #include <windows.h> #include <tlhelp32.h> #include <tchar.h> #define the_popen _popen #define the_pclose _pclose #else #include <link.h> #define the_popen popen #define the_pclose pclose #endif namespace { #ifdef _WIN32 std::string get_file_version(const char* path) { // https://stackoverflow.com/questions/940707/how-do-i-programmatically-get-the-version-of-a-dll-or-exe-file std::string ret; DWORD verHandle = 0; UINT size = 0; LPBYTE lpBuffer = NULL; DWORD verSize = GetFileVersionInfoSize(path, &verHandle); if (verSize != NULL) { LPSTR verData = new char[verSize]; if (GetFileVersionInfo(path, verHandle, verSize, verData)) { if (VerQueryValue(verData, "\\", reinterpret_cast<void**>(&lpBuffer), &size)) { if (size) { VS_FIXEDFILEINFO* verInfo = reinterpret_cast<VS_FIXEDFILEINFO*>(lpBuffer); if (verInfo->dwSignature == 0xfeef04bd) { // Doesn't matter if you are on 32 bit or 64 bit, // DWORD is always 32 bits, so first two revision numbers // come from dwFileVersionMS, last two come from dwFileVersionLS ret += std::to_string((verInfo->dwFileVersionMS >> 16) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionMS >> 0) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionLS >> 16) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionLS >> 0) & 0xffff); } } } } delete[] verData; } return ret; } #else /** * Extract list of library search paths from a dlopen(nullptr, RTLD_NOW) handle. * @param handle A handle generated with dlopen(nullptr, RTLD_NOW). * @return List of library search paths. */ [[maybe_unused]] std::vector<std::string> dlinfo_search_path(void* handle) { // `man dlinfo` std::vector<std::string> paths; Dl_serinfo serinfo; if (dlinfo(handle, RTLD_DI_SERINFOSIZE, &serinfo) != 0) { throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } auto* sip = reinterpret_cast<Dl_serinfo*>(std::malloc(serinfo.dls_size)); if (dlinfo(handle, RTLD_DI_SERINFOSIZE, sip) != 0) { std::free(sip); throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } if (dlinfo(handle, RTLD_DI_SERINFO, sip) != 0) { std::free(sip); throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } paths.resize(serinfo.dls_cnt); for (unsigned int i = 0; i < serinfo.dls_cnt; i++) { paths[i] = std::string(sip->dls_serpath[i].dls_name); } std::free(sip); return paths; } /** * Extract list of loaded libraries from a dlopen(nullptr, RTLD_NOW) handle. * @param handle A handle generated with dlopen(nullptr, RTLD_NOW). * @return List of loaded libraries. */ std::vector<std::string> dlinfo_linkmap(void* handle) { std::vector<std::string> list; struct link_map* map = nullptr; if (dlinfo(handle, RTLD_DI_LINKMAP, &map) != 0) { throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } map = map->l_next; // ignore current exe itself while (map != nullptr) { list.emplace_back(std::string(map->l_name)); map = map->l_next; } return list; } #endif } void megamol::core::utility::platform::RuntimeInfo::get_runtime_libraries() { #ifdef _WIN32 HANDLE h_mod_snap = INVALID_HANDLE_VALUE; h_mod_snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if (h_mod_snap != INVALID_HANDLE_VALUE) { std::stringstream out; MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); if (Module32First(h_mod_snap, &me32)) { do { out << me32.szExePath << " ("; out << get_file_version(me32.szExePath) << ")" << std::endl; } while (Module32Next(h_mod_snap, &me32)); } CloseHandle(h_mod_snap); m_runtime_libraries = out.str(); } else { m_runtime_libraries = ""; } #else void* handle = dlopen(nullptr, RTLD_NOW); // TODO looks like all library paths are already absolute, do we need search paths here? // const auto paths = dlinfo_search_path(handle); const auto list = dlinfo_linkmap(handle); std::stringstream out; for (const auto& lib : list) { out << lib; // If the library is a symlink, print link target to get the filename with the full version number. std::filesystem::path p(lib); if (std::filesystem::is_symlink(p)) { p = std::filesystem::canonical(p); out << " (=> " << p.string() << ")"; } out << std::endl; } m_module_info = out.str(); #endif } void megamol::core::utility::platform::RuntimeInfo::get_os_info() { #ifdef _WIN32 m_os_info = execute("ver"); #else m_os_info = execute("cat /etc/issue"); #endif } std::string megamol::core::utility::platform::RuntimeInfo::execute(const std::string& cmd) { std::array<char, 1024> buffer; std::string result; auto pipe = the_popen(cmd.c_str(), "r"); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe)) { if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) result += buffer.data(); } auto rc = the_pclose(pipe); if (rc == EXIT_SUCCESS) { return result; } else { return "unable to execute " + cmd; } } <commit_msg>typo<commit_after>/** * MegaMol * Copyright (c) 2021, MegaMol Dev Team * All rights reserved. */ #include "mmcore/utility/platform/RuntimeInfo.h" #include <array> #include <filesystem> #include <sstream> #include <stdexcept> #include <vector> #ifdef _WIN32 #include <windows.h> #include <tlhelp32.h> #include <tchar.h> #define the_popen _popen #define the_pclose _pclose #else #include <link.h> #define the_popen popen #define the_pclose pclose #endif namespace { #ifdef _WIN32 std::string get_file_version(const char* path) { // https://stackoverflow.com/questions/940707/how-do-i-programmatically-get-the-version-of-a-dll-or-exe-file std::string ret; DWORD verHandle = 0; UINT size = 0; LPBYTE lpBuffer = NULL; DWORD verSize = GetFileVersionInfoSize(path, &verHandle); if (verSize != NULL) { LPSTR verData = new char[verSize]; if (GetFileVersionInfo(path, verHandle, verSize, verData)) { if (VerQueryValue(verData, "\\", reinterpret_cast<void**>(&lpBuffer), &size)) { if (size) { VS_FIXEDFILEINFO* verInfo = reinterpret_cast<VS_FIXEDFILEINFO*>(lpBuffer); if (verInfo->dwSignature == 0xfeef04bd) { // Doesn't matter if you are on 32 bit or 64 bit, // DWORD is always 32 bits, so first two revision numbers // come from dwFileVersionMS, last two come from dwFileVersionLS ret += std::to_string((verInfo->dwFileVersionMS >> 16) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionMS >> 0) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionLS >> 16) & 0xffff) + "." + std::to_string((verInfo->dwFileVersionLS >> 0) & 0xffff); } } } } delete[] verData; } return ret; } #else /** * Extract list of library search paths from a dlopen(nullptr, RTLD_NOW) handle. * @param handle A handle generated with dlopen(nullptr, RTLD_NOW). * @return List of library search paths. */ [[maybe_unused]] std::vector<std::string> dlinfo_search_path(void* handle) { // `man dlinfo` std::vector<std::string> paths; Dl_serinfo serinfo; if (dlinfo(handle, RTLD_DI_SERINFOSIZE, &serinfo) != 0) { throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } auto* sip = reinterpret_cast<Dl_serinfo*>(std::malloc(serinfo.dls_size)); if (dlinfo(handle, RTLD_DI_SERINFOSIZE, sip) != 0) { std::free(sip); throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } if (dlinfo(handle, RTLD_DI_SERINFO, sip) != 0) { std::free(sip); throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } paths.resize(serinfo.dls_cnt); for (unsigned int i = 0; i < serinfo.dls_cnt; i++) { paths[i] = std::string(sip->dls_serpath[i].dls_name); } std::free(sip); return paths; } /** * Extract list of loaded libraries from a dlopen(nullptr, RTLD_NOW) handle. * @param handle A handle generated with dlopen(nullptr, RTLD_NOW). * @return List of loaded libraries. */ std::vector<std::string> dlinfo_linkmap(void* handle) { std::vector<std::string> list; struct link_map* map = nullptr; if (dlinfo(handle, RTLD_DI_LINKMAP, &map) != 0) { throw std::runtime_error(std::string("Error from dlinfo(): ") + dlerror()); } map = map->l_next; // ignore current exe itself while (map != nullptr) { list.emplace_back(std::string(map->l_name)); map = map->l_next; } return list; } #endif } void megamol::core::utility::platform::RuntimeInfo::get_runtime_libraries() { #ifdef _WIN32 HANDLE h_mod_snap = INVALID_HANDLE_VALUE; h_mod_snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if (h_mod_snap != INVALID_HANDLE_VALUE) { std::stringstream out; MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); if (Module32First(h_mod_snap, &me32)) { do { out << me32.szExePath << " ("; out << get_file_version(me32.szExePath) << ")" << std::endl; } while (Module32Next(h_mod_snap, &me32)); } CloseHandle(h_mod_snap); m_runtime_libraries = out.str(); } else { m_runtime_libraries = ""; } #else void* handle = dlopen(nullptr, RTLD_NOW); // TODO looks like all library paths are already absolute, do we need search paths here? // const auto paths = dlinfo_search_path(handle); const auto list = dlinfo_linkmap(handle); std::stringstream out; for (const auto& lib : list) { out << lib; // If the library is a symlink, print link target to get the filename with the full version number. std::filesystem::path p(lib); if (std::filesystem::is_symlink(p)) { p = std::filesystem::canonical(p); out << " (=> " << p.string() << ")"; } out << std::endl; } m_runtime_libraries = out.str(); #endif } void megamol::core::utility::platform::RuntimeInfo::get_os_info() { #ifdef _WIN32 m_os_info = execute("ver"); #else m_os_info = execute("cat /etc/issue"); #endif } std::string megamol::core::utility::platform::RuntimeInfo::execute(const std::string& cmd) { std::array<char, 1024> buffer; std::string result; auto pipe = the_popen(cmd.c_str(), "r"); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe)) { if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) result += buffer.data(); } auto rc = the_pclose(pipe); if (rc == EXIT_SUCCESS) { return result; } else { return "unable to execute " + cmd; } } <|endoftext|>
<commit_before>#include "model.h" #include "figurepainter.h" #include <string> #include <algorithm> #include <map> double figures::Segment::getApproximateDistanceToBorder(const Point &p) { double res = std::min((p - a).length(), (p - b).length()); // Please note that here we do not care about floatint-point error, // as if 'start' falls near 'a' or 'b', we've already calculated it if (Point::dotProduct(p - a, b - a) >= 0 && Point::dotProduct(p - b, a - b) >= 0) { res = std::min(res, getDistanceToLine(p)); } return res; } double figures::Segment::getDistanceToLine(const Point &p) { // Coefficients of A*x + B*y + C = 0 double A = b.y - a.y; double B = a.x - b.x; double C = -A * a.x - B * a.y; // normalization of the equation double D = sqrt(A * A + B * B); if (fabs(D) < 1e-8) { return HUGE_VAL; } // degenerate case A /= D; B /= D; C /= D; return fabs(A * p.x + B * p.y + C); } double figures::Rectangle::getApproximateDistanceToBorder(const Point &p) { bool inX = box.leftDown.x <= p.x && p.x <= box.rightUp.x; bool inY = box.leftDown.y <= p.y && p.y <= box.rightUp.y; double res = HUGE_VAL; if (inX) { // Point lies in a vertical bar bounded by Left and Right res = std::min(res, fabs(p.y - box.leftDown.y)); res = std::min(res, fabs(p.y - box.rightUp.y)); } if (inY) { // Point lies in a horizontal bar res = std::min(res, fabs(p.x - box.leftDown.x)); res = std::min(res, fabs(p.x - box.rightUp.x)); } if (!inX && !inY) { res = std::min(res, (p - box.leftDown).length()); res = std::min(res, (p - box.rightUp).length()); res = std::min(res, (p - box.leftUp()).length()); res = std::min(res, (p - box.rightDown()).length()); } return res; } double figures::Ellipse::getApproximateDistanceToBorder(const Point &_p) { Point p = _p - box.center(); if (p.length() < 1e-7) { return std::min(box.width(), box.height()) / 2; } double a = box.width() / 2; double b = box.height() / 2; Point near = p; near.x /= a; near.y /= b; double d = near.length(); near.x /= d; near.y /= d; near.x *= a; near.y *= b; return (p - near).length(); } std::vector<Point> getMiddleBorderPoints(BoundingBox box) { std::vector<Point> res; res.push_back(Point(box.center().x, box.leftDown.y)); res.push_back(Point(box.center().x, box.rightUp.y)); res.push_back(Point(box.leftDown.x, box.center().y)); res.push_back(Point(box.rightUp.x, box.center().y)); return res; } void figures::SegmentConnection::recalculate() { using std::vector; using std::get; vector<Point> as = getMiddleBorderPoints(figA->getBoundingBox()); vector<Point> bs = getMiddleBorderPoints(figB->getBoundingBox()); double minDistSquared = HUGE_VAL; for (Point a : as) { for (Point b : bs) { double curDistSquared = (a - b).lengthSquared(); if (minDistSquared > curDistSquared) { minDistSquared = curDistSquared; this->a = a; this->b = b; } } } } std::istream &operator>>(std::istream &in, Model &model) { int count; if (!(in >> count)) { throw model_format_error("unable to read number of figures"); } std::vector<PFigure> figures; size_t selected_id = 0; while (count -- > 0) { std::string type; if (!(in >> type)) { throw model_format_error("unable to read fngure type"); } if (type == "segment" || type == "segment_connection") { std::shared_ptr<figures::Segment> segm; if (type == "segment_connection") { size_t aId, bId; if (!(in >> aId >> bId)) { throw model_format_error("unable to read connection information"); } aId--, bId--; if (aId >= figures.size() || bId >= figures.size()) { throw model_format_error("invalid figures in connection"); } auto figA = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(aId)); auto figB = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(bId)); if (!figA || !figB) { throw model_format_error("invalid reference in connection"); } segm = std::make_shared<figures::SegmentConnection>(figA, figB); } else { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read segment"); } segm = std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2)); } bool arrowA, arrowB; if (!(in >> arrowA >> arrowB)) { throw model_format_error("unable to read segment"); } segm->setArrowedA(arrowA); segm->setArrowedB(arrowB); figures.push_back(segm); } else if (type == "rectangle") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read rectangle"); } figures.push_back(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read ellipse"); } figures.push_back(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "selected=") { if (selected_id != 0) { throw model_format_error("two figures are selected"); } if (!(in >> selected_id)) { throw model_format_error("unable to read selected figure id"); } } else { throw model_format_error("unknown type: '" + type + "'"); } } for (PFigure figure : figures) { model.addFigure(figure); } if (selected_id != 0) { model.selectedFigure = figures.at(selected_id - 1); } return in; } class FigurePrinter : public FigureVisitor { public: FigurePrinter(std::ostream &out, const std::map<PFigure, size_t> &ids) : out(out), ids(ids) {} virtual void accept(figures::Segment &segm) { out << "segment "; printPoint(segm.getA()); out << " "; printPoint(segm.getB()); out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::SegmentConnection &segm) { out << "segment_connection "; out << ids.at(segm.getFigureA()) << " "; out << ids.at(segm.getFigureB()) << " "; out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::Ellipse &fig) { out << "ellipse "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } virtual void accept(figures::Rectangle &fig) { out << "rectangle "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } private: std::ostream &out; const std::map<PFigure, size_t> &ids; void printPoint(const Point &p) { out << p.x << " " << p.y; } void printBoundingBox(const BoundingBox &box) { printPoint(box.leftDown); out << " "; printPoint(box.rightUp); } }; std::ostream &operator<<(std::ostream &out, Model &model) { out << (model.size() + !!model.selectedFigure) << '\n'; std::map<PFigure, size_t> ids; for (PFigure figure : model) { size_t id = ids.size() + 1; ids[figure] = id; } FigurePrinter printer(out, ids); for (PFigure figure : model) { figure->visit(printer); } if (model.selectedFigure) { out << "selected= " << ids.at(model.selectedFigure) << "\n"; } return out; } class CloningVisitor : public FigureVisitor { public: CloningVisitor(const std::map<PFigure, PFigure> &mapping) : mapping(mapping) {} PFigure getResult() { return result; } virtual void accept(figures::Segment &fig) override { result = std::make_shared<figures::Segment>(fig); } virtual void accept(figures::SegmentConnection &fig) { auto newA = std::dynamic_pointer_cast<figures::BoundedFigure>(mapping.at(fig.getFigureA())); auto newB = std::dynamic_pointer_cast<figures::BoundedFigure>(mapping.at(fig.getFigureB())); auto res = std::make_shared<figures::SegmentConnection>(newA, newB); res->setArrowedA(fig.getArrowedA()); res->setArrowedB(fig.getArrowedB()); result = res; } virtual void accept(figures::Ellipse &fig) { result = std::make_shared<figures::Ellipse>(fig); } virtual void accept(figures::Rectangle &fig) { result = std::make_shared<figures::Rectangle>(fig); } private: const std::map<PFigure, PFigure> &mapping; PFigure result; }; PFigure clone(PFigure figure, const std::map<PFigure, PFigure> &othersMapping) { CloningVisitor visitor(othersMapping); figure->visit(visitor); return visitor.getResult(); } void exportModelToSvg(Model &m, std::ostream &out) { FigureSvgPainter painter(out); painter.printHeader(); for (PFigure figure : m) { figure->visit(painter); } painter.printFooter(); } <commit_msg>#33: SegmentConnection::recalculate() was updated: now it connects centers of figures and cuts the result so it connects borders<commit_after>#include "model.h" #include "figurepainter.h" #include <string> #include <algorithm> #include <map> double figures::Segment::getApproximateDistanceToBorder(const Point &p) { double res = std::min((p - a).length(), (p - b).length()); // Please note that here we do not care about floatint-point error, // as if 'start' falls near 'a' or 'b', we've already calculated it if (Point::dotProduct(p - a, b - a) >= 0 && Point::dotProduct(p - b, a - b) >= 0) { res = std::min(res, getDistanceToLine(p)); } return res; } double figures::Segment::getDistanceToLine(const Point &p) { // Coefficients of A*x + B*y + C = 0 double A = b.y - a.y; double B = a.x - b.x; double C = -A * a.x - B * a.y; // normalization of the equation double D = sqrt(A * A + B * B); if (fabs(D) < 1e-8) { return HUGE_VAL; } // degenerate case A /= D; B /= D; C /= D; return fabs(A * p.x + B * p.y + C); } double figures::Rectangle::getApproximateDistanceToBorder(const Point &p) { bool inX = box.leftDown.x <= p.x && p.x <= box.rightUp.x; bool inY = box.leftDown.y <= p.y && p.y <= box.rightUp.y; double res = HUGE_VAL; if (inX) { // Point lies in a vertical bar bounded by Left and Right res = std::min(res, fabs(p.y - box.leftDown.y)); res = std::min(res, fabs(p.y - box.rightUp.y)); } if (inY) { // Point lies in a horizontal bar res = std::min(res, fabs(p.x - box.leftDown.x)); res = std::min(res, fabs(p.x - box.rightUp.x)); } if (!inX && !inY) { res = std::min(res, (p - box.leftDown).length()); res = std::min(res, (p - box.rightUp).length()); res = std::min(res, (p - box.leftUp()).length()); res = std::min(res, (p - box.rightDown()).length()); } return res; } double figures::Ellipse::getApproximateDistanceToBorder(const Point &_p) { Point p = _p - box.center(); if (p.length() < 1e-7) { return std::min(box.width(), box.height()) / 2; } double a = box.width() / 2; double b = box.height() / 2; Point near = p; near.x /= a; near.y /= b; double d = near.length(); near.x /= d; near.y /= d; near.x *= a; near.y *= b; return (p - near).length(); } /* * Consider a segment from figure's center to point b * Intersection point of this segment with figure is returned, * If there is no such one or figure is degenerate, center is returned instead */ class CutSegmentFromCenterVisitor : FigureVisitor { static constexpr double EPS = 1e-8; Point b; Point _result; CutSegmentFromCenterVisitor(const Point &_b) : b(_b) {} public: Point result() { return _result; } virtual void accept(figures::Ellipse &figure) override { BoundingBox ellipse = figure.getBoundingBox(); _result = ellipse.center(); if (ellipse.width() < EPS || ellipse.height() < EPS) { return; } Point direction = b - ellipse.center(); double aspectRatio = ellipse.width() / ellipse.height(); direction.x /= aspectRatio; double r = ellipse.height() / 2; if (direction.length() < r - EPS) { return; } direction = direction * (r / direction.length()); direction.x *= aspectRatio; _result = ellipse.center() + direction; } virtual void accept(figures::Rectangle &figure) override { BoundingBox rect = figure.getBoundingBox(); _result = rect.center(); if (rect.width() < EPS|| rect.height() < EPS) { return; } Point direction = b - rect.center(); double aspectRatio = rect.width() / rect.height(); direction.x /= aspectRatio; double r = rect.height() / 2; double compressRatio = std::min(r / fabs(direction.x), r / fabs(direction.y)); if (compressRatio > 1 - EPS) { return; } direction = direction * compressRatio; direction.x *= aspectRatio; _result = rect.center() + direction; } virtual void accept(figures::Segment &) override { throw visitor_implementation_not_found(); } virtual void accept(figures::SegmentConnection &) override { throw visitor_implementation_not_found(); } static Point apply(PFigure figure, Point b) { CutSegmentFromCenterVisitor visitor(b); figure->visit(visitor); return visitor.result(); } }; void figures::SegmentConnection::recalculate() { Point centerA = figA->getBoundingBox().center(); Point centerB = figB->getBoundingBox().center(); this->a = CutSegmentFromCenterVisitor::apply(figA, centerB); this->b = CutSegmentFromCenterVisitor::apply(figB, centerA); } std::istream &operator>>(std::istream &in, Model &model) { int count; if (!(in >> count)) { throw model_format_error("unable to read number of figures"); } std::vector<PFigure> figures; size_t selected_id = 0; while (count -- > 0) { std::string type; if (!(in >> type)) { throw model_format_error("unable to read fngure type"); } if (type == "segment" || type == "segment_connection") { std::shared_ptr<figures::Segment> segm; if (type == "segment_connection") { size_t aId, bId; if (!(in >> aId >> bId)) { throw model_format_error("unable to read connection information"); } aId--, bId--; if (aId >= figures.size() || bId >= figures.size()) { throw model_format_error("invalid figures in connection"); } auto figA = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(aId)); auto figB = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(bId)); if (!figA || !figB) { throw model_format_error("invalid reference in connection"); } segm = std::make_shared<figures::SegmentConnection>(figA, figB); } else { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read segment"); } segm = std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2)); } bool arrowA, arrowB; if (!(in >> arrowA >> arrowB)) { throw model_format_error("unable to read segment"); } segm->setArrowedA(arrowA); segm->setArrowedB(arrowB); figures.push_back(segm); } else if (type == "rectangle") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read rectangle"); } figures.push_back(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read ellipse"); } figures.push_back(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "selected=") { if (selected_id != 0) { throw model_format_error("two figures are selected"); } if (!(in >> selected_id)) { throw model_format_error("unable to read selected figure id"); } } else { throw model_format_error("unknown type: '" + type + "'"); } } for (PFigure figure : figures) { model.addFigure(figure); } if (selected_id != 0) { model.selectedFigure = figures.at(selected_id - 1); } return in; } class FigurePrinter : public FigureVisitor { public: FigurePrinter(std::ostream &out, const std::map<PFigure, size_t> &ids) : out(out), ids(ids) {} virtual void accept(figures::Segment &segm) { out << "segment "; printPoint(segm.getA()); out << " "; printPoint(segm.getB()); out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::SegmentConnection &segm) { out << "segment_connection "; out << ids.at(segm.getFigureA()) << " "; out << ids.at(segm.getFigureB()) << " "; out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::Ellipse &fig) { out << "ellipse "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } virtual void accept(figures::Rectangle &fig) { out << "rectangle "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } private: std::ostream &out; const std::map<PFigure, size_t> &ids; void printPoint(const Point &p) { out << p.x << " " << p.y; } void printBoundingBox(const BoundingBox &box) { printPoint(box.leftDown); out << " "; printPoint(box.rightUp); } }; std::ostream &operator<<(std::ostream &out, Model &model) { out << (model.size() + !!model.selectedFigure) << '\n'; std::map<PFigure, size_t> ids; for (PFigure figure : model) { size_t id = ids.size() + 1; ids[figure] = id; } FigurePrinter printer(out, ids); for (PFigure figure : model) { figure->visit(printer); } if (model.selectedFigure) { out << "selected= " << ids.at(model.selectedFigure) << "\n"; } return out; } class CloningVisitor : public FigureVisitor { public: CloningVisitor(const std::map<PFigure, PFigure> &mapping) : mapping(mapping) {} PFigure getResult() { return result; } virtual void accept(figures::Segment &fig) override { result = std::make_shared<figures::Segment>(fig); } virtual void accept(figures::SegmentConnection &fig) { auto newA = std::dynamic_pointer_cast<figures::BoundedFigure>(mapping.at(fig.getFigureA())); auto newB = std::dynamic_pointer_cast<figures::BoundedFigure>(mapping.at(fig.getFigureB())); auto res = std::make_shared<figures::SegmentConnection>(newA, newB); res->setArrowedA(fig.getArrowedA()); res->setArrowedB(fig.getArrowedB()); result = res; } virtual void accept(figures::Ellipse &fig) { result = std::make_shared<figures::Ellipse>(fig); } virtual void accept(figures::Rectangle &fig) { result = std::make_shared<figures::Rectangle>(fig); } private: const std::map<PFigure, PFigure> &mapping; PFigure result; }; PFigure clone(PFigure figure, const std::map<PFigure, PFigure> &othersMapping) { CloningVisitor visitor(othersMapping); figure->visit(visitor); return visitor.getResult(); } void exportModelToSvg(Model &m, std::ostream &out) { FigureSvgPainter painter(out); painter.printHeader(); for (PFigure figure : m) { figure->visit(painter); } painter.printFooter(); } <|endoftext|>
<commit_before>#include "llvm/Reoptimizer/Mapping/FInfo.h" #include "llvm/Pass.h" #include "llvm/Module.h" namespace { class FunctionInfo : public Pass { std::ostream &Out; public: FunctionInfo(std::ostream &out) : Out(out){} const char* getPassName() const{return "Sparc FunctionInfo";} bool run(Module &M); private: void FunctionInfo::writePrologue(const char *area, const char *label); void FunctionInfo::writeEpilogue(const char *area, const char *label); }; } Pass *getFunctionInfo(std::ostream &out){ return new FunctionInfo(out); } bool FunctionInfo::run(Module &M){ unsigned f; writePrologue("FUNCTION MAP", "FunctionBB"); f=0; for(Module::iterator FI=M.begin(), FE=M.end(); FE!=FI; ++FI){ if(FI->isExternal()) continue; Out << "\t.xword BBMIMap"<<f<<"\n"; ++f; } writeEpilogue("FUNCTION MAP", "FunctionBB"); writePrologue("FUNCTION MAP", "FunctionLI"); f=0; for(Module::iterator FI=M.begin(), FE=M.end(); FE!=FI; ++FI){ if(FI->isExternal()) continue; Out << "\t.xword LMIMap"<<f<<"\n"; ++f; } writeEpilogue("FUNCTION MAP", "FunctionLI"); return false; } void FunctionInfo::writePrologue(const char *area, const char *label){ Out << "\n\n\n!"<<area<<"\n"; Out << "\t.section \".rodata\"\n\t.align 8\n"; Out << "\t.global "<<label<<"\n"; Out << "\t.type "<<label<<",#object\n"; Out << label<<":\n"; //Out << "\t.word .end_"<<label<<"-"<<label<<"\n"; } void FunctionInfo::writeEpilogue(const char *area, const char *label){ Out << ".end_" << label << ":\n"; Out << "\t.size " << label << ", .end_" << label << "-" << label << "\n\n\n\n"; //Out << "\n\n!" << area << " Length\n"; //Out << "\t.section \".bbdata\",#alloc,#write\n"; //Out << "\t.global " << label << "_length\n"; //Out << "\t.align 4\n"; //Out << "\t.type " << label << "_length,#object\n"; //Out << "\t.size "<< label <<"_length,4\n"; //Out << label <<" _length:\n"; //Out << "\t.word\t.end_"<<label<<"-"<<label<<"\n\n\n\n"; } <commit_msg>Minor cleanups. This pass should be moved to lib/Target/Sparc since it's sparc specific It also needs a file comment.<commit_after>#include "llvm/Reoptimizer/Mapping/FInfo.h" #include "llvm/Pass.h" #include "llvm/Module.h" namespace { class FunctionInfo : public Pass { std::ostream &Out; public: FunctionInfo(std::ostream &out) : Out(out){} const char* getPassName() const{ return "Sparc FunctionInfo"; } bool run(Module &M); private: void writePrologue(const char *area, const char *label); void writeEpilogue(const char *area, const char *label); }; } Pass *getFunctionInfo(std::ostream &out){ return new FunctionInfo(out); } bool FunctionInfo::run(Module &M){ unsigned f; writePrologue("FUNCTION MAP", "FunctionBB"); f=0; for(Module::iterator FI=M.begin(), FE=M.end(); FE!=FI; ++FI){ if(FI->isExternal()) continue; Out << "\t.xword BBMIMap"<<f<<"\n"; ++f; } writeEpilogue("FUNCTION MAP", "FunctionBB"); writePrologue("FUNCTION MAP", "FunctionLI"); f=0; for(Module::iterator FI=M.begin(), FE=M.end(); FE!=FI; ++FI){ if(FI->isExternal()) continue; Out << "\t.xword LMIMap"<<f<<"\n"; ++f; } writeEpilogue("FUNCTION MAP", "FunctionLI"); return false; } void FunctionInfo::writePrologue(const char *area, const char *label){ Out << "\n\n\n!"<<area<<"\n"; Out << "\t.section \".rodata\"\n\t.align 8\n"; Out << "\t.global "<<label<<"\n"; Out << "\t.type "<<label<<",#object\n"; Out << label<<":\n"; //Out << "\t.word .end_"<<label<<"-"<<label<<"\n"; } void FunctionInfo::writeEpilogue(const char *area, const char *label){ Out << ".end_" << label << ":\n"; Out << "\t.size " << label << ", .end_" << label << "-" << label << "\n\n\n\n"; //Out << "\n\n!" << area << " Length\n"; //Out << "\t.section \".bbdata\",#alloc,#write\n"; //Out << "\t.global " << label << "_length\n"; //Out << "\t.align 4\n"; //Out << "\t.type " << label << "_length,#object\n"; //Out << "\t.size "<< label <<"_length,4\n"; //Out << label <<" _length:\n"; //Out << "\t.word\t.end_"<<label<<"-"<<label<<"\n\n\n\n"; } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Baozeng Ding <sploving1@gmail.com> // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Exception.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/Validation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" extern "C" { /// Throw an InvalidDerefException if the Arg pointer is invalid. ///\param Interp: The interpreter that has compiled the code. ///\param Expr: The expression corresponding determining the pointer value. ///\param Arg: The pointer to be checked. ///\returns void*, const-cast from Arg, to reduce the complexity in the /// calling AST nodes, at the expense of possibly doing a /// T* -> const void* -> const_cast<void*> -> T* round trip. void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr, const void* Arg) { const clang::Expr* const E = (const clang::Expr*)Expr; // The isValidAddress function return true even when the pointer is // null thus the checks have to be done before returning successfully from the // function in this specific order. if (!Arg) { cling::Interpreter* I = (cling::Interpreter*)Interp; clang::Sema& S = I->getCI()->getSema(); // Print a nice backtrace. I->getCallbacks()->PrintStackTrace(); throw cling::InvalidDerefException(&S, E, cling::InvalidDerefException::DerefType::NULL_DEREF); } else if (!cling::utils::isAddressValid(Arg)) { cling::Interpreter* I = (cling::Interpreter*)Interp; clang::Sema& S = I->getCI()->getSema(); // Print a nice backtrace. I->getCallbacks()->PrintStackTrace(); throw cling::InvalidDerefException(&S, E, cling::InvalidDerefException::DerefType::INVALID_MEM); } return const_cast<void*>(Arg); } } namespace cling { InterpreterException::InterpreterException(const std::string& What) : std::runtime_error(What), m_Sema(nullptr) {} InterpreterException::InterpreterException(const char* What, clang::Sema* S) : std::runtime_error(What), m_Sema(S) {} bool InterpreterException::diagnose() const { return false; } InterpreterException::~InterpreterException() noexcept {} InvalidDerefException::InvalidDerefException(clang::Sema* S, const clang::Expr* E, DerefType type) : InterpreterException(type == INVALID_MEM ? "Trying to access a pointer that points to an invalid memory address." : "Trying to dereference null pointer or trying to call routine taking " "non-null arguments", S), m_Arg(E), m_Type(type) {} InvalidDerefException::~InvalidDerefException() noexcept {} bool InvalidDerefException::diagnose() const { // Construct custom diagnostic: warning for invalid memory address; // no equivalent in clang. if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) { clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics(); unsigned DiagID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning, "invalid memory pointer passed to a callee:"); Diags.Report(m_Arg->getLocStart(), DiagID) << m_Arg->getSourceRange(); } else m_Sema->Diag(m_Arg->getLocStart(), clang::diag::warn_null_arg) << m_Arg->getSourceRange(); return true; } CompilationException::CompilationException(const std::string& Reason) : InterpreterException(Reason) {} CompilationException::~CompilationException() noexcept {} void CompilationException::throwingHandler(void * /*user_data*/, const std::string& reason, bool /*gen_crash_diag*/) { throw cling::CompilationException(reason); } } // end namespace cling <commit_msg>Fix a crash when using an undeclared identifier (Jira #ROOT-10193)<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Baozeng Ding <sploving1@gmail.com> // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Exception.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Utils/Validation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" extern "C" { /// Throw an InvalidDerefException if the Arg pointer is invalid. ///\param Interp: The interpreter that has compiled the code. ///\param Expr: The expression corresponding determining the pointer value. ///\param Arg: The pointer to be checked. ///\returns void*, const-cast from Arg, to reduce the complexity in the /// calling AST nodes, at the expense of possibly doing a /// T* -> const void* -> const_cast<void*> -> T* round trip. void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr, const void* Arg) { const clang::Expr* const E = (const clang::Expr*)Expr; // The isValidAddress function return true even when the pointer is // null thus the checks have to be done before returning successfully from the // function in this specific order. if (!Arg) { cling::Interpreter* I = (cling::Interpreter*)Interp; clang::Sema& S = I->getCI()->getSema(); // Print a nice backtrace. I->getCallbacks()->PrintStackTrace(); throw cling::InvalidDerefException(&S, E, cling::InvalidDerefException::DerefType::NULL_DEREF); } else if (!cling::utils::isAddressValid(Arg)) { cling::Interpreter* I = (cling::Interpreter*)Interp; clang::Sema& S = I->getCI()->getSema(); // Print a nice backtrace. I->getCallbacks()->PrintStackTrace(); throw cling::InvalidDerefException(&S, E, cling::InvalidDerefException::DerefType::INVALID_MEM); } return const_cast<void*>(Arg); } } namespace cling { InterpreterException::InterpreterException(const std::string& What) : std::runtime_error(What), m_Sema(nullptr) {} InterpreterException::InterpreterException(const char* What, clang::Sema* S) : std::runtime_error(What), m_Sema(S) {} bool InterpreterException::diagnose() const { return false; } InterpreterException::~InterpreterException() noexcept {} InvalidDerefException::InvalidDerefException(clang::Sema* S, const clang::Expr* E, DerefType type) : InterpreterException(type == INVALID_MEM ? "Trying to access a pointer that points to an invalid memory address." : "Trying to dereference null pointer or trying to call routine taking " "non-null arguments", S), m_Arg(E), m_Type(type) {} InvalidDerefException::~InvalidDerefException() noexcept {} bool InvalidDerefException::diagnose() const { // Construct custom diagnostic: warning for invalid memory address; // no equivalent in clang. if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) { clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics(); unsigned DiagID = Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning, "invalid memory pointer passed to a callee:"); Diags.Report(m_Arg->getLocStart(), DiagID) << m_Arg->getSourceRange(); } else m_Sema->Diag(m_Arg->getLocStart(), clang::diag::warn_null_arg) << m_Arg->getSourceRange(); return true; } CompilationException::CompilationException(const std::string& Reason) : InterpreterException(Reason) {} CompilationException::~CompilationException() noexcept {} void CompilationException::throwingHandler(void * /*user_data*/, const std::string& reason, bool /*gen_crash_diag*/) { #ifndef _MSC_VER throw cling::CompilationException(reason); #endif } } // end namespace cling <|endoftext|>
<commit_before>#include <limits> #include <stdexcept> //test #include <iostream> #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { this->triangles.push_back(Triangle(&mesh, 0)); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->aabb = AABB(min, max); if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left); } if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right); } } void BVHNode::insert(std::vector<Triangle>* triangles) { this->triangles.push_back(triangles->back()); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); triangles->pop_back(); for (unsigned int var = 2; var < triangles->size(); ++var) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { if (this->aabb.intersect(ray)) { if (left == NULL && right == NULL) { } } return false; } <commit_msg>snapshot<commit_after>#include <limits> #include <stdexcept> //test #include <iostream> #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { this->triangles.push_back(Triangle(&mesh, 0)); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->aabb = AABB(min, max); if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left); } if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right); } } void BVHNode::insert(std::vector<Triangle>* triangles) { this->triangles.push_back(triangles->back()); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); triangles->pop_back(); for (unsigned int var = 2; var < triangles->size(); ++var) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { if (this->aabb.intersect(ray)) { if (left == NULL && right == NULL) for (unsigned int var = 1; var < triangles.size(); ++var) if (triangles.at(var).intersect(ray, intersection)) return true; else return left->intersect(ray, intersection) || right->intersect(ray, intersection); } return false; } <|endoftext|>
<commit_before>#include "main.h" #include "viewer.h" #include "lang_val.h" #include "registry.h" #include "config.h" //#include "control.h" #include "orz/logger.h" #include "ipc_client.h" #include "ipc_server.h" #include <boost/locale.hpp> #include <boost/scoped_array.hpp> #include <wx/app.h> #include <wx/msgdlg.h> #include <wx/snglinst.h> const wchar_t* ClassName = L"PictusMainMutex"; class MyApp:public wxApp { public: bool OnInit() override { SetVendorName("Poppeman"); if(argc > 1) { // Workaround for bug or weird wxWidgets behavior. // "something.exe" "some long argument" results in the following: // argv[0] = something.exe // argv[1] = some long argument" std::string params = ToAString(argv[1]); if (params[params.size() - 1] == '"' && params[0] != '"') { params = params.substr(0, params.size() - 1); } return start_app(params) == EXIT_SUCCESS; } else { return start_app("") == EXIT_SUCCESS; } } MyApp(): m_singleMutex(ClassName) {} ~MyApp() {} private: App::Viewer* m_viewer = nullptr; Img::CodecFactoryStore cfs; wxSingleInstanceChecker m_singleMutex; std::shared_ptr<IPC::OpenFileServer> m_server; int start_app(std::string params) { if (params == "--cleanup") { // If the user refused to uninstall the previous version when upgrading, the uninstaller will likely call pictus.exe with --cleanup // as parameter. Let's not throw up a blank Pictus windows in that situation. // This applies when 1.1.4.0 or older was installed. return EXIT_SUCCESS; } // Make sure that boost (and boost.filesystem) uses UTF-8 on Windows whenever possible. std::locale::global(boost::locale::generator().generate("")); boost::filesystem::path::imbue(std::locale()); cfs.AddBuiltinCodecs(); try { auto cfg = Reg::Load(App::cg_SettingsLocation); // TODO: Control logging by some other mechanism, such as an .ini setting //Log.SetOutput(assure_folder(App::cg_RunLogLocation)); Intl::LanguageTable(c_lang_strings); Intl::CurrentLanguage(cfg.View.Language); m_viewer = new App::Viewer(&cfs, cfg); m_viewer->CreateWindow(); if (cfg.View.MultipleInstances == false && m_singleMutex.IsAnotherRunning()) { auto client = std::make_shared<IPC::OpenFileClient>(); auto con = dynamic_cast<IPC::OpenFileConnection*>(client->MakeConnection(L"localhost", ClassName, L"OPENFILE")); if (con != nullptr) { con->SendOpenFile(params); con->Disconnect(); } return EXIT_FAILURE; } m_server = std::make_shared<IPC::OpenFileServer>(m_viewer); m_server->Create(ClassName); // Attempt to display viewer if (m_viewer->Init(params.c_str())) { m_viewer->Show(true); } //viewer.StartApplication(); } catch(Err::DuplicateInstance&) { // This is not something out of the ordinary. } catch(std::exception& e) { Log << "Exception caught:\n" << e.what() << "\n"; wxMessageBox((L"An error occurred: " + UTF8ToWString(e.what())).c_str(), L"Pictus Error", wxOK); //throw; // Good for debugging } //Win::Control::DestructControls(); return EXIT_SUCCESS; } }; wxIMPLEMENT_APP(MyApp); <commit_msg>Avoid corrupting non-ASCII characters in command line arguments<commit_after>#include "main.h" #include "viewer.h" #include "lang_val.h" #include "registry.h" #include "config.h" //#include "control.h" #include "orz/logger.h" #include "ipc_client.h" #include "ipc_server.h" #include <boost/locale.hpp> #include <boost/scoped_array.hpp> #include <wx/app.h> #include <wx/msgdlg.h> #include <wx/snglinst.h> const wchar_t* ClassName = L"PictusMainMutex"; class MyApp:public wxApp { public: bool OnInit() override { SetVendorName("Poppeman"); if(argc > 1) { // Workaround for bug or weird wxWidgets behavior. // "something.exe" "some long argument" results in the following: // argv[0] = something.exe // argv[1] = some long argument" std::string params = argv[1].ToUTF8(); if (params[params.size() - 1] == '"' && params[0] != '"') { params = params.substr(0, params.size() - 1); } return start_app(params) == EXIT_SUCCESS; } else { return start_app("") == EXIT_SUCCESS; } } MyApp(): m_singleMutex(ClassName) {} ~MyApp() {} private: App::Viewer* m_viewer = nullptr; Img::CodecFactoryStore cfs; wxSingleInstanceChecker m_singleMutex; std::shared_ptr<IPC::OpenFileServer> m_server; int start_app(std::string params) { if (params == "--cleanup") { // If the user refused to uninstall the previous version when upgrading, the uninstaller will likely call pictus.exe with --cleanup // as parameter. Let's not throw up a blank Pictus windows in that situation. // This applies when 1.1.4.0 or older was installed. return EXIT_SUCCESS; } // Make sure that boost (and boost.filesystem) uses UTF-8 on Windows whenever possible. std::locale::global(boost::locale::generator().generate("")); boost::filesystem::path::imbue(std::locale()); cfs.AddBuiltinCodecs(); try { auto cfg = Reg::Load(App::cg_SettingsLocation); // TODO: Control logging by some other mechanism, such as an .ini setting //Log.SetOutput(assure_folder(App::cg_RunLogLocation)); Intl::LanguageTable(c_lang_strings); Intl::CurrentLanguage(cfg.View.Language); m_viewer = new App::Viewer(&cfs, cfg); m_viewer->CreateWindow(); if (cfg.View.MultipleInstances == false && m_singleMutex.IsAnotherRunning()) { auto client = std::make_shared<IPC::OpenFileClient>(); auto con = dynamic_cast<IPC::OpenFileConnection*>(client->MakeConnection(L"localhost", ClassName, L"OPENFILE")); if (con != nullptr) { con->SendOpenFile(params); con->Disconnect(); } return EXIT_FAILURE; } m_server = std::make_shared<IPC::OpenFileServer>(m_viewer); m_server->Create(ClassName); // Attempt to display viewer if (m_viewer->Init(params.c_str())) { m_viewer->Show(true); } //viewer.StartApplication(); } catch(Err::DuplicateInstance&) { // This is not something out of the ordinary. } catch(std::exception& e) { Log << "Exception caught:\n" << e.what() << "\n"; wxMessageBox((L"An error occurred: " + UTF8ToWString(e.what())).c_str(), L"Pictus Error", wxOK); //throw; // Good for debugging } //Win::Control::DestructControls(); return EXIT_SUCCESS; } }; wxIMPLEMENT_APP(MyApp); <|endoftext|>
<commit_before>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE ExactTransientSolution #define BOOST_TEST_MAIN #include <cap/energy_storage_device.h> #include <cap/mp_values.h> #include <deal.II/base/types.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <cmath> #include <iostream> #include <fstream> #include <numeric> namespace cap { void verification_problem(std::shared_ptr<cap::EnergyStorageDevice> dev) { // gold vs computed double const charge_current = 5e-3; double const charge_time = 0.01; double const time_step = 1e-4; double const epsilon = time_step * 1.0e-4; unsigned int pos = 0; double computed_voltage; double const percent_tolerance = 1e-6; std::vector<double> gold_solution(10); gold_solution[0] = 1.725914356067658e-01; gold_solution[1] = 1.802025636145941e-01; gold_solution[2] = 1.859326352495181e-01; gold_solution[3] = 1.905978440188036e-01; gold_solution[4] = 1.946022119085378e-01; gold_solution[5] = 1.981601232287249e-01; gold_solution[6] = 2.013936650249285e-01; gold_solution[7] = 2.043807296399895e-01; gold_solution[8] = 2.071701713934283e-01; gold_solution[9] = 2.097979282542038e-01; for (double time = 0.0; time <= charge_time + epsilon; time += time_step) { dev->evolve_one_time_step_constant_current(time_step, charge_current); dev->get_voltage(computed_voltage); if ((std::abs(time + time_step - 1e-3) < 1e-7) || (std::abs(time + time_step - 2e-3) < 1e-7) || (std::abs(time + time_step - 3e-3) < 1e-7) || (std::abs(time + time_step - 4e-3) < 1e-7) || (std::abs(time + time_step - 5e-3) < 1e-7) || (std::abs(time + time_step - 6e-3) < 1e-7) || (std::abs(time + time_step - 7e-3) < 1e-7) || (std::abs(time + time_step - 8e-3) < 1e-7) || (std::abs(time + time_step - 9e-3) < 1e-7) || (std::abs(time + time_step - 10e-3) < 1e-7)) { BOOST_CHECK_CLOSE(computed_voltage, gold_solution[pos], percent_tolerance); ++pos; } } } } // end namespace cap BOOST_AUTO_TEST_CASE(test_exact_transient_solution) { // parse input file boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(boost::mpi::communicator(), device_database); cap::verification_problem(device); } <commit_msg>Relax tolerance in test_exact_transient_solution.cc<commit_after>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE ExactTransientSolution #define BOOST_TEST_MAIN #include <cap/energy_storage_device.h> #include <cap/mp_values.h> #include <deal.II/base/types.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <cmath> #include <iostream> #include <fstream> #include <numeric> namespace cap { void verification_problem(std::shared_ptr<cap::EnergyStorageDevice> dev) { // gold vs computed double const charge_current = 5e-3; double const charge_time = 0.01; double const time_step = 1e-4; double const epsilon = time_step * 1.0e-4; unsigned int pos = 0; double computed_voltage; // check that error less than 1e-5 % AND less than 1 microvolt double const percent_tolerance = 1e-5; double const tolerance = 1e-6; std::vector<double> gold_solution(10); gold_solution[0] = 1.725914356067658e-01; gold_solution[1] = 1.802025636145941e-01; gold_solution[2] = 1.859326352495181e-01; gold_solution[3] = 1.905978440188036e-01; gold_solution[4] = 1.946022119085378e-01; gold_solution[5] = 1.981601232287249e-01; gold_solution[6] = 2.013936650249285e-01; gold_solution[7] = 2.043807296399895e-01; gold_solution[8] = 2.071701713934283e-01; gold_solution[9] = 2.097979282542038e-01; for (double time = 0.0; time <= charge_time + epsilon; time += time_step) { dev->evolve_one_time_step_constant_current(time_step, charge_current); dev->get_voltage(computed_voltage); if ((std::abs(time + time_step - 1e-3) < 1e-7) || (std::abs(time + time_step - 2e-3) < 1e-7) || (std::abs(time + time_step - 3e-3) < 1e-7) || (std::abs(time + time_step - 4e-3) < 1e-7) || (std::abs(time + time_step - 5e-3) < 1e-7) || (std::abs(time + time_step - 6e-3) < 1e-7) || (std::abs(time + time_step - 7e-3) < 1e-7) || (std::abs(time + time_step - 8e-3) < 1e-7) || (std::abs(time + time_step - 9e-3) < 1e-7) || (std::abs(time + time_step - 10e-3) < 1e-7)) { BOOST_CHECK_CLOSE(computed_voltage, gold_solution[pos], percent_tolerance); BOOST_CHECK_SMALL(computed_voltage - gold_solution[pos], tolerance); ++pos; } } } } // end namespace cap BOOST_AUTO_TEST_CASE(test_exact_transient_solution) { // parse input file boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(boost::mpi::communicator(), device_database); cap::verification_problem(device); } <|endoftext|>
<commit_before>#include "RadioUtils.h" #include <EEPROM.h> #include "../../src/common.h" #include <RF12.h> RadioUtils::RadioUtils(){ dynamicRouting = false; distance = 100; int nodeID = 0; int groupID = 0; int parentID = 0; } void RadioUtils::initialize(){ nodeID = EEPROM.read(NODE_ID_LOCATION); groupID = EEPROM.read(GROUP_ID_LOCATION); parentID = EEPROM.read(PARENT_ID_LOCATION); rf12_initialize(nodeID, FREQUENCY, groupID); } int RadioUtils::getNodeID(){ return nodeID; } void RadioUtils::setTransmitPower(byte txPower){ rf12_control(0x9850 | (txPower > 7 ? 7 : txPower)); } int RadioUtils::getGroupID(){ return groupID; } int RadioUtils::getParentID(){ return parentID; } int RadioUtils::routeUpdateDistance(int d, byte p){ if(d < distance){ distance = d; parentID = p; return 1; } else { return 0; } } int RadioUtils::routeGetLength(){ return distance; } int RadioUtils::routePerformOneStep(){ for(int i = 0; i < TIMEOUT; i++) { if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ char text[MAX_MESSAGE_LENGTH] = ""; for (byte i = 0; i < rf12_len; ++i) { text[i] = rf12_data[i]; } String payload = String(text); int d = routeParseDistance(payload); byte id = 0; byte saveHdr; saveHdr = rf12_hdr; getID(&saveHdr, &id); int result = routeUpdateDistance(d+1, id); if(result == 1){ //TODO print } routeBroadcastLength(); return 1; } } delay(90); } routeBroadcastLength(); return -1; } void RadioUtils::routeBroadcastLength(){ byte hdr = 0; String d = String(distance, DEC); String message = String("distance:" + d); char payload[15] = ""; message.toCharArray(payload, message.length()+d.length()+1); setBroadcast(&hdr); resetAck(&hdr); rf12_sendNow(hdr, payload, message.length()); } int RadioUtils::routeParseDistance(String d){ String head = d.substring(0,d.indexOf(':')); if(head == "distance"){ String body = d.substring(d.indexOf(':')+1); return body.toInt(); } else { return -1; } } int RadioUtils::setAck(byte* hdr){ byte ackOr = B10000000; *hdr = (*hdr | ackOr); return 0; } int RadioUtils::resetAck(byte* hdr){ byte ackOr = B10000000; *hdr =(*hdr & ~ackOr); return 0; } int RadioUtils::setBroadcast(byte* hdr){ byte broadOr = B10111111; *hdr = (*hdr & broadOr); return 0; } int RadioUtils::setID(byte* hdr, byte id){ byte idAnd = B00011111; id = (id & idAnd); *hdr = (*hdr & ~idAnd); *hdr = (*hdr | id); return 0; } int RadioUtils::getID(byte* hdr, byte* id){ byte idAnd = B00011111; *id = *hdr & idAnd; return 0; } void RadioUtils::enableDynamicRouting(){ dynamicRouting = true; } <commit_msg>routing ack added<commit_after>#include "RadioUtils.h" #include <EEPROM.h> #include "../../src/common.h" #include <RF12.h> RadioUtils::RadioUtils(){ dynamicRouting = false; distance = 100; int nodeID = 0; int groupID = 0; int parentID = 0; } void RadioUtils::initialize(){ nodeID = EEPROM.read(NODE_ID_LOCATION); groupID = EEPROM.read(GROUP_ID_LOCATION); parentID = EEPROM.read(PARENT_ID_LOCATION); rf12_initialize(nodeID, FREQUENCY, groupID); } int RadioUtils::getNodeID(){ return nodeID; } void RadioUtils::setTransmitPower(byte txPower){ rf12_control(0x9850 | (txPower > 7 ? 7 : txPower)); } int RadioUtils::getGroupID(){ return groupID; } int RadioUtils::getParentID(){ return parentID; } int RadioUtils::routeUpdateDistance(int d, byte p){ if(d < distance){ distance = d; parentID = p; return 1; } else { return 0; } } int RadioUtils::routeGetLength(){ return distance; } int RadioUtils::routePerformOneStep(){ for(int i = 0; i < TIMEOUT; i++) { if(rf12_recvDone()){ if(RF12_WANTS_ACK){ rf12_sendStart(RF12_ACK_REPLY,0,0); } if(rf12_crc == 0){ char text[MAX_MESSAGE_LENGTH] = ""; for (byte i = 0; i < rf12_len; ++i) { text[i] = rf12_data[i]; } String payload = String(text); int d = routeParseDistance(payload); byte id = 0; byte saveHdr; saveHdr = rf12_hdr; getID(&saveHdr, &id); int result = routeUpdateDistance(d+1, id); if(result == 1){ //TODO print } routeBroadcastLength(); return 1; } } delay(90); } routeBroadcastLength(); return -1; } void RadioUtils::routeBroadcastLength(){ byte hdr = 0; String d = String(distance, DEC); String message = String("distance:" + d); char payload[15] = ""; message.toCharArray(payload, message.length()+d.length()+1); setBroadcast(&hdr); setAck(&hdr); rf12_sendNow(hdr, payload, message.length()); } int RadioUtils::routeParseDistance(String d){ String head = d.substring(0,d.indexOf(':')); if(head == "distance"){ String body = d.substring(d.indexOf(':')+1); return body.toInt(); } else { return -1; } } int RadioUtils::setAck(byte* hdr){ byte ackOr = B10000000; *hdr = (*hdr | ackOr); return 0; } int RadioUtils::resetAck(byte* hdr){ byte ackOr = B10000000; *hdr =(*hdr & ~ackOr); return 0; } int RadioUtils::setBroadcast(byte* hdr){ byte broadOr = B10111111; *hdr = (*hdr & broadOr); return 0; } int RadioUtils::setID(byte* hdr, byte id){ byte idAnd = B00011111; id = (id & idAnd); *hdr = (*hdr & ~idAnd); *hdr = (*hdr | id); return 0; } int RadioUtils::getID(byte* hdr, byte* id){ byte idAnd = B00011111; *id = *hdr & idAnd; return 0; } void RadioUtils::enableDynamicRouting(){ dynamicRouting = true; } <|endoftext|>
<commit_before>#include <turbodbc/time_helpers.h> #include <sql.h> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace turbodbc { boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0}); int64_t timestamp_to_microseconds(char const * data_pointer) { auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer); intptr_t const microseconds = sql_ts.fraction / 1000; boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day}, {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds}); return (ts - timestamp_epoch).total_microseconds(); } boost::gregorian::date const date_epoch(1970, 1, 1); intptr_t date_to_days(char const * data_pointer) { auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer); boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day); return (date - date_epoch).days(); } } <commit_msg>Add missing includes for Windows<commit_after>#include <turbodbc/time_helpers.h> #ifdef _WIN32 #include <windows.h> #endif #include <cstring> #include <sql.h> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace turbodbc { boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0}); int64_t timestamp_to_microseconds(char const * data_pointer) { auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer); intptr_t const microseconds = sql_ts.fraction / 1000; boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day}, {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds}); return (ts - timestamp_epoch).total_microseconds(); } boost::gregorian::date const date_epoch(1970, 1, 1); intptr_t date_to_days(char const * data_pointer) { auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer); boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day); return (date - date_epoch).days(); } } <|endoftext|>
<commit_before>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===// // // 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 file implements the JIT interfaces for the X86 target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "X86JITInfo.h" #include "X86Relocations.h" #include "X86Subtarget.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/Config/alloca.h" #include <cstdlib> #include <iostream> using namespace llvm; #ifdef _MSC_VER extern "C" void *_AddressOfReturnAddress(void); #pragma intrinsic(_AddressOfReturnAddress) #endif void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) { unsigned char *OldByte = (unsigned char *)Old; *OldByte++ = 0xE9; // Emit JMP opcode. unsigned *OldWord = (unsigned *)OldByte; unsigned NewAddr = (intptr_t)New; unsigned OldAddr = (intptr_t)OldWord; *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code. } /// JITCompilerFunction - This contains the address of the JIT function used to /// compile a function lazily. static TargetJITInfo::JITCompilerFn JITCompilerFunction; // Get the ASMPREFIX for the current host. This is often '_'. #ifndef __USER_LABEL_PREFIX__ #define __USER_LABEL_PREFIX__ #endif #define GETASMPREFIX2(X) #X #define GETASMPREFIX(X) GETASMPREFIX2(X) #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__) // Provide a wrapper for X86CompilationCallback2 that saves non-traditional // callee saved registers, for the fastcc calling convention. extern "C" { #if defined(__x86_64__) // No need to save EAX/EDX for X86-64. void X86CompilationCallback(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback\n" ASMPREFIX "X86CompilationCallback:\n" // Save RBP "pushq %rbp\n" // Save RSP "movq %rsp, %rbp\n" // Save all int arg registers "pushq %rdi\n" "pushq %rsi\n" "pushq %rdx\n" "pushq %rcx\n" "pushq %r8\n" "pushq %r9\n" // Align stack on 16-byte boundary. ESP might not be properly aligned // (8 byte) if this is called from an indirect stub. "andq $-16, %rsp\n" // Save all XMM arg registers "subq $128, %rsp\n" "movaps %xmm0, (%rsp)\n" "movaps %xmm1, 16(%rsp)\n" "movaps %xmm2, 32(%rsp)\n" "movaps %xmm3, 48(%rsp)\n" "movaps %xmm4, 64(%rsp)\n" "movaps %xmm5, 80(%rsp)\n" "movaps %xmm6, 96(%rsp)\n" "movaps %xmm7, 112(%rsp)\n" // JIT callee "movq %rbp, %rdi\n" // Pass prev frame and return address "movq 8(%rbp), %rsi\n" "call " ASMPREFIX "X86CompilationCallback2\n" // Restore all XMM arg registers "movaps 112(%rsp), %xmm7\n" "movaps 96(%rsp), %xmm6\n" "movaps 80(%rsp), %xmm5\n" "movaps 64(%rsp), %xmm4\n" "movaps 48(%rsp), %xmm3\n" "movaps 32(%rsp), %xmm2\n" "movaps 16(%rsp), %xmm1\n" "movaps (%rsp), %xmm0\n" // Restore RSP "movq %rbp, %rsp\n" // Restore all int arg registers "subq $48, %rsp\n" "popq %r9\n" "popq %r8\n" "popq %rcx\n" "popq %rdx\n" "popq %rsi\n" "popq %rdi\n" // Restore RBP "popq %rbp\n" "ret\n"); #elif defined(__i386__) || defined(i386) || defined(_M_IX86) #ifndef _MSC_VER void X86CompilationCallback(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback\n" ASMPREFIX "X86CompilationCallback:\n" "pushl %ebp\n" "movl %esp, %ebp\n" // Standard prologue #if FASTCC_NUM_INT_ARGS_INREGS > 0 "pushl %eax\n" "pushl %edx\n" // Save EAX/EDX #endif #if defined(__APPLE__) "andl $-16, %esp\n" // Align ESP on 16-byte boundary #endif "subl $16, %esp\n" "movl 4(%ebp), %eax\n" // Pass prev frame and return address "movl %eax, 4(%esp)\n" "movl %ebp, (%esp)\n" "call " ASMPREFIX "X86CompilationCallback2\n" "movl %ebp, %esp\n" // Restore ESP #if FASTCC_NUM_INT_ARGS_INREGS > 0 "subl $8, %esp\n" "popl %edx\n" "popl %eax\n" #endif "popl %ebp\n" "ret\n"); // Same as X86CompilationCallback but also saves XMM argument registers. void X86CompilationCallback_SSE(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback_SSE\n" ASMPREFIX "X86CompilationCallback_SSE:\n" "pushl %ebp\n" "movl %esp, %ebp\n" // Standard prologue #if FASTCC_NUM_INT_ARGS_INREGS > 0 "pushl %eax\n" "pushl %edx\n" // Save EAX/EDX #endif "andl $-16, %esp\n" // Align ESP on 16-byte boundary // Save all XMM arg registers "subl $64, %esp\n" "movaps %xmm0, (%esp)\n" "movaps %xmm1, 16(%esp)\n" "movaps %xmm2, 32(%esp)\n" "movaps %xmm3, 48(%esp)\n" "subl $16, %esp\n" "movl 4(%ebp), %eax\n" // Pass prev frame and return address "movl %eax, 4(%esp)\n" "movl %ebp, (%esp)\n" "call " ASMPREFIX "X86CompilationCallback2\n" "addl $16, %esp\n" "movaps 48(%esp), %xmm3\n" "movaps 32(%esp), %xmm2\n" "movaps 16(%esp), %xmm1\n" "movaps (%esp), %xmm0\n" "movl %ebp, %esp\n" // Restore ESP #if FASTCC_NUM_INT_ARGS_INREGS > 0 "subl $8, %esp\n" "popl %edx\n" "popl %eax\n" #endif "popl %ebp\n" "ret\n"); #else void X86CompilationCallback2(void); _declspec(naked) void X86CompilationCallback(void) { __asm { push eax push edx call X86CompilationCallback2 pop edx pop eax ret } } #endif // _MSC_VER #else // Not an i386 host void X86CompilationCallback() { std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n"; abort(); } #endif } /// X86CompilationCallback - This is the target-specific function invoked by the /// function stub when we did not know the real target of a call. This function /// must locate the start of the stub or call site and pass it into the JIT /// compiler function. #ifdef _MSC_VER extern "C" void X86CompilationCallback2() { assert(sizeof(size_t) == 4); // FIXME: handle Win64 unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress(); RetAddrLoc += 3; // skip over ret addr, edx, eax unsigned RetAddr = *RetAddrLoc; #else extern "C" void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) { intptr_t *RetAddrLoc = &StackPtr[1]; #endif assert(*RetAddrLoc == RetAddr && "Could not find return address on the stack!"); // It's a stub if there is an interrupt marker after the call. bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD; // The call instruction should have pushed the return value onto the stack... RetAddr -= 4; // Backtrack to the reference itself... #if 0 DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr << " ESP=" << (void*)StackPtr << ": Resolving call to function: " << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n"); #endif // Sanity check to make sure this really is a call instruction. assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!"); intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr); // Rewrite the call target... so that we don't end up here every time we // execute the call. *(unsigned *)RetAddr = (unsigned)(NewVal-RetAddr-4); if (isStub) { // If this is a stub, rewrite the call into an unconditional branch // instruction so that two return addresses are not pushed onto the stack // when the requested function finally gets called. This also makes the // 0xCD byte (interrupt) dead, so the marker doesn't effect anything. ((unsigned char*)RetAddr)[-1] = 0xE9; } // Change the return address to reexecute the call instruction... *RetAddrLoc -= 5; } TargetJITInfo::LazyResolverFn X86JITInfo::getLazyResolverFunction(JITCompilerFn F) { JITCompilerFunction = F; unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; union { unsigned u[3]; char c[12]; } text; if (!X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) { // FIXME: support for AMD family of processors. if (memcmp(text.c, "GenuineIntel", 12) == 0) { X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX); if ((EDX >> 25) & 0x1) return X86CompilationCallback_SSE; } } return X86CompilationCallback; } void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) { // Note, we cast to intptr_t here to silence a -pedantic warning that // complains about casting a function pointer to a normal pointer. if (Fn != (void*)(intptr_t)X86CompilationCallback && Fn != (void*)(intptr_t)X86CompilationCallback_SSE) { MCE.startFunctionStub(5); MCE.emitByte(0xE9); MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4); return MCE.finishFunctionStub(0); } MCE.startFunctionStub(6); MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination... MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4); MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub! return MCE.finishFunctionStub(0); } /// relocate - Before the JIT can run a block of code that has been emitted, /// it must rewrite the code to contain the actual addresses of any /// referenced global symbols. void X86JITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs, unsigned char* GOTBase) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { void *RelocPos = (char*)Function + MR->getMachineCodeOffset(); intptr_t ResultPtr = (intptr_t)MR->getResultPointer(); switch ((X86::RelocationType)MR->getRelocationType()) { case X86::reloc_pcrel_word: { // PC relative relocation, add the relocated value to the value already in // memory, after we adjust it for where the PC is. ResultPtr = ResultPtr-(intptr_t)RelocPos-4-MR->getConstantVal(); *((unsigned*)RelocPos) += (unsigned)ResultPtr; break; } case X86::reloc_absolute_word: // Absolute relocation, just add the relocated value to the value already // in memory. *((unsigned*)RelocPos) += (unsigned)ResultPtr; break; } } } <commit_msg>Unbreak x86-64 build.<commit_after>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===// // // 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 file implements the JIT interfaces for the X86 target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "X86JITInfo.h" #include "X86Relocations.h" #include "X86Subtarget.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/Config/alloca.h" #include <cstdlib> #include <iostream> using namespace llvm; #ifdef _MSC_VER extern "C" void *_AddressOfReturnAddress(void); #pragma intrinsic(_AddressOfReturnAddress) #endif void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) { unsigned char *OldByte = (unsigned char *)Old; *OldByte++ = 0xE9; // Emit JMP opcode. unsigned *OldWord = (unsigned *)OldByte; unsigned NewAddr = (intptr_t)New; unsigned OldAddr = (intptr_t)OldWord; *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code. } /// JITCompilerFunction - This contains the address of the JIT function used to /// compile a function lazily. static TargetJITInfo::JITCompilerFn JITCompilerFunction; // Get the ASMPREFIX for the current host. This is often '_'. #ifndef __USER_LABEL_PREFIX__ #define __USER_LABEL_PREFIX__ #endif #define GETASMPREFIX2(X) #X #define GETASMPREFIX(X) GETASMPREFIX2(X) #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__) // Provide a wrapper for X86CompilationCallback2 that saves non-traditional // callee saved registers, for the fastcc calling convention. extern "C" { #if defined(__x86_64__) // No need to save EAX/EDX for X86-64. void X86CompilationCallback(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback\n" ASMPREFIX "X86CompilationCallback:\n" // Save RBP "pushq %rbp\n" // Save RSP "movq %rsp, %rbp\n" // Save all int arg registers "pushq %rdi\n" "pushq %rsi\n" "pushq %rdx\n" "pushq %rcx\n" "pushq %r8\n" "pushq %r9\n" // Align stack on 16-byte boundary. ESP might not be properly aligned // (8 byte) if this is called from an indirect stub. "andq $-16, %rsp\n" // Save all XMM arg registers "subq $128, %rsp\n" "movaps %xmm0, (%rsp)\n" "movaps %xmm1, 16(%rsp)\n" "movaps %xmm2, 32(%rsp)\n" "movaps %xmm3, 48(%rsp)\n" "movaps %xmm4, 64(%rsp)\n" "movaps %xmm5, 80(%rsp)\n" "movaps %xmm6, 96(%rsp)\n" "movaps %xmm7, 112(%rsp)\n" // JIT callee "movq %rbp, %rdi\n" // Pass prev frame and return address "movq 8(%rbp), %rsi\n" "call " ASMPREFIX "X86CompilationCallback2\n" // Restore all XMM arg registers "movaps 112(%rsp), %xmm7\n" "movaps 96(%rsp), %xmm6\n" "movaps 80(%rsp), %xmm5\n" "movaps 64(%rsp), %xmm4\n" "movaps 48(%rsp), %xmm3\n" "movaps 32(%rsp), %xmm2\n" "movaps 16(%rsp), %xmm1\n" "movaps (%rsp), %xmm0\n" // Restore RSP "movq %rbp, %rsp\n" // Restore all int arg registers "subq $48, %rsp\n" "popq %r9\n" "popq %r8\n" "popq %rcx\n" "popq %rdx\n" "popq %rsi\n" "popq %rdi\n" // Restore RBP "popq %rbp\n" "ret\n"); #elif defined(__i386__) || defined(i386) || defined(_M_IX86) #ifndef _MSC_VER void X86CompilationCallback(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback\n" ASMPREFIX "X86CompilationCallback:\n" "pushl %ebp\n" "movl %esp, %ebp\n" // Standard prologue #if FASTCC_NUM_INT_ARGS_INREGS > 0 "pushl %eax\n" "pushl %edx\n" // Save EAX/EDX #endif #if defined(__APPLE__) "andl $-16, %esp\n" // Align ESP on 16-byte boundary #endif "subl $16, %esp\n" "movl 4(%ebp), %eax\n" // Pass prev frame and return address "movl %eax, 4(%esp)\n" "movl %ebp, (%esp)\n" "call " ASMPREFIX "X86CompilationCallback2\n" "movl %ebp, %esp\n" // Restore ESP #if FASTCC_NUM_INT_ARGS_INREGS > 0 "subl $8, %esp\n" "popl %edx\n" "popl %eax\n" #endif "popl %ebp\n" "ret\n"); // Same as X86CompilationCallback but also saves XMM argument registers. void X86CompilationCallback_SSE(void); asm( ".text\n" ".align 8\n" ".globl " ASMPREFIX "X86CompilationCallback_SSE\n" ASMPREFIX "X86CompilationCallback_SSE:\n" "pushl %ebp\n" "movl %esp, %ebp\n" // Standard prologue #if FASTCC_NUM_INT_ARGS_INREGS > 0 "pushl %eax\n" "pushl %edx\n" // Save EAX/EDX #endif "andl $-16, %esp\n" // Align ESP on 16-byte boundary // Save all XMM arg registers "subl $64, %esp\n" "movaps %xmm0, (%esp)\n" "movaps %xmm1, 16(%esp)\n" "movaps %xmm2, 32(%esp)\n" "movaps %xmm3, 48(%esp)\n" "subl $16, %esp\n" "movl 4(%ebp), %eax\n" // Pass prev frame and return address "movl %eax, 4(%esp)\n" "movl %ebp, (%esp)\n" "call " ASMPREFIX "X86CompilationCallback2\n" "addl $16, %esp\n" "movaps 48(%esp), %xmm3\n" "movaps 32(%esp), %xmm2\n" "movaps 16(%esp), %xmm1\n" "movaps (%esp), %xmm0\n" "movl %ebp, %esp\n" // Restore ESP #if FASTCC_NUM_INT_ARGS_INREGS > 0 "subl $8, %esp\n" "popl %edx\n" "popl %eax\n" #endif "popl %ebp\n" "ret\n"); #else void X86CompilationCallback2(void); _declspec(naked) void X86CompilationCallback(void) { __asm { push eax push edx call X86CompilationCallback2 pop edx pop eax ret } } #endif // _MSC_VER #else // Not an i386 host void X86CompilationCallback() { std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n"; abort(); } #endif } /// X86CompilationCallback - This is the target-specific function invoked by the /// function stub when we did not know the real target of a call. This function /// must locate the start of the stub or call site and pass it into the JIT /// compiler function. #ifdef _MSC_VER extern "C" void X86CompilationCallback2() { assert(sizeof(size_t) == 4); // FIXME: handle Win64 unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress(); RetAddrLoc += 3; // skip over ret addr, edx, eax unsigned RetAddr = *RetAddrLoc; #else extern "C" void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) { intptr_t *RetAddrLoc = &StackPtr[1]; #endif assert(*RetAddrLoc == RetAddr && "Could not find return address on the stack!"); // It's a stub if there is an interrupt marker after the call. bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD; // The call instruction should have pushed the return value onto the stack... RetAddr -= 4; // Backtrack to the reference itself... #if 0 DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr << " ESP=" << (void*)StackPtr << ": Resolving call to function: " << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n"); #endif // Sanity check to make sure this really is a call instruction. assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!"); intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr); // Rewrite the call target... so that we don't end up here every time we // execute the call. *(unsigned *)RetAddr = (unsigned)(NewVal-RetAddr-4); if (isStub) { // If this is a stub, rewrite the call into an unconditional branch // instruction so that two return addresses are not pushed onto the stack // when the requested function finally gets called. This also makes the // 0xCD byte (interrupt) dead, so the marker doesn't effect anything. ((unsigned char*)RetAddr)[-1] = 0xE9; } // Change the return address to reexecute the call instruction... *RetAddrLoc -= 5; } TargetJITInfo::LazyResolverFn X86JITInfo::getLazyResolverFunction(JITCompilerFn F) { JITCompilerFunction = F; #if !defined(__x86_64__) unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; union { unsigned u[3]; char c[12]; } text; if (!X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) { // FIXME: support for AMD family of processors. if (memcmp(text.c, "GenuineIntel", 12) == 0) { X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX); if ((EDX >> 25) & 0x1) return X86CompilationCallback_SSE; } } #endif return X86CompilationCallback; } void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) { // Note, we cast to intptr_t here to silence a -pedantic warning that // complains about casting a function pointer to a normal pointer. #if defined(__x86_64__) bool NotCC = Fn != (void*)(intptr_t)X86CompilationCallback; #else bool NotCC = (Fn != (void*)(intptr_t)X86CompilationCallback && Fn != (void*)(intptr_t)X86CompilationCallback_SSE); #endif if (NotCC) { MCE.startFunctionStub(5); MCE.emitByte(0xE9); MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4); return MCE.finishFunctionStub(0); } MCE.startFunctionStub(6); MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination... MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4); MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub! return MCE.finishFunctionStub(0); } /// relocate - Before the JIT can run a block of code that has been emitted, /// it must rewrite the code to contain the actual addresses of any /// referenced global symbols. void X86JITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs, unsigned char* GOTBase) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { void *RelocPos = (char*)Function + MR->getMachineCodeOffset(); intptr_t ResultPtr = (intptr_t)MR->getResultPointer(); switch ((X86::RelocationType)MR->getRelocationType()) { case X86::reloc_pcrel_word: { // PC relative relocation, add the relocated value to the value already in // memory, after we adjust it for where the PC is. ResultPtr = ResultPtr-(intptr_t)RelocPos-4-MR->getConstantVal(); *((unsigned*)RelocPos) += (unsigned)ResultPtr; break; } case X86::reloc_absolute_word: // Absolute relocation, just add the relocated value to the value already // in memory. *((unsigned*)RelocPos) += (unsigned)ResultPtr; break; } } } <|endoftext|>
<commit_before>// wandurr1.cpp - game of wandering around doing stuff written in c++/ncurses hurr durr // copyright 2017 inhabited.systems // This program is covered by the MIT License. // See the file LICENSE included with this distribution for terms. // see the file README.md for more information, including how to compile and // run this program. // wandurr1 does not use classes, so this code will look more C-like. I may do // a wandurr2 that uses classes. #include <stdlib.h> #include <ncurses.h> #include <math.h> #include <signal.h> #include <iostream> #include <vector> #include <string> using namespace std; void vec2dinitrandint(vector<vector<int>>& pvec, int rsize); void print2dvec(vector<vector<int>> pvec, string title); void drawgamescreen(); void drawhelpscreen(); static void finish(int sig); int row = 0, col = 0, rows = 0, cols = 0; const int cpairs=7; vector<vector<int> > vec2d; int main(void) { //int row = 0, col = 0; time_t timenow; timenow = time(NULL); srand(timenow); //const int rows = 15, cols = 40; (void) signal(SIGINT, finish); (void) initscr(); keypad(stdscr, TRUE); (void) nonl(); (void) cbreak(); (void) echo(); initscr(); addstr("Wandurr! Press any key to begin:\n"); curs_set(0); getmaxyx(stdscr,rows,cols); rows-=2; cols-=2; printw("rows: %d cols: %d", rows, cols); refresh(); getch(); // vector<vector<int> > vec2d; vec2d.resize(rows); for (int i = 0; i < rows; ++i) vec2d[i].resize(cols); vec2dinitrandint(vec2d, cpairs); //print2dvec(vec2d, "vec2d"); if (has_colors()) { //addstr("has_colors()\n"); refresh(); //getch(); start_color(); init_pair(0, COLOR_WHITE, COLOR_BLACK); init_pair(1, COLOR_WHITE, COLOR_RED); init_pair(2, COLOR_WHITE, COLOR_GREEN); init_pair(3, COLOR_WHITE, COLOR_YELLOW); init_pair(4, COLOR_WHITE, COLOR_BLUE); init_pair(5, COLOR_WHITE, COLOR_MAGENTA); init_pair(6, COLOR_WHITE, COLOR_CYAN); init_pair(7, COLOR_WHITE, COLOR_WHITE); } nodelay(stdscr, TRUE); move(rows+1,0); addstr("Press any key to quit.\n"); getch(); while(ERR == getch()) { drawgamescreen(); //napms(100); refresh(); } endwin(); finish(0); return 0; } void vec2dinitrandint(vector<vector<int>>& pvec, int rsize) { for (unsigned int i = 0; i < pvec.size(); i++) { for (unsigned int j = 0; j < pvec[i].size(); j++) { pvec[i][j] = rand()%rsize; // cout << "pvec[" << i << "][" << j << "] = " << pvec[i][j] << "\n"; } } } void print2dvec(vector<vector<int>> pvec, string title) { // TODO: change this crap to use ncurses instead of cout!!! or just delete this? // print out the 2d vector of int passed in as pvec cout << "\n" << title << "\n"; for (unsigned int i = 0; i < pvec.size(); i++) { for (unsigned int j = 0; j < pvec[i].size(); j++) cout << pvec[i][j] << " "; cout << "\n"; } cout << "\n"; } void drawgamescreen() { int rowoffset = 1, coloffset = 1; for(row=2; row < rows; row++) { for(col=2; col < cols-3; col++) { // move(row+rowoffset,col+coloffset); //attrset(COLOR_PAIR(rand()%7+1)); attrset(COLOR_PAIR(vec2d[row][col]+1)); if (vec2d[row][col] > 0) vec2d[row][col]=vec2d[row][col]-1; else vec2d[row][col] = rand()%cpairs; addch(' '); } napms(10); refresh(); } } void drawhelpscreen() { } static void finish(int sig) { endwin(); exit(0); } <commit_msg>made Cell struct, green field, added dollar sign treasure<commit_after>// wandurr1.cpp - game of wandering around doing stuff written in c++/ncurses hurr durr // copyright 2017 inhabited.systems // This program is covered by the MIT License. // See the file LICENSE included with this distribution for terms. // see the file README.md for more information, including how to compile and // run this program. // wandurr1 does not use classes, so this code will look more C-like. I may do // a wandurr2 that uses classes. #include <stdlib.h> #include <ncurses.h> #include <math.h> #include <signal.h> #include <iostream> #include <vector> #include <string> using namespace std; int row = 0, col = 0, rows = 0, cols = 0; const int cpairs=7; typedef struct { char occupant; int y; int x; char color; } Cell; vector<vector<Cell> > vec2d; void vec2dinitrandint(vector<vector<Cell>>& pvec, int rsize); void print2dvec(vector<vector<Cell>> pvec, string title); void drawgamescreen(); void drawhelpscreen(); static void finish(int sig); int main(void) { //int row = 0, col = 0; time_t timenow; timenow = time(NULL); srand(timenow); //const int rows = 15, cols = 40; // what the hell is this crap? FIX IT! (void) signal(SIGINT, finish); (void) initscr(); keypad(stdscr, TRUE); (void) nonl(); (void) cbreak(); (void) echo(); addstr("Wandurr! Press any key to begin:\n"); curs_set(0); getmaxyx(stdscr,rows,cols); rows-=2; cols-=2; printw("rows: %d cols: %d", rows, cols); refresh(); getch(); // vector<vector<int> > vec2d; vec2d.resize(rows); for (int i = 0; i < rows; ++i) vec2d[i].resize(cols); vec2dinitrandint(vec2d, cpairs); //print2dvec(vec2d, "vec2d"); if (has_colors()) { //addstr("has_colors()\n"); refresh(); //getch(); start_color(); init_pair(0, COLOR_WHITE, COLOR_BLACK); init_pair(1, COLOR_WHITE, COLOR_RED); init_pair(2, COLOR_WHITE, COLOR_GREEN); init_pair(3, COLOR_WHITE, COLOR_YELLOW); init_pair(4, COLOR_WHITE, COLOR_BLUE); init_pair(5, COLOR_WHITE, COLOR_MAGENTA); init_pair(6, COLOR_WHITE, COLOR_CYAN); init_pair(7, COLOR_WHITE, COLOR_WHITE); } nodelay(stdscr, TRUE); move(rows+1,0); addstr("Press any key to quit.\n"); getch(); while(ERR == getch()) { drawgamescreen(); //napms(100); refresh(); } endwin(); finish(0); return 0; } void vec2dinitrandint(vector<vector<Cell>>& pvec, int rsize) { for (unsigned int i = 0; i < pvec.size(); i++) { for (unsigned int j = 0; j < pvec[i].size(); j++) { // this is supposed to be green pvec[i][j].color = 1; if (rand()%100==1) pvec[i][j].occupant = '$'; else pvec[i][j].occupant = ' '; // cout << "pvec[" << i << "][" << j << "] = " << pvec[i][j].color << "\n"; } } } void print2dvec(vector<vector<Cell>> pvec, string title) { // TODO: change this crap to use ncurses instead of cout!!! or just delete this? // print out the 2d vector of int passed in as pvec cout << "\n" << title << "\n"; for (unsigned int i = 0; i < pvec.size(); i++) { for (unsigned int j = 0; j < pvec[i].size(); j++) { cout << pvec[i][j].color << " "; } cout << "\n"; } cout << "\n"; } void drawgamescreen() { int rowoffset = 1, coloffset = 1; for(row=2; row < rows; row++) { for(col=2; col < cols-3; col++) { move(row+rowoffset,col+coloffset); //attrset(COLOR_PAIR(rand()%7+1)); attrset(COLOR_PAIR(vec2d[row][col].color+1)); //if (vec2d[row][col].color > 0) vec2d[row][col].color=vec2d[row][col].color-1; //else vec2d[row][col].color = rand()%cpairs; addch(vec2d[row][col].occupant); } //napms(10); refresh(); } } void drawhelpscreen() { } static void finish(int sig) { endwin(); exit(0); } <|endoftext|>
<commit_before>#include "photoeffects.hpp" #include "test_utils.hpp" #include <gtest/gtest.h> using namespace cv; TEST(photoeffects, FadeColorInvalidImageFormat) { Mat src(10, 20, CV_8UC2); Mat dst; EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5, 5), Point(5, 10))); } TEST(photoeffects, FadeColorInvalidArgument) { Mat src(10, 20, CV_8UC1); Mat dst; EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(50,5), Point(5,10))); EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5,5), Point(5,-10))); EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5,5), Point(5,5))); } TEST(photoeffects, FadeColorTest) { Mat imageWithOneChannel(100, 200, CV_8UC1); Mat imageWithThreeChannel(100, 200, CV_8UC3); Mat dst; EXPECT_EQ(0, fadeColor(imageWithOneChannel, dst, Point(5,5), Point(5,8))); EXPECT_EQ(0, fadeColor(imageWithThreeChannel, dst, Point(5,5), Point(5,8))); } TEST(photoeffects, FadeColorRegressionTest) { string input ="./testdata/fadeColor_test.png"; string expectedOutput ="./testdata/fadeColor_result.png"; Mat image, dst, rightDst; image = imread(input, CV_LOAD_IMAGE_COLOR); rightDst = imread(expectedOutput, CV_LOAD_IMAGE_COLOR); if (image.empty()) FAIL() << "Can't read " + input + " image"; if (rightDst.empty()) FAIL() << "Can't read " + expectedOutput + " image"; EXPECT_EQ(0, fadeColor(image, dst, Point(100, 100), Point(1, 1))); for (int i=0; i<dst.rows; i++) { for (int j=0; j<dst.cols; j++) { for (int k=0; k<3; k++) { ASSERT_EQ(rightDst.at<Vec3b>(i, j)[k], dst.at<Vec3b>(i, j)[k]); } } } } <commit_msg>correct Point in regression test<commit_after>#include "photoeffects.hpp" #include "test_utils.hpp" #include <gtest/gtest.h> using namespace cv; TEST(photoeffects, FadeColorInvalidImageFormat) { Mat src(10, 20, CV_8UC2); Mat dst; EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5, 5), Point(5, 10))); } TEST(photoeffects, FadeColorInvalidArgument) { Mat src(10, 20, CV_8UC1); Mat dst; EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(50,5), Point(5,10))); EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5,5), Point(5,-10))); EXPECT_ERROR(CV_StsAssert, fadeColor(src, dst, Point(5,5), Point(5,5))); } TEST(photoeffects, FadeColorTest) { Mat imageWithOneChannel(100, 200, CV_8UC1); Mat imageWithThreeChannel(100, 200, CV_8UC3); Mat dst; EXPECT_EQ(0, fadeColor(imageWithOneChannel, dst, Point(5,5), Point(5,8))); EXPECT_EQ(0, fadeColor(imageWithThreeChannel, dst, Point(5,5), Point(5,8))); } TEST(photoeffects, FadeColorRegressionTest) { string input ="./testdata/fadeColor_test.png"; string expectedOutput ="./testdata/fadeColor_result.png"; Mat image, dst, rightDst; image = imread(input, CV_LOAD_IMAGE_COLOR); rightDst = imread(expectedOutput, CV_LOAD_IMAGE_COLOR); if (image.empty()) FAIL() << "Can't read " + input + " image"; if (rightDst.empty()) FAIL() << "Can't read " + expectedOutput + " image"; EXPECT_EQ(0, fadeColor(image, dst, Point(100, 100), Point(250, 250))); for (int i=0; i<dst.rows; i++) { for (int j=0; j<dst.cols; j++) { for (int k=0; k<3; k++) { ASSERT_EQ(rightDst.at<Vec3b>(i, j)[k], dst.at<Vec3b>(i, j)[k]); } } } } <|endoftext|>
<commit_before>// fmfrecord.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; using namespace FlyCapture2; using namespace cv; int _tmain(int argc, _TCHAR* argv[]) { int imageWidth = 1280, imageHeight = 1024; BusManager busMgr; unsigned int numCameras; PGRGuid guid; FlyCapture2::Error error; error = busMgr.GetNumOfCameras(&numCameras); printf("Number of cameras detected: %u\n", numCameras); if (numCameras < 1) { printf("Insufficient number of cameras\n"); return -1; } vector<PGRcam> fcam(numCameras); vector<FmfWriter> fout(numCameras); //Initialize cameras for (int i = 0; i < numCameras; i++) { error = busMgr.GetCameraFromIndex(i, &guid); fcam[i].id = i; error = fcam[i].Connect(guid); error = fcam[i].SetCameraParameters(imageWidth, imageHeight); error = fcam[i].SetProperty(SHUTTER, 6.657); error = fcam[i].SetProperty(GAIN, 0.0); //error = fcam[i].SetTrigger(); error = fcam[i].Start(); if (error != PGRERROR_OK) { error.PrintErrorTrace(); return -1; } } omp_set_nested(1); #pragma omp parallel for num_threads(numCameras) for (int i = 0; i < numCameras; i++) { int key_state = 0; bool stream = true; bool record = false; queue <Mat> dispStream; queue <Image> imageStream; queue <TimeStamp> timeStamps; #pragma omp parallel sections num_threads(3) { #pragma omp section { while (true) { FlyCapture2::Image img = fcam[i].GrabFrame(); FlyCapture2::TimeStamp stamp = fcam[i].GetTimeStamp(); Mat frame = fcam[i].convertImagetoMat(img); #pragma omp critical { dispStream.push(frame); imageStream.push(img); timeStamps.push(stamp); } if (GetAsyncKeyState(VK_F1)) { if (!key_state) record = !record; key_state = 1; } else key_state = 0; if (GetAsyncKeyState(VK_ESCAPE)) { stream = false; break; } } } #pragma omp section { while (true) { if (!imageStream.empty()) { if (record) { if (!fout[i].IsOpen()) { fout[i].id = i; fout[i].Open(); fout[i].InitHeader(imageWidth, imageHeight); fout[i].WriteHeader(); } fout[i].WriteFrame(timeStamps.front(), imageStream.front()); fout[i].WriteLog(timeStamps.front()); fout[i].nframes++; } else { if (fout[i].IsOpen()) fout[i].Close(); } #pragma omp critical { imageStream.pop(); timeStamps.pop(); } } if (i == 0) printf("Recording buffer size %06d, Frames written %06d\r", imageStream.size(), fout[i].nframes); if (imageStream.size() == 0 && !stream) break; } } #pragma omp section { while (true) { if (!dispStream.empty()) { imshow(string("image %d", i), dispStream.back()); #pragma omp critical { dispStream = queue<Mat>(); } } waitKey(1); if (!stream) { destroyWindow(string("image %d", i)); break; } } } } } for (unsigned int i = 0; i < numCameras; i++) { fcam[i].Stop(); if (fout[i].IsOpen()) fout[i].Close(); } return 0; } <commit_msg>fixed window naming<commit_after>// fmfrecord.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; using namespace FlyCapture2; using namespace cv; int _tmain(int argc, _TCHAR* argv[]) { int imageWidth = 1280, imageHeight = 1024; BusManager busMgr; unsigned int numCameras; PGRGuid guid; FlyCapture2::Error error; error = busMgr.GetNumOfCameras(&numCameras); printf("Number of cameras detected: %u\n", numCameras); if (numCameras < 1) { printf("Insufficient number of cameras\n"); return -1; } vector<PGRcam> fcam(numCameras); vector<FmfWriter> fout(numCameras); vector<string> window_name(numCameras); //Initialize cameras for (int i = 0; i < numCameras; i++) { error = busMgr.GetCameraFromIndex(i, &guid); fcam[i].id = i; window_name[i] = "Camera " + to_string(i); error = fcam[i].Connect(guid); error = fcam[i].SetCameraParameters(imageWidth, imageHeight); error = fcam[i].SetProperty(SHUTTER, 6.657); error = fcam[i].SetProperty(GAIN, 0.0); //error = fcam[i].SetTrigger(); error = fcam[i].Start(); if (error != PGRERROR_OK) { error.PrintErrorTrace(); return -1; } } printf("\nPress [F1] to start/stop recording. Press [ESC] to exit.\n\n"); omp_set_nested(1); #pragma omp parallel for num_threads(numCameras) for (int i = 0; i < numCameras; i++) { int key_state = 0; bool stream = true; bool record = false; queue <Mat> dispStream; queue <Image> imageStream; queue <TimeStamp> timeStamps; #pragma omp parallel sections num_threads(3) { #pragma omp section { while (true) { FlyCapture2::Image img = fcam[i].GrabFrame(); FlyCapture2::TimeStamp stamp = fcam[i].GetTimeStamp(); Mat frame = fcam[i].convertImagetoMat(img); #pragma omp critical { dispStream.push(frame); imageStream.push(img); timeStamps.push(stamp); } if (GetAsyncKeyState(VK_F1)) { if (!key_state) record = !record; key_state = 1; } else key_state = 0; if (GetAsyncKeyState(VK_ESCAPE)) { stream = false; break; } } } #pragma omp section { while (true) { if (!imageStream.empty()) { if (record) { if (!fout[i].IsOpen()) { fout[i].id = i; fout[i].Open(); fout[i].InitHeader(imageWidth, imageHeight); fout[i].WriteHeader(); } fout[i].WriteFrame(timeStamps.front(), imageStream.front()); fout[i].WriteLog(timeStamps.front()); fout[i].nframes++; } else { if (fout[i].IsOpen()) fout[i].Close(); } #pragma omp critical { imageStream.pop(); timeStamps.pop(); } } if (i == 0) printf("Recording buffer size %06d, Frames written %06d\r", imageStream.size(), fout[i].nframes); if (imageStream.size() == 0 && !stream) break; } } #pragma omp section { while (true) { if (!dispStream.empty()) { imshow(window_name[i], dispStream.back()); #pragma omp critical { dispStream = queue<Mat>(); } } waitKey(1); if (!stream) break; } } } } destroyAllWindows(); for (unsigned int i = 0; i < numCameras; i++) { fcam[i].Stop(); if (fout[i].IsOpen()) fout[i].Close(); } return 0; } <|endoftext|>
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be recursive instead of iterative. Right now, we // scan linearly through values, removing unused ones as we go. The problem is // that this may cause other earlier values to become unused. To make sure that // we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Opt/AllOpts.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const Value *) { return true; } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class ValueSubclass, class ItemParentType, class DCEController> static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, DCEController DCEControl) { bool Changed = false; typedef ValueHolder<ValueSubclass, ItemParentType> Container; int Offset = DCEController::EndOffs; for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getOperand(2) == 0 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // RemovePredecessorFromBlock - This function is called when we are about // to remove a predecessor from a basic block. This function takes care of // removing the predecessor from the PHI nodes in BB so that after the pred // is removed, the number of PHI slots per bb is equal to the number of // predecessors. // static void RemovePredecessorFromBlock(BasicBlock *BB, BasicBlock *Pred) { pred_iterator PI(pred_begin(BB)), EI(pred_end(BB)); unsigned max_idx; //cerr << "RPFB: " << Pred << "From Block: " << BB; // Loop over the rest of the predecssors until we run out, or until we find // out that there are more than 2 predecessors. for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/; // If there are exactly two predecessors, then we want to nuke the PHI nodes // altogether. bool NukePHIs = max_idx == 2; assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!"); // Okay, now we know that we need to remove predecessor #pred_idx from all // PHI nodes. Iterate over each PHI node fixing them up BasicBlock::iterator II(BB->begin()); for (; (*II)->isPHINode(); ++II) { PHINode *PN = (PHINode*)*II; PN->removeIncomingValue(BB); if (NukePHIs) { // Destroy the PHI altogether?? assert(PN->getOperand(1) == 0 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(II); } } } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ++BBIt) { BasicBlock *BB = *BBIt; assert(BB->getTerminator() && "Degenerate basic block encountered!"); #if 0 // This is know to basically work? // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences() && 0) { cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), bind_2nd(RemovePredecessorFromBlock, BB)); while (!BB->empty()) { Instruction *I = BB->front(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().remove(BB->begin()); } delete M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts use on the next block, we want the previous one Changed = true; continue; } #endif #if 0 // This has problems // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor cerr << "Killing Trivial BB: \n" << BB; if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts use on the next block, we want the previous one if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block cerr << "Method after removal: \n" << M; Changed = true; continue; } } #endif // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts us on the NEXT bb. We want the prev BB Changed = true; // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); // You ARE the weakest link... goodbye delete BB; //WriteToVCG(M, "MergedInto"); } } } // Remove unused constants Changed |= DoRemoveUnusedConstants(M); return Changed; } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool DoDeadCodeElimination(Module *C) { bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; } <commit_msg>* Factored RemovePredecessorFromBlock into BasicBlock::removePredecessor * Avoid messing around with this case: br label %A %A: br label %A * Enable optimizations that are correct now.<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Opt/AllOpts.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include "llvm/Tools/STLExtras.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const Value *) { return true; } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class ValueSubclass, class ItemParentType, class DCEController> static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, DCEController DCEControl) { bool Changed = false; typedef ValueHolder<ValueSubclass, ItemParentType> Container; int Offset = DCEController::EndOffs; for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getOperand(2) == 0 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ++BBIt) { BasicBlock *BB = *BBIt; assert(BB->getTerminator() && "Degenerate basic block encountered!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences() && 0) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), bind_obj(BB, &BasicBlock::removePredecessor)); while (!BB->empty()) { Instruction *I = BB->front(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().remove(BB->begin()); } delete M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts use on the next block, we want the previous one Changed = true; continue; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts use on the next block, we want the previous one if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; Changed = true; continue; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); --BBIt; // remove puts us on the NEXT bb. We want the prev BB Changed = true; // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); // You ARE the weakest link... goodbye delete BB; //WriteToVCG(M, "MergedInto"); } } } // Remove unused constants Changed |= DoRemoveUnusedConstants(M); return Changed; } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool DoDeadCodeElimination(Module *C) { bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ // OpenGL ES 2.0 code #include <GLES2/gl2.h> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "glm/glm.hpp" #include <jni.h> #include <android/log.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include "GLES2Lesson.h" #include "NdkGlue.h" #include "android_asset_operations.h" static std::string gVertexShader; static std::string gFragmentShader; void loadShaders(JNIEnv *env, jobject &obj) { AAssetManager *asset_manager = AAssetManager_fromJava(env, obj); FILE *fd; fd = android_fopen("vertex.glsl", "r", asset_manager); gVertexShader = readShaderToString(fd); fclose(fd); fd = android_fopen("fragment.glsl", "r", asset_manager); gFragmentShader = readShaderToString(fd); fclose(fd); } bool setupGraphics(int w, int h) { return GLES2Lesson::init(w, h, gVertexShader.c_str(), gFragmentShader.c_str()); } void renderFrame() { GLES2Lesson::render(); } void shutdown() { GLES2Lesson::shutdown(); } extern "C" { JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onCreate(JNIEnv *env, void *reserved, jobject assetManager); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onDestroy(JNIEnv *env, jobject obj); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_init(JNIEnv *env, jobject obj, jint width, jint height); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_step(JNIEnv *env, jobject obj); }; JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onCreate(JNIEnv *env, void *reserved, jobject assetManager) { loadShaders(env, assetManager); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_init(JNIEnv *env, jobject obj, jint width, jint height) { setupGraphics(width, height); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_step(JNIEnv *env, jobject obj) { renderFrame(); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onDestroy(JNIEnv *env, jobject obj) { shutdown(); } <commit_msg>Fix compilation for Lesson 3<commit_after>/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ // OpenGL ES 2.0 code #include <GLES2/gl2.h> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "glm/glm.hpp" #include <jni.h> #include <android/log.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include "GLES2Lesson.h" #include "NdkGlue.h" #include "android_asset_operations.h" static std::string gVertexShader; static std::string gFragmentShader; void loadShaders(JNIEnv *env, jobject &obj) { AAssetManager *asset_manager = AAssetManager_fromJava(env, obj); FILE *fd; fd = android_fopen("vertex.glsl", "r", asset_manager); gVertexShader = readToString(fd); fclose(fd); fd = android_fopen("fragment.glsl", "r", asset_manager); gFragmentShader = readToString(fd); fclose(fd); } bool setupGraphics(int w, int h) { return GLES2Lesson::init(w, h, gVertexShader.c_str(), gFragmentShader.c_str()); } void renderFrame() { GLES2Lesson::render(); } void shutdown() { GLES2Lesson::shutdown(); } extern "C" { JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onCreate(JNIEnv *env, void *reserved, jobject assetManager); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onDestroy(JNIEnv *env, jobject obj); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_init(JNIEnv *env, jobject obj, jint width, jint height); JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_step(JNIEnv *env, jobject obj); }; JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onCreate(JNIEnv *env, void *reserved, jobject assetManager) { loadShaders(env, assetManager); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_init(JNIEnv *env, jobject obj, jint width, jint height) { setupGraphics(width, height); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_step(JNIEnv *env, jobject obj) { renderFrame(); } JNIEXPORT void JNICALL Java_br_odb_nehe_lesson03_GL2JNILib_onDestroy(JNIEnv *env, jobject obj) { shutdown(); } <|endoftext|>
<commit_before>#define DEBUG_TYPE "dyn-aa" #include <string> #include <fstream> #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/CommandLine.h" #include "rcs/typedefs.h" #include "rcs/IDAssigner.h" #include "dyn-aa/BaselineAliasAnalysis.h" #include "dyn-aa/DynamicAliasAnalysis.h" #include "dyn-aa/Utils.h" using namespace std; using namespace llvm; using namespace rcs; using namespace dyn_aa; namespace dyn_aa { struct AliasAnalysisChecker: public ModulePass { static char ID; AliasAnalysisChecker(): ModulePass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool runOnModule(Module &M); private: static bool CompareMissingAliases(const ValuePair &VP1, const ValuePair &VP2); static pair<Function *, Function *> GetContainingFunctionPair( const ValuePair &VP); void collectDynamicAliases(DenseSet<ValuePair> &DynamicAliases); void collectMissingAliases(const DenseSet<ValuePair> &DynamicAliases); void sortMissingAliases(); void reportMissingAliases(); vector<ValuePair> MissingAliases; }; } static cl::opt<bool> IntraProc( "intra", cl::desc("Whether the checked AA supports intra-procedural queries only")); static cl::opt<string> InputDynamicAliases("input-dyn-aliases", cl::desc("input dynamic aliases")); static cl::opt<bool> CheckAllPointers("check-all-pointers", cl::desc("check all pointers")); static cl::opt<bool> PrintValueInReport("print-value-in-report", cl::desc("print values in the report"), cl::init(true)); static RegisterPass<AliasAnalysisChecker> X( "check-aa", "Check whether the alias analysis is sound", false, // Is CFG Only? true); // Is Analysis? STATISTIC(NumDynamicAliases, "Number of dynamic aliases"); char AliasAnalysisChecker::ID = 0; void AliasAnalysisChecker::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); // Note that DynamicAliasAnalysis is not registered to the // AliasAnalysis group. if (InputDynamicAliases == "") { AU.addRequired<DynamicAliasAnalysis>(); } AU.addRequired<AliasAnalysis>(); AU.addRequired<BaselineAliasAnalysis>(); AU.addRequired<IDAssigner>(); } void AliasAnalysisChecker::collectDynamicAliases( DenseSet<ValuePair> &DynamicAliases) { DynamicAliases.clear(); if (InputDynamicAliases == "") { DynamicAliasAnalysis &DAA = getAnalysis<DynamicAliasAnalysis>(); DynamicAliases.insert(DAA.getAllAliases().begin(), DAA.getAllAliases().end()); } else { IDAssigner &IDA = getAnalysis<IDAssigner>(); ifstream InputFile(InputDynamicAliases.c_str()); unsigned VID1, VID2; while (InputFile >> VID1 >> VID2) { Value *V1 = IDA.getValue(VID1), *V2 = IDA.getValue(VID2); DynamicAliases.insert(make_pair(V1, V2)); } } } // Collects missing aliases to <MissingAliases>. void AliasAnalysisChecker::collectMissingAliases( const DenseSet<ValuePair> &DynamicAliases) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasAnalysis &BaselineAA = getAnalysis<BaselineAliasAnalysis>(); MissingAliases.clear(); for (DenseSet<ValuePair>::const_iterator I = DynamicAliases.begin(); I != DynamicAliases.end(); ++I) { Value *V1 = I->first, *V2 = I->second; if (IntraProc && !DynAAUtils::IsIntraProcQuery(V1, V2)) { continue; } if (!CheckAllPointers) { if (!DynAAUtils::PointerIsDereferenced(V1) || !DynAAUtils::PointerIsDereferenced(V2)) { continue; } } if (BaselineAA.alias(V1, V2) != AliasAnalysis::NoAlias && AA.alias(V1, V2) == AliasAnalysis::NoAlias) { MissingAliases.push_back(make_pair(V1, V2)); } } } bool AliasAnalysisChecker::CompareMissingAliases(const ValuePair &VP1, const ValuePair &VP2) { pair<Function *, Function *> FP1 = GetContainingFunctionPair(VP1); pair<Function *, Function *> FP2 = GetContainingFunctionPair(VP2); return FP1 < FP2; } // Sorts missing aliases so that missing aliases inside the same function are // likely clustered. void AliasAnalysisChecker::sortMissingAliases() { sort(MissingAliases.begin(), MissingAliases.end(), CompareMissingAliases); } bool AliasAnalysisChecker::runOnModule(Module &M) { DenseSet<ValuePair> DynamicAliases; collectDynamicAliases(DynamicAliases); NumDynamicAliases = DynamicAliases.size(); collectMissingAliases(DynamicAliases); sortMissingAliases(); reportMissingAliases(); return false; } pair<Function *, Function *> AliasAnalysisChecker::GetContainingFunctionPair( const ValuePair &VP) { const Function *F1 = DynAAUtils::GetContainingFunction(VP.first); const Function *F2 = DynAAUtils::GetContainingFunction(VP.second); return make_pair(const_cast<Function *>(F1), const_cast<Function *>(F2)); } void AliasAnalysisChecker::reportMissingAliases() { IDAssigner &IDA = getAnalysis<IDAssigner>(); unsigned NumReportedMissingAliases = 0; for (size_t i = 0; i < MissingAliases.size(); ++i) { Value *V1 = MissingAliases[i].first, *V2 = MissingAliases[i].second; // Do not report BitCasts and PhiNodes. The reports on them are typically // redundant. if (isa<BitCastInst>(V1) || isa<BitCastInst>(V2)) continue; if (isa<PHINode>(V1) || isa<PHINode>(V2)) continue; ++NumReportedMissingAliases; errs().changeColor(raw_ostream::RED); errs() << "Missing alias:"; errs().resetColor(); // Print some features of this missing alias. errs() << (DynAAUtils::IsIntraProcQuery(V1, V2) ? " (intra)" : " (inter)"); if (DynAAUtils::PointerIsDereferenced(V1) && DynAAUtils::PointerIsDereferenced(V2)) { errs() << " (deref)"; } else { errs() << " (non-deref)"; } errs() << "\n"; errs() << "[" << IDA.getValueID(V1) << "] "; if (PrintValueInReport) DynAAUtils::PrintValue(errs(), V1); errs() << "\n"; errs() << "[" << IDA.getValueID(V2) << "] "; if (PrintValueInReport) DynAAUtils::PrintValue(errs(), V2); errs() << "\n"; } if (NumReportedMissingAliases == 0) { errs().changeColor(raw_ostream::GREEN); errs() << "Congrats! You passed all the tests.\n"; errs().resetColor(); } else { errs().changeColor(raw_ostream::RED); errs() << "Detected " << NumReportedMissingAliases << " missing aliases.\n"; errs().resetColor(); } } <commit_msg>Sort MissingAliases by value pair<commit_after>#define DEBUG_TYPE "dyn-aa" #include <string> #include <fstream> #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/CommandLine.h" #include "rcs/typedefs.h" #include "rcs/IDAssigner.h" #include "dyn-aa/BaselineAliasAnalysis.h" #include "dyn-aa/DynamicAliasAnalysis.h" #include "dyn-aa/Utils.h" using namespace std; using namespace llvm; using namespace rcs; using namespace dyn_aa; namespace dyn_aa { struct AliasAnalysisChecker: public ModulePass { static char ID; AliasAnalysisChecker(): ModulePass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool runOnModule(Module &M); private: static bool CompareOnFunction(const ValuePair &VP1, const ValuePair &VP2); static pair<Function *, Function *> GetContainingFunctionPair( const ValuePair &VP); void collectDynamicAliases(DenseSet<ValuePair> &DynamicAliases); void collectMissingAliases(const DenseSet<ValuePair> &DynamicAliases); void reportMissingAliases(); vector<ValuePair> MissingAliases; }; } static cl::opt<bool> IntraProc( "intra", cl::desc("Whether the checked AA supports intra-procedural queries only")); static cl::opt<string> InputDynamicAliases("input-dyn-aliases", cl::desc("input dynamic aliases")); static cl::opt<bool> CheckAllPointers("check-all-pointers", cl::desc("check all pointers")); static cl::opt<bool> PrintValueInReport("print-value-in-report", cl::desc("print values in the report"), cl::init(true)); static RegisterPass<AliasAnalysisChecker> X( "check-aa", "Check whether the alias analysis is sound", false, // Is CFG Only? true); // Is Analysis? STATISTIC(NumDynamicAliases, "Number of dynamic aliases"); char AliasAnalysisChecker::ID = 0; void AliasAnalysisChecker::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); // Note that DynamicAliasAnalysis is not registered to the // AliasAnalysis group. if (InputDynamicAliases == "") { AU.addRequired<DynamicAliasAnalysis>(); } AU.addRequired<AliasAnalysis>(); AU.addRequired<BaselineAliasAnalysis>(); AU.addRequired<IDAssigner>(); } void AliasAnalysisChecker::collectDynamicAliases( DenseSet<ValuePair> &DynamicAliases) { DynamicAliases.clear(); if (InputDynamicAliases == "") { DynamicAliasAnalysis &DAA = getAnalysis<DynamicAliasAnalysis>(); DynamicAliases.insert(DAA.getAllAliases().begin(), DAA.getAllAliases().end()); } else { IDAssigner &IDA = getAnalysis<IDAssigner>(); ifstream InputFile(InputDynamicAliases.c_str()); unsigned VID1, VID2; while (InputFile >> VID1 >> VID2) { Value *V1 = IDA.getValue(VID1), *V2 = IDA.getValue(VID2); DynamicAliases.insert(make_pair(V1, V2)); } } } // Collects missing aliases to <MissingAliases>. void AliasAnalysisChecker::collectMissingAliases( const DenseSet<ValuePair> &DynamicAliases) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasAnalysis &BaselineAA = getAnalysis<BaselineAliasAnalysis>(); MissingAliases.clear(); for (DenseSet<ValuePair>::const_iterator I = DynamicAliases.begin(); I != DynamicAliases.end(); ++I) { Value *V1 = I->first, *V2 = I->second; if (IntraProc && !DynAAUtils::IsIntraProcQuery(V1, V2)) { continue; } if (!CheckAllPointers) { if (!DynAAUtils::PointerIsDereferenced(V1) || !DynAAUtils::PointerIsDereferenced(V2)) { continue; } } if (BaselineAA.alias(V1, V2) != AliasAnalysis::NoAlias && AA.alias(V1, V2) == AliasAnalysis::NoAlias) { MissingAliases.push_back(make_pair(V1, V2)); } } } // Sorts missing aliases so that missing aliases inside the same function are // likely clustered. bool AliasAnalysisChecker::CompareOnFunction(const ValuePair &VP1, const ValuePair &VP2) { pair<Function *, Function *> FP1 = GetContainingFunctionPair(VP1); pair<Function *, Function *> FP2 = GetContainingFunctionPair(VP2); return FP1 < FP2; } bool AliasAnalysisChecker::runOnModule(Module &M) { DenseSet<ValuePair> DynamicAliases; collectDynamicAliases(DynamicAliases); NumDynamicAliases = DynamicAliases.size(); collectMissingAliases(DynamicAliases); sort(MissingAliases.begin(), MissingAliases.end()); reportMissingAliases(); return false; } pair<Function *, Function *> AliasAnalysisChecker::GetContainingFunctionPair( const ValuePair &VP) { const Function *F1 = DynAAUtils::GetContainingFunction(VP.first); const Function *F2 = DynAAUtils::GetContainingFunction(VP.second); return make_pair(const_cast<Function *>(F1), const_cast<Function *>(F2)); } void AliasAnalysisChecker::reportMissingAliases() { IDAssigner &IDA = getAnalysis<IDAssigner>(); vector<ValuePair> ReportedMissingAliases; for (size_t i = 0; i < MissingAliases.size(); ++i) { Value *V1 = MissingAliases[i].first, *V2 = MissingAliases[i].second; // Do not report BitCasts and PhiNodes. The reports on them are typically // redundant. if (isa<BitCastInst>(V1) || isa<BitCastInst>(V2)) continue; if (isa<PHINode>(V1) || isa<PHINode>(V2)) continue; ReportedMissingAliases.push_back(MissingAliases[i]); } sort(ReportedMissingAliases.begin(), ReportedMissingAliases.end(), CompareOnFunction); for (size_t i = 0; i < ReportedMissingAliases.size(); ++i) { Value *V1 = ReportedMissingAliases[i].first; Value *V2 = ReportedMissingAliases[i].second; errs().changeColor(raw_ostream::RED); errs() << "Missing alias:"; errs().resetColor(); // Print some features of this missing alias. errs() << (DynAAUtils::IsIntraProcQuery(V1, V2) ? " (intra)" : " (inter)"); if (DynAAUtils::PointerIsDereferenced(V1) && DynAAUtils::PointerIsDereferenced(V2)) { errs() << " (deref)"; } else { errs() << " (non-deref)"; } errs() << "\n"; errs() << "[" << IDA.getValueID(V1) << "] "; if (PrintValueInReport) DynAAUtils::PrintValue(errs(), V1); errs() << "\n"; errs() << "[" << IDA.getValueID(V2) << "] "; if (PrintValueInReport) DynAAUtils::PrintValue(errs(), V2); errs() << "\n"; } if (ReportedMissingAliases.empty()) { errs().changeColor(raw_ostream::GREEN); errs() << "Congrats! You passed all the tests.\n"; errs().resetColor(); } else { errs().changeColor(raw_ostream::RED); errs() << "Detected " << ReportedMissingAliases.size() << " missing aliases.\n"; errs().resetColor(); } } <|endoftext|>
<commit_before>// symbiosis: A framework for toy compilers // #include "symbiosis.hpp" #include <sys/stat.h> #include <iostream> #include <vector> #include "cpu_defines.hpp" using namespace std; namespace symbiosis { void dump(uchar* start, size_t s) { for (size_t i = 0; i < s; i++) { printf("%02x ", start[i]); } } #ifdef __x86_64__ bool intel = true; bool arm = false; #endif #ifdef __arm__ bool intel = false; bool arm = true; #endif bool pic_mode; class exception : public std::exception { const char *what_; public: exception(const char *w) : what_(w) { } virtual ~exception() throw() { } virtual const char* what() const throw() { return what_; } }; char *command_file = 0;; #define M10(v, b) #v #b #define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v) #define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v) #define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v) #define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v) uchar *virtual_code_start = 0; uchar *virtual_code_end = 0; uchar *out_code_start = 0; uchar *out_code_end = 0; uchar *out_c = 0; uchar *out_c0 = 0; uchar *virtual_strings_start = 0; uchar *virtual_strings_end = 0; uchar *out_strings_start = 0; uchar *out_strings_end = 0; uchar *out_s = 0; #define STRINGS_START "STRINGS_START" #define STRINGS_END "STRINGS_END" unsigned int _i32 = 0; const char* id::i32() { if (virtual_adr) { _i32 = (size_t)virtual_adr; //printf("virtual_adr: %x\n", _i32); return (const char*)&_i32; } if (type == T_UINT) return (const char*)&d.ui; return (const char*)&d.i; } const char* id::i64() { if (type == T_ULONG) return (const char*)&d.ul; return (const char*)&d.l; } vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong", "charp", "float", "double"}; void id::describe() { if (type > type_str.size() - 1) { cout << "<id:" << type << ">"; } else { cout << type_str[type]; } cout << endl; } id id::operator()(id i) { add_parameter(i); return i; } id_new::id_new(const char *p) : id(p) { virtual_adr = virtual_strings_start + (out_s - out_strings_start); virtual_size = strlen(p); if (out_s + virtual_size + 1 > out_strings_end) throw exception("Strings: Out of memory"); memcpy(out_s, p, virtual_size + 1); out_s += virtual_size + 1; }; const char *reserved_strings[] = { STRINGS_START, M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc) STRINGS_END }; #define FIND(v) { \ pos = 0; \ bool found = false; \ for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \ for (int j = 0; j < v##_s; j++) { \ if (buf[i + j] != v[j]) break; \ if (j == v##_s - 1) { \ pos = i; \ found = true; \ } \ } \ } } uchar buf[200 * 1024]; FILE* input = 0; size_t input_size = 0; void find_space(uchar* start, size_t start_s, uchar* end, size_t end_s, uchar **out_start, uchar **out_end) { if (!input) { input = fopen(command_file, "r"); if (!input) { fprintf(stderr, "Failed\n"); } input_size = fread(buf, 1, sizeof(buf), input); } size_t pos = 0, s = 0, e = 0; FIND(start); s = pos; FIND(end); e = pos; *out_start = &buf[s]; *out_end = &buf[e]; //printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s); } void write() { FILE *out = fopen("a.out", "w"); fwrite(buf, 1, input_size, out); fclose(out); printf("Writing a.out\n"); chmod("a.out", 0777); } int __offset = 0; const char* call_offset(uchar *out_current_code_pos, void *__virt_f) { auto virt_f = (uchar*)__virt_f; ssize_t out_start_distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = virt_f - virtual_code_start; __offset = virt_dist_from_code_start - out_start_distance - 5; cout << "__virt_f: " << __virt_f << endl; //cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl; return (const char*)&__offset; } const char* rip_relative_offset(uchar *out_current_code_pos, uchar *virt_adr) { ssize_t distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = (size_t)virt_adr - (size_t)virtual_code_start - distance; __offset = virt_dist_from_code_start - 7; printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n", (size_t)virt_adr, __offset, (size_t)(out_s - out_strings_start)); return (const char*)&__offset; } int parameter_count = 0; const char *register_parameters_intel_32[] = { "\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ }; const char *register_rip_relative_parameters_intel_64[] = { "\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */ "\x48\x8d\x15" /* rdx */ }; const char *register_parameters_arm_32[] = { "\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ }; const char *register_parameters_intel_64[] = { "\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ }; constexpr int parameters_max = 3; void emit(const char* _s, size_t _l = 0) { size_t l = _l > 0 ? _l : strlen(_s); uchar *s = (uchar *)_s; uchar *e = s + l; if (out_c + l > out_code_end) throw exception("Code: Out of memory"); for (uchar * b = s; b < e; b++, out_c++) { *out_c = *b; } dump(s, l); } void emit(uchar uc) { emit((const char *)&uc, sizeof(uc)); } class Backend { public: Backend() { } virtual ~Backend() { } virtual void add_parameter(id p) = 0; virtual void jmp(void *f) = 0; virtual void __call(void *f) = 0; virtual void __vararg_call(void *f) = 0; }; class Intel : public Backend { public: Intel() : Backend() { } virtual void add_parameter(id p) { if (p.is_charp()) { if (!pic_mode) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else { uchar *out_current_code_pos = out_c; emit(register_rip_relative_parameters_intel_64[parameter_count]); emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); } } else if (p.is_integer()) { if (p.is_32()) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else if (p.is_64()) { emit(register_parameters_intel_64[parameter_count]); emit(p.i64(), 8); } } } virtual void jmp(void *f) { uchar *out_current_code_pos = out_c; emit(I_JMP_e9); emit(call_offset(out_current_code_pos, f), 4); } virtual void __call(void *f) { uchar *out_current_code_pos = out_c; emit(I_CALL_e8); emit(call_offset(out_current_code_pos, f), 4); } virtual void __vararg_call(void *f) { emit(I_XOR_30); emit(0xc0); // xor al,al __call(f); } }; class Arm : public Backend { public: Arm() : Backend() { } virtual void add_parameter(id p) { throw exception("No arm support yet!"); //if (p.is_charp()) { // if (!pic_mode) { // emit(register_parameters_intel_32[parameter_count]); // emit(p.i32(), 4); // } else { // uchar *out_current_code_pos = out_c; // emit(register_rip_relative_parameters_intel_64[parameter_count]); // emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); // } //} else if (p.is_integer()) { // if (p.is_32()) { // emit(register_parameters_intel_32[parameter_count]); // emit(p.i32(), 4); // } else if (p.is_64()) { // emit(register_parameters_intel_64[parameter_count]); // emit(p.i64(), 8); // } //} } virtual void jmp(void *f) { throw exception("No arm support yet!"); } virtual void __call(void *f) { throw exception("No arm support yet!"); } virtual void __vararg_call(void *f) { throw exception("No arm support yet!"); } }; Backend* backend; id add_parameter(id p) { if (parameter_count >= parameters_max) { fprintf(stderr, "Too many parameters!\n"); return p; } backend->add_parameter(p); ++parameter_count; return p; } void jmp(void *f) { backend->jmp(f); } void __call(void *f) { backend->__call(f); parameter_count = 0; } void __vararg_call(void *f) { backend->__vararg_call(f); } void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) { //if (!identify_cpu_and_pic_mode()) exit(1); cout << "intel: " << intel << ", arm: " << arm << ", pic_mode: " << pic_mode << endl; if (intel) { backend = new Intel(); } if (arm) { backend = new Arm(); } command_file = c; virtual_code_start = start; virtual_code_end = end; find_space(start, ss, end, es, &out_code_start, &out_code_end); virtual_strings_start = (uchar *)STRINGS_START; virtual_strings_end = (uchar *)STRINGS_END; out_c = out_code_start; find_space(virtual_strings_start, strlen(STRINGS_START), virtual_strings_end, strlen(STRINGS_END), &out_strings_start, &out_strings_end); out_s = out_strings_start; } void finish() { jmp(virtual_code_end); write(); } } <commit_msg>Introduced callbacks for PC relative LDRs on ARM.<commit_after>// symbiosis: A framework for toy compilers // #include "symbiosis.hpp" #include <sys/stat.h> #include <iostream> #include <vector> #include <functional> #include "cpu_defines.hpp" using namespace std; namespace symbiosis { void dump(uchar* start, size_t s) { for (size_t i = 0; i < s; i++) { printf("%02x ", start[i]); } } #ifdef __x86_64__ bool intel = true; bool arm = false; #endif #ifdef __arm__ bool intel = false; bool arm = true; #endif bool pic_mode; class exception : public std::exception { const char *what_; public: exception(const char *w) : what_(w) { } virtual ~exception() throw() { } virtual const char* what() const throw() { return what_; } }; char *command_file = 0;; #define M10(v, b) #v #b #define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v) #define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v) #define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v) #define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v) uchar *virtual_code_start = 0; uchar *virtual_code_end = 0; uchar *out_code_start = 0; uchar *out_code_end = 0; uchar *out_c = 0; uchar *out_c0 = 0; uchar *virtual_strings_start = 0; uchar *virtual_strings_end = 0; uchar *out_strings_start = 0; uchar *out_strings_end = 0; uchar *out_s = 0; #define STRINGS_START "STRINGS_START" #define STRINGS_END "STRINGS_END" unsigned int _i32 = 0; const char* id::i32() { if (virtual_adr) { _i32 = (size_t)virtual_adr; //printf("virtual_adr: %x\n", _i32); return (const char*)&_i32; } if (type == T_UINT) return (const char*)&d.ui; return (const char*)&d.i; } const char* id::i64() { if (type == T_ULONG) return (const char*)&d.ul; return (const char*)&d.l; } vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong", "charp", "float", "double"}; void id::describe() { if (type > type_str.size() - 1) { cout << "<id:" << type << ">"; } else { cout << type_str[type]; } cout << endl; } id id::operator()(id i) { add_parameter(i); return i; } id_new::id_new(const char *p) : id(p) { virtual_adr = virtual_strings_start + (out_s - out_strings_start); virtual_size = strlen(p); if (out_s + virtual_size + 1 > out_strings_end) throw exception("Strings: Out of memory"); memcpy(out_s, p, virtual_size + 1); out_s += virtual_size + 1; }; const char *reserved_strings[] = { STRINGS_START, M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc) STRINGS_END }; #define FIND(v) { \ pos = 0; \ bool found = false; \ for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \ for (int j = 0; j < v##_s; j++) { \ if (buf[i + j] != v[j]) break; \ if (j == v##_s - 1) { \ pos = i; \ found = true; \ } \ } \ } } uchar buf[200 * 1024]; FILE* input = 0; size_t input_size = 0; void find_space(uchar* start, size_t start_s, uchar* end, size_t end_s, uchar **out_start, uchar **out_end) { if (!input) { input = fopen(command_file, "r"); if (!input) { fprintf(stderr, "Failed\n"); } input_size = fread(buf, 1, sizeof(buf), input); } size_t pos = 0, s = 0, e = 0; FIND(start); s = pos; FIND(end); e = pos; *out_start = &buf[s]; *out_end = &buf[e]; //printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s); } void write() { FILE *out = fopen("a.out", "w"); fwrite(buf, 1, input_size, out); fclose(out); printf("Writing a.out\n"); chmod("a.out", 0777); } int __offset = 0; const char* call_offset(uchar *out_current_code_pos, void *__virt_f) { auto virt_f = (uchar*)__virt_f; ssize_t out_start_distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = virt_f - virtual_code_start; __offset = virt_dist_from_code_start - out_start_distance - 5; cout << "__virt_f: " << __virt_f << endl; //cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl; return (const char*)&__offset; } const char* rip_relative_offset(uchar *out_current_code_pos, uchar *virt_adr) { ssize_t distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = (size_t)virt_adr - (size_t)virtual_code_start - distance; __offset = virt_dist_from_code_start - 7; printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n", (size_t)virt_adr, __offset, (size_t)(out_s - out_strings_start)); return (const char*)&__offset; } constexpr int parameters_max = 3; void emit(const char* _s, size_t _l = 0) { size_t l = _l > 0 ? _l : strlen(_s); uchar *s = (uchar *)_s; uchar *e = s + l; if (out_c + l > out_code_end) throw exception("Code: Out of memory"); for (uchar * b = s; b < e; b++, out_c++) { *out_c = *b; } dump(s, l); } void emit(uchar uc) { emit((const char *)&uc, sizeof(uc)); } class Backend { vector<function<void()> > callbacks; public: int parameter_count = 0; Backend() { } virtual ~Backend() { } void callback(function<void()> f) { callbacks.push_back(f); } void perform_callbacks() { for (size_t i = 0; i < callbacks.size(); ++i) { callbacks[i](); }} virtual void add_parameter(id p) = 0; virtual void jmp(void *f) = 0; virtual void __call(void *f) = 0; virtual void __vararg_call(void *f) = 0; }; const char *register_parameters_intel_32[] = { "\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ }; const char *register_rip_relative_parameters_intel_64[] = { "\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */ "\x48\x8d\x15" /* rdx */ }; const char *register_parameters_intel_64[] = { "\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ }; class Intel : public Backend { public: Intel() : Backend() { } virtual void add_parameter(id p) { if (p.is_charp()) { if (!pic_mode) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else { uchar *out_current_code_pos = out_c; emit(register_rip_relative_parameters_intel_64[parameter_count]); emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); } } else if (p.is_integer()) { if (p.is_32()) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else if (p.is_64()) { emit(register_parameters_intel_64[parameter_count]); emit(p.i64(), 8); } } } virtual void jmp(void *f) { uchar *out_current_code_pos = out_c; emit(I_JMP_e9); emit(call_offset(out_current_code_pos, f), 4); } virtual void __call(void *f) { uchar *out_current_code_pos = out_c; emit(I_CALL_e8); emit(call_offset(out_current_code_pos, f), 4); } virtual void __vararg_call(void *f) { emit(I_XOR_30); emit(0xc0); // xor al,al __call(f); } }; const char *register_parameters_arm_32[] = { "\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ }; class Arm : public Backend { public: Arm() : Backend() { } virtual void add_parameter(id p) { //if (p.is_charp()) { // if (!pic_mode) { // emit(register_parameters_intel_32[parameter_count]); // emit(p.i32(), 4); // } else { // uchar *out_current_code_pos = out_c; // emit(register_rip_relative_parameters_intel_64[parameter_count]); // emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); // } if (p.is_integer()) { if (p.is_32()) { emit(register_parameters_arm_32[parameter_count]); uchar *ldr_p = out_c - 1; emit("\x0"); callback([=]() { cout << "Would set: " << ldr_p << endl; }); } else if (p.is_64()) { throw exception("64bit not supported yet!"); } } else { throw exception("No integer not supported yet"); } } virtual void jmp(void *f) { throw exception("No arm support yet!"); } virtual void __call(void *f) { //throw exception("No arm support yet!"); perform_callbacks(); } virtual void __vararg_call(void *f) { throw exception("No arm support yet!"); } }; Backend* backend; id add_parameter(id p) { if (backend->parameter_count >= parameters_max) { fprintf(stderr, "Too many parameters!\n"); return p; } backend->add_parameter(p); ++backend->parameter_count; return p; } void jmp(void *f) { backend->jmp(f); } void __call(void *f) { backend->__call(f); backend->parameter_count = 0; } void __vararg_call(void *f) { backend->__vararg_call(f); } void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) { //if (!identify_cpu_and_pic_mode()) exit(1); cout << "intel: " << intel << ", arm: " << arm << ", pic_mode: " << pic_mode << endl; if (intel) { backend = new Intel(); } if (arm) { backend = new Arm(); } command_file = c; virtual_code_start = start; virtual_code_end = end; find_space(start, ss, end, es, &out_code_start, &out_code_end); virtual_strings_start = (uchar *)STRINGS_START; virtual_strings_end = (uchar *)STRINGS_END; out_c = out_code_start; find_space(virtual_strings_start, strlen(STRINGS_START), virtual_strings_end, strlen(STRINGS_END), &out_strings_start, &out_strings_end); out_s = out_strings_start; } void finish() { jmp(virtual_code_end); write(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbtreeview.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: rt $ $Date: 2005-09-08 14:27:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif #include "dbaccess_helpid.hrc" // ......................................................................... namespace dbaui { // ......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; DBG_NAME(DBTreeView) //======================================================================== // class DBTreeView //======================================================================== DBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits) : Window( pParent, nBits ) , m_pTreeListBox(NULL) { DBG_CTOR(DBTreeView,NULL); m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_HASLINES | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT,sal_True); m_pTreeListBox->EnableCheckButton(NULL); m_pTreeListBox->SetDragDropMode( 0 ); m_pTreeListBox->EnableInplaceEditing( sal_True ); m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX); m_pTreeListBox->Show(); } // ----------------------------------------------------------------------------- DBTreeView::~DBTreeView() { DBG_DTOR(DBTreeView,NULL); if (m_pTreeListBox) { if (m_pTreeListBox->GetModel()) { m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox); m_pTreeListBox->DisconnectFromModel(); } ::std::auto_ptr<Window> aTemp(m_pTreeListBox); m_pTreeListBox = NULL; } } // ----------------------------------------------------------------------------- void DBTreeView::SetPreExpandHandler(const Link& _rHdl) { m_pTreeListBox->SetPreExpandHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::GetPreExpandHandler() const { return m_pTreeListBox->GetPreExpandHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setCutHandler(const Link& _rHdl) { m_pTreeListBox->setCutHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getCutHandler() const { return m_pTreeListBox->getCutHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setCopyHandler(const Link& _rHdl) { m_pTreeListBox->setCopyHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getCopyHandler() const { return m_pTreeListBox->getCopyHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setPasteHandler(const Link& _rHdl) { m_pTreeListBox->setPasteHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getPasteHandler() const { return m_pTreeListBox->getPasteHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setDeleteHandler(const Link& _rHdl) { m_pTreeListBox->setDeleteHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getDeleteHandler() const { return m_pTreeListBox->getDeleteHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setEditingHandler(const Link& _rHdl) { m_pTreeListBox->setEditingHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getEditingHandler() const { return m_pTreeListBox->getEditingHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setEditedHandler(const Link& _rHdl) { m_pTreeListBox->setEditedHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getEditedHandler() const { return m_pTreeListBox->getEditedHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::Resize() { Window::Resize(); m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel()); } // ------------------------------------------------------------------------- DBTreeListModel* DBTreeView::getModel() const { return (DBTreeListModel*)m_pTreeListBox->GetModel(); } // ------------------------------------------------------------------------- void DBTreeView::setModel(DBTreeListModel* _pTreeModel) { if (_pTreeModel) _pTreeModel->InsertView(m_pTreeListBox); m_pTreeListBox->SetModel(_pTreeModel); } // ------------------------------------------------------------------------- DBTreeListBox* DBTreeView::getListBox() const { return m_pTreeListBox; } // ------------------------------------------------------------------------- void DBTreeView::setSelectHdl(const Link& _rHdl) { m_pTreeListBox->SetSelectHdl(_rHdl); } // ----------------------------------------------------------------------------- void DBTreeView::GetFocus() { Window::GetFocus(); if ( m_pTreeListBox )//&& !m_pTreeListBox->HasChildPathFocus()) m_pTreeListBox->GrabFocus(); } // ......................................................................... } // namespace dbaui // ......................................................................... <commit_msg>INTEGRATION: CWS pchfix02 (1.19.184); FILE MERGED 2006/09/01 17:24:21 kaib 1.19.184.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dbtreeview.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: obo $ $Date: 2006-09-17 06:57:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif #include "dbaccess_helpid.hrc" // ......................................................................... namespace dbaui { // ......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; DBG_NAME(DBTreeView) //======================================================================== // class DBTreeView //======================================================================== DBTreeView::DBTreeView( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nBits) : Window( pParent, nBits ) , m_pTreeListBox(NULL) { DBG_CTOR(DBTreeView,NULL); m_pTreeListBox = new DBTreeListBox(this, _rxORB ,WB_HASLINES | WB_SORT | WB_HASBUTTONS | WB_HSCROLL |WB_HASBUTTONSATROOT,sal_True); m_pTreeListBox->EnableCheckButton(NULL); m_pTreeListBox->SetDragDropMode( 0 ); m_pTreeListBox->EnableInplaceEditing( sal_True ); m_pTreeListBox->SetHelpId(HID_TLB_TREELISTBOX); m_pTreeListBox->Show(); } // ----------------------------------------------------------------------------- DBTreeView::~DBTreeView() { DBG_DTOR(DBTreeView,NULL); if (m_pTreeListBox) { if (m_pTreeListBox->GetModel()) { m_pTreeListBox->GetModel()->RemoveView(m_pTreeListBox); m_pTreeListBox->DisconnectFromModel(); } ::std::auto_ptr<Window> aTemp(m_pTreeListBox); m_pTreeListBox = NULL; } } // ----------------------------------------------------------------------------- void DBTreeView::SetPreExpandHandler(const Link& _rHdl) { m_pTreeListBox->SetPreExpandHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::GetPreExpandHandler() const { return m_pTreeListBox->GetPreExpandHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setCutHandler(const Link& _rHdl) { m_pTreeListBox->setCutHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getCutHandler() const { return m_pTreeListBox->getCutHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setCopyHandler(const Link& _rHdl) { m_pTreeListBox->setCopyHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getCopyHandler() const { return m_pTreeListBox->getCopyHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setPasteHandler(const Link& _rHdl) { m_pTreeListBox->setPasteHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getPasteHandler() const { return m_pTreeListBox->getPasteHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setDeleteHandler(const Link& _rHdl) { m_pTreeListBox->setDeleteHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getDeleteHandler() const { return m_pTreeListBox->getDeleteHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setEditingHandler(const Link& _rHdl) { m_pTreeListBox->setEditingHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getEditingHandler() const { return m_pTreeListBox->getEditingHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::setEditedHandler(const Link& _rHdl) { m_pTreeListBox->setEditedHandler(_rHdl); } // ----------------------------------------------------------------------------- Link DBTreeView::getEditedHandler() const { return m_pTreeListBox->getEditedHandler(); } // ----------------------------------------------------------------------------- void DBTreeView::Resize() { Window::Resize(); m_pTreeListBox->SetPosSizePixel(Point(0,0),GetOutputSizePixel()); } // ------------------------------------------------------------------------- DBTreeListModel* DBTreeView::getModel() const { return (DBTreeListModel*)m_pTreeListBox->GetModel(); } // ------------------------------------------------------------------------- void DBTreeView::setModel(DBTreeListModel* _pTreeModel) { if (_pTreeModel) _pTreeModel->InsertView(m_pTreeListBox); m_pTreeListBox->SetModel(_pTreeModel); } // ------------------------------------------------------------------------- DBTreeListBox* DBTreeView::getListBox() const { return m_pTreeListBox; } // ------------------------------------------------------------------------- void DBTreeView::setSelectHdl(const Link& _rHdl) { m_pTreeListBox->SetSelectHdl(_rHdl); } // ----------------------------------------------------------------------------- void DBTreeView::GetFocus() { Window::GetFocus(); if ( m_pTreeListBox )//&& !m_pTreeListBox->HasChildPathFocus()) m_pTreeListBox->GrabFocus(); } // ......................................................................... } // namespace dbaui // ......................................................................... <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <sstream> #include <glm/vec3.hpp> #include <map> #include "box.hpp" #include "sdfloader.hpp" #include "scene.hpp" #include "material.hpp" #include "camera.hpp" #include "color.hpp" #include "sphere.hpp" Sdfloader::Sdfloader() : file_{""} {} Sdfloader::Sdfloader(std::string file) : file_{file} {} Sdfloader::~Sdfloader() {} Scene Sdfloader::loadscene(std::string file) const{ std::ifstream datei(file, std::ios::in); Scene scene{}; std::string line, name; std::stringstream flt; if (datei.good()){ std::cout << "File is good." << std::endl; while(datei >> line){ if (line.compare("#") == 0 || line.compare("") == 0){ continue; } else if (line.compare("camera") == 0){ datei >> name; datei >> line; flt << line; float fovx; flt >> fovx; flt.clear(); Camera c{name, fovx}; scene.camera = c; } else if (line.compare("renderer") == 0){ std::string camname; datei >> camname; //falls der renderer doch angepasst wird std::string filename; datei >> filename; datei >> line; unsigned xres; unsigned yres; flt << line; flt >> xres; flt.clear(); datei >> line; flt << line; flt >> yres; flt.clear(); Renderer r{xres, yres, filename}; scene.renderer = r; } else if (line.compare("define") == 0){ datei >> line; if (line.compare("material") == 0){ datei >> name; float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ka(r,g,b); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color kd(r,g,b); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ks(r,g,b); flt.clear(); float m; datei >> line; flt << line; flt >> m; flt.clear(); Material mat{name, ka, kd, ks, m}; scene.materials[name] = mat; } else if (line.compare("amblight") == 0){ float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color amb(r,g,b); flt.clear(); scene.amblight = amb; } else if (line.compare("background") == 0){ float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color back(r,g,b); flt.clear(); scene.background = back; } else if (line.compare("light") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 pos(x,y,z); flt.clear(); float r, g, b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ld(r,g,b); flt.clear(); Light light(name, pos, ld); scene.lights.push_back(light); } else if (line.compare("shape") == 0){ datei >> line; if (line.compare("box") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 p1(x,y,z); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 p2(x,y,z); flt.clear(); datei >> line; std::shared_ptr<Shape> s_ptr = std::make_shared<Box>( Box{ p1, p2, name, scene.materials[line] } ); scene.shapes.push_back(s_ptr); } if (line.compare("sphere") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 pos(x,y,z); flt.clear(); datei >> line; flt << line; float r; flt >> r; datei >> line; std::shared_ptr<Shape> sphere(new Sphere(pos, r,name, scene.materials[line])); scene.shapes.push_back(sphere); } } } } } else if (datei.fail()){ std::cout << "File is bad." << std::endl; } else{ std::cout << "No file found." << std::endl; } return scene; } <commit_msg>update<commit_after>#include <iostream> #include <string> #include <fstream> #include <sstream> #include <glm/vec3.hpp> #include <map> #include "box.hpp" #include "sdfloader.hpp" #include "scene.hpp" #include "material.hpp" #include "camera.hpp" #include "color.hpp" #include "sphere.hpp" Sdfloader::Sdfloader() : file_{""} {} Sdfloader::Sdfloader(std::string file) : file_{file} {} Sdfloader::~Sdfloader() {} Scene Sdfloader::loadscene(std::string file) const{ std::ifstream datei(file, std::ios::in); std::string line, name; std::stringstream flt; std::map<std::string, Material> matmap; std::vector<std::shared_ptr <Shape>> shapevec; std::vector<Light> lightvec; if (datei.good()){ std::cout << "File is good." << std::endl; while(datei >> line){ if (line.compare("#") == 0 || line.compare("") == 0){ continue; } else if (line.compare("camera") == 0){ datei >> name; datei >> line; flt << line; float fovx; flt >> fovx; flt.clear(); Camera c{name, fovx}; scene.camera = c; } else if (line.compare("renderer") == 0){ std::string camname; datei >> camname; //falls der renderer doch angepasst wird std::string filename; datei >> filename; datei >> line; unsigned xres; unsigned yres; flt << line; flt >> xres; flt.clear(); datei >> line; flt << line; flt >> yres; flt.clear(); Renderer r{xres, yres, filename}; scene.renderer = r; } else if (line.compare("define") == 0){ datei >> line; if (line.compare("material") == 0){ datei >> name; float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ka(r,g,b); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color kd(r,g,b); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ks(r,g,b); flt.clear(); float m; datei >> line; flt << line; flt >> m; flt.clear(); Material mat{name, ka, kd, ks, m}; scene.materials[name] = mat; } else if (line.compare("amblight") == 0){ float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color amb(r,g,b); flt.clear(); scene.amblight = amb; } else if (line.compare("background") == 0){ float r,g,b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color back(r,g,b); flt.clear(); scene.background = back; } else if (line.compare("light") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 pos(x,y,z); flt.clear(); float r, g, b; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> r >> g >> b; Color ld(r,g,b); flt.clear(); Light light(name, pos, ld); scene.lights.push_back(light); } else if (line.compare("shape") == 0){ datei >> line; if (line.compare("box") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 p1(x,y,z); flt.clear(); datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 p2(x,y,z); flt.clear(); datei >> line; std::shared_ptr<Shape> s_ptr = std::make_shared<Box>( Box{ p1, p2, name, scene.materials[line] } ); scene.shapes.push_back(s_ptr); } if (line.compare("sphere") == 0){ datei >> name; float x, y, z; datei >> line; flt << line << ' '; datei >> line; flt << line << ' '; datei >> line; flt << line; flt >> x >> y >> z; glm::vec3 pos(x,y,z); flt.clear(); datei >> line; flt << line; float r; flt >> r; datei >> line; std::shared_ptr<Shape> sphere(new Sphere(pos, r,name, scene.materials[line])); scene.shapes.push_back(sphere); } } } } } else if (datei.fail()){ std::cout << "File is bad." << std::endl; } else{ std::cout << "No file found." << std::endl; } Scene scene{}; return scene; } <|endoftext|>
<commit_before>#ifndef SDF_LOADER_HPP #define SDF_LOADER_HPP #include <iostream> #include <fstream> #include <string> #include <vector> #include "material.hpp" struct SDFloader { SDFloader() : {}; void sdfLoad(std::string const& inputFile) { std::fstream input; input.open(inputFile); if(input.is_open()) { std::stringstream stream; std::string line; std::string word; std::vector<Material> vec_material; while(std::getline(input, line)) { stream << line; stream >> word; if(word == "define") { stream >> word; if(word == "material") { int i = 16; //gets name std::string name; while(line.at(i) != ' ') { name.push_back(line[i]); ++i; } ++i; std::vector<float> numbers(10); for(int j = 0; j < numbers.size(); ++j) { //gets numbers for colours etc float a = line[i] - '0'; numbers[j] = a; i = i+2; } Color color1(numbers[0], numbers[1], numbers[2]); Color color2(numbers[3], numbers[4], numbers[5]); Color color3(numbers[6], numbers[7], numbers[8]); Material material(name, color1, color2, color3, numbers[9]); vec_material.push_back(material); } } } for (std::vector<Material>::iterator it = vec_material.begin(); it != vec_material.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; } else { std::cout << "Couldn't find file." << std::endl; } } }:<commit_msg>sdfloader looks better now maybe lissy out<commit_after>#ifndef SDF_LOADER_HPP #define SDF_LOADER_HPP #include <iostream> #include <fstream> #include <string> #include <vector> #include "material.hpp" struct SDFloader { SDFloader() : {}; void sdfLoad(std::string const& inputFile) { std::fstream input; input.open(inputFile); if(input.is_open()) { std::stringstream stream; std::string line; std::string word; std::vector<Material> vec_material; while(std::getline(input, line)) { stream << line; stream >> word; if(word == "define") { stream >> word; if(word == "material") { Material material; stream >> material.m_name; stream >> material.m_ka.r; stream >> material.m_ka.g; stream >> material.m_ka.b; stream >> material.m_kd.r; stream >> material.m_kd.g; stream >> material.m_kd.b; stream >> material.m_ks.r; stream >> material.m_ks.g; stream >> material.m_ks.b; } } } for (std::vector<Material>::iterator it = vec_material.begin(); it != vec_material.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; } else { std::cout << "Couldn't find file." << std::endl; } } }:<|endoftext|>
<commit_before>//===-------------- AliasAnalysis.cpp - SIL Alias Analysis ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-aa" #include "swift/SILPasses/Utils/AliasAnalysis.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILArgument.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// /// Strip off casts/address projections from V until there is nothing /// left to strip. static SILValue getUnderlyingObject(SILValue V) { while (true) { SILValue V2 = V.stripCasts().stripAddressProjections().stripIndexingInsts(); if (V2 == V) return V2; V = V2; } } /// Returns true if Kind is one of AllocStackInst, AllocBoxInst, AllocRefInst, /// or AllocArrayInst. static bool isAllocationInst(ValueKind Kind) { switch (Kind) { case ValueKind::AllocStackInst: case ValueKind::AllocBoxInst: case ValueKind::AllocRefInst: case ValueKind::AllocArrayInst: return true; default: return false; } } /// A no alias argument is an argument that is an address type. static bool isNoAliasArgument(SILValue V) { auto *Arg = dyn_cast<SILArgument>(V.getDef()); if (!Arg) return false; return Arg->getType().isAddress(); } /// Return true if V is an object that at compile time can be uniquely /// identified. static bool isIdentifiableObject(SILValue V) { ValueKind Kind = V->getKind(); if (isAllocationInst(Kind) || isNoAliasArgument(V) || isa<LiteralInst>(*V)) return true; return false; } /// Returns true if we can prove that the two input SILValues which do not equal /// can not alias. static bool aliasUnequalObjects(SILValue O1, SILValue O2) { assert(O1 != O2 && "This function should only be called on unequal values."); // If O1 and O2 do not equal and they are both values that can be statically // and uniquely identified, they can not alias. if (isIdentifiableObject(O1) && isIdentifiableObject(O2)) return true; // We failed to prove that the two objects are different. return false; } //===----------------------------------------------------------------------===// // Entry Points //===----------------------------------------------------------------------===// AliasAnalysis::AliasResult AliasAnalysis::alias(SILValue V1, SILValue V2) { DEBUG(llvm::dbgs() << "ALIAS ANALYSIS:\n V1: " << *V1.getDef() << " V2: " << *V2.getDef()); // Strip off any casts on V1, V2. V1 = V1.stripCasts(); V2 = V2.stripCasts(); DEBUG(llvm::dbgs() << " After Cast Stripping V1:" << *V1.getDef()); DEBUG(llvm::dbgs() << " After Cast Stripping V2:" << *V2.getDef()); // Create a key to lookup if we have already computed an alias result for V1, // V2. Canonicalize our cache keys so that the pointer with the lower address // is always the first element of the pair. This ensures we do not pollute our // cache with two entries with the same key, albeit with the key's fields // swapped. auto Key = V1 < V2? std::make_pair(V1, V2) : std::make_pair(V2, V1); // If we find our key in the cache, just return the alias result. auto Pair = AliasCache.find(Key); if (Pair != AliasCache.end()) { DEBUG(llvm::dbgs() << " Found value in the cache: " << unsigned(Pair->second)); return Pair->second; } // Ok, we need to actually compute an Alias Analysis result for V1, V2. Begin // by finding the "base" of V1, V2 by stripping off all casts and GEPs. SILValue O1 = getUnderlyingObject(V1); SILValue O2 = getUnderlyingObject(V2); // If O1 and O2 do not equal, see if we can prove that they can not be the // same object. If we can, return No Alias. if (O1 != O2 && aliasUnequalObjects(O1, O2)) return AliasCache[Key] = AliasResult::NoAlias; // We could not prove anything. Be conservative and return that V1, V2 may // alias. return AliasResult::MayAlias; } SILInstruction::MemoryBehavior AliasAnalysis::getMemoryBehavior(SILInstruction *Inst, SILValue V) { DEBUG(llvm::dbgs() << "GET MEMORY BEHAVIOR FOR:\n " << *Inst << " " << *V.getDef()); // If we already know that we do not read or write memory, just return None. if (!Inst->mayReadOrWriteMemory()) { DEBUG(llvm::dbgs() << " Inst does not write memory. Returning None.\n"); return MemoryBehavior::None; } switch (Inst->getKind()) { case ValueKind::LoadInst: // If the load address doesn't alias the given address, it doesn't read or // write the specified memory. if (alias(Inst->getOperand(0), V) == AliasResult::NoAlias) { DEBUG(llvm::dbgs() << " Load does not alias inst. Returning None.\n"); return MemoryBehavior::None; } // Otherwise be conservative and just return reads since loads can only // read. DEBUG(llvm::dbgs() << " Could not prove load does not alias inst. " "Returning MayRead.\n"); return MemoryBehavior::MayRead; case ValueKind::StoreInst: // If the store dest cannot alias the pointer in question, then the // specified value can not be modified by the store. if (alias(cast<StoreInst>(Inst)->getDest(), V) == AliasResult::NoAlias) { DEBUG(llvm::dbgs() << " Store Dst does not alias inst. Returning " "None.\n"); return MemoryBehavior::None; } // Otherwise, a store just writes. DEBUG(llvm::dbgs() << " Could not prove store does not alias inst. " "Returning MayWrite.\n"); return MemoryBehavior::MayWrite; case ValueKind::ApplyInst: { // If the ApplyInst is from a no-read builtin it can not read or write and // if it comes from a no-side effect builtin, it can only read. auto *AI = cast<ApplyInst>(Inst); auto *BFR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef()); // If our callee is not a builtin, be conservative and return may have side // effects. if (!BFR) { DEBUG(llvm::dbgs() << " Found apply we don't understand returning " "MHSF.\n"); return MemoryBehavior::MayHaveSideEffects; } // If the builtin is read none, it does not read or write memory. if (isReadNone(BFR)) { DEBUG(llvm::dbgs() << " Found apply of read none builtin. Returning" " None.\n"); return MemoryBehavior::None; } // If the builtin is side effect free, then it can only read memory. if (isSideEffectFree(BFR)) { DEBUG(llvm::dbgs() << " Found apply of side effect free builtin. " "Returning MayRead.\n"); return MemoryBehavior::MayRead; } // Otherwise be conservative and return that we may have side effects. DEBUG(llvm::dbgs() << " Found apply of side effect builtin. " "Returning MayHaveSideEffects.\n"); return MemoryBehavior::MayHaveSideEffects; } default: // If we do not have a special case, just return the generic memory // behavior of Inst. return Inst->getMemoryBehavior(); } } <commit_msg>[sil-aa] Some more debug statements and small cleanups. NFC.<commit_after>//===-------------- AliasAnalysis.cpp - SIL Alias Analysis ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-aa" #include "swift/SILPasses/Utils/AliasAnalysis.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILArgument.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// /// Strip off casts/indexing insts/address projections from V until there is /// nothing left to strip. static SILValue getUnderlyingObject(SILValue V) { while (true) { SILValue V2 = V.stripCasts().stripAddressProjections().stripIndexingInsts(); if (V2 == V) return V2; V = V2; } } /// Returns true if Kind is one of AllocStackInst, AllocBoxInst, AllocRefInst, /// or AllocArrayInst. static bool isAllocationInst(ValueKind Kind) { switch (Kind) { case ValueKind::AllocStackInst: case ValueKind::AllocBoxInst: case ValueKind::AllocRefInst: case ValueKind::AllocArrayInst: return true; default: return false; } } /// A no alias argument is an argument that is an address type. static bool isNoAliasArgument(SILValue V) { auto *Arg = dyn_cast<SILArgument>(V.getDef()); if (!Arg) return false; return Arg->getType().isAddress(); } /// Return true if V is an object that at compile time can be uniquely /// identified. static bool isIdentifiableObject(SILValue V) { ValueKind Kind = V->getKind(); if (isAllocationInst(Kind) || isNoAliasArgument(V) || isa<LiteralInst>(*V)) return true; return false; } /// Returns true if we can prove that the two input SILValues which do not equal /// can not alias. static bool aliasUnequalObjects(SILValue O1, SILValue O2) { assert(O1 != O2 && "This function should only be called on unequal values."); // If O1 and O2 do not equal and they are both values that can be statically // and uniquely identified, they can not alias. if (isIdentifiableObject(O1) && isIdentifiableObject(O2)) return true; // We failed to prove that the two objects are different. return false; } //===----------------------------------------------------------------------===// // Entry Points //===----------------------------------------------------------------------===// AliasAnalysis::AliasResult AliasAnalysis::alias(SILValue V1, SILValue V2) { DEBUG(llvm::dbgs() << "ALIAS ANALYSIS:\n V1: " << *V1.getDef() << " V2: " << *V2.getDef()); // Strip off any casts on V1, V2. V1 = V1.stripCasts(); V2 = V2.stripCasts(); DEBUG(llvm::dbgs() << " After Cast Stripping V1:" << *V1.getDef()); DEBUG(llvm::dbgs() << " After Cast Stripping V2:" << *V2.getDef()); // Create a key to lookup if we have already computed an alias result for V1, // V2. Canonicalize our cache keys so that the pointer with the lower address // is always the first element of the pair. This ensures we do not pollute our // cache with two entries with the same key, albeit with the key's fields // swapped. auto Key = V1 < V2? std::make_pair(V1, V2) : std::make_pair(V2, V1); // If we find our key in the cache, just return the alias result. auto Pair = AliasCache.find(Key); if (Pair != AliasCache.end()) { DEBUG(llvm::dbgs() << " Found value in the cache: " << unsigned(Pair->second)); return Pair->second; } // Ok, we need to actually compute an Alias Analysis result for V1, V2. Begin // by finding the "base" of V1, V2 by stripping off all casts and GEPs. SILValue O1 = getUnderlyingObject(V1); SILValue O2 = getUnderlyingObject(V2); DEBUG(llvm::dbgs() << " Underlying V1:" << *O1.getDef()); DEBUG(llvm::dbgs() << " Underlying V2:" << *O2.getDef()); // If O1 and O2 do not equal, see if we can prove that they can not be the // same object. If we can, return No Alias. if (O1 != O2 && aliasUnequalObjects(O1, O2)) return AliasCache[Key] = AliasResult::NoAlias; // We could not prove anything. Be conservative and return that V1, V2 may // alias. return AliasResult::MayAlias; } SILInstruction::MemoryBehavior AliasAnalysis::getMemoryBehavior(SILInstruction *Inst, SILValue V) { DEBUG(llvm::dbgs() << "GET MEMORY BEHAVIOR FOR:\n " << *Inst << " " << *V.getDef()); // If we already know that we do not read or write memory, just return None. if (!Inst->mayReadOrWriteMemory()) { DEBUG(llvm::dbgs() << " Inst does not write memory. Returning None.\n"); return MemoryBehavior::None; } switch (Inst->getKind()) { case ValueKind::LoadInst: // If the load address doesn't alias the given address, it doesn't read or // write the specified memory. if (alias(Inst->getOperand(0), V) == AliasResult::NoAlias) { DEBUG(llvm::dbgs() << " Load does not alias inst. Returning None.\n"); return MemoryBehavior::None; } // Otherwise be conservative and just return reads since loads can only // read. DEBUG(llvm::dbgs() << " Could not prove load does not alias inst. " "Returning MayRead.\n"); return MemoryBehavior::MayRead; case ValueKind::StoreInst: // If the store dest cannot alias the pointer in question, then the // specified value can not be modified by the store. if (alias(cast<StoreInst>(Inst)->getDest(), V) == AliasResult::NoAlias) { DEBUG(llvm::dbgs() << " Store Dst does not alias inst. Returning " "None.\n"); return MemoryBehavior::None; } // Otherwise, a store just writes. DEBUG(llvm::dbgs() << " Could not prove store does not alias inst. " "Returning MayWrite.\n"); return MemoryBehavior::MayWrite; case ValueKind::ApplyInst: { // If the ApplyInst is from a no-read builtin it can not read or write and // if it comes from a no-side effect builtin, it can only read. auto *AI = cast<ApplyInst>(Inst); auto *BFR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef()); // If our callee is not a builtin, be conservative and return may have side // effects. if (!BFR) { DEBUG(llvm::dbgs() << " Found apply we don't understand returning " "MHSF.\n"); return MemoryBehavior::MayHaveSideEffects; } // If the builtin is read none, it does not read or write memory. if (isReadNone(BFR)) { DEBUG(llvm::dbgs() << " Found apply of read none builtin. Returning" " None.\n"); return MemoryBehavior::None; } // If the builtin is side effect free, then it can only read memory. if (isSideEffectFree(BFR)) { DEBUG(llvm::dbgs() << " Found apply of side effect free builtin. " "Returning MayRead.\n"); return MemoryBehavior::MayRead; } // Otherwise be conservative and return that we may have side effects. DEBUG(llvm::dbgs() << " Found apply of side effect builtin. " "Returning MayHaveSideEffects.\n"); return MemoryBehavior::MayHaveSideEffects; } default: // If we do not have a special case, just return the generic memory // behavior of Inst. return Inst->getMemoryBehavior(); } } <|endoftext|>
<commit_before>/* nsjail ----------------------------------------- Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "nsjail.h" #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/time.h> #include <termios.h> #include <unistd.h> #include <algorithm> #include <cerrno> #include <memory> #include <vector> #include "cmdline.h" #include "logs.h" #include "macros.h" #include "net.h" #include "sandbox.h" #include "subproc.h" #include "util.h" namespace nsjail { static __thread int sigFatal = 0; static __thread bool showProc = false; static void sigHandler(int sig) { if (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) { return; } if (sig == SIGUSR1 || sig == SIGQUIT) { showProc = true; return; } sigFatal = sig; } static bool setSigHandler(int sig) { LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig); sigset_t smask; sigemptyset(&smask); struct sigaction sa; sa.sa_handler = sigHandler; sa.sa_mask = smask; sa.sa_flags = 0; sa.sa_restorer = NULL; if (sig == SIGTTIN || sig == SIGTTOU) { sa.sa_handler = SIG_IGN; } if (sigaction(sig, &sa, NULL) == -1) { PLOG_E("sigaction(%d)", sig); return false; } return true; } static bool setSigHandlers(void) { for (const auto& i : nssigs) { if (!setSigHandler(i)) { return false; } } return true; } static bool setTimer(nsjconf_t* nsjconf) { if (nsjconf->mode == MODE_STANDALONE_EXECVE) { return true; } struct itimerval it = { .it_interval = { .tv_sec = 1, .tv_usec = 0, }, .it_value = { .tv_sec = 1, .tv_usec = 0, }, }; if (setitimer(ITIMER_REAL, &it, NULL) == -1) { PLOG_E("setitimer(ITIMER_REAL)"); return false; } return true; } static bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) { std::vector<struct pollfd> fds; fds.reserve(nsjconf->pipes.size() * 3 + 1); for (const auto& p : nsjconf->pipes) { fds.push_back({ .fd = p.sock_fd, .events = POLLIN | POLLOUT, .revents = 0, }); fds.push_back({ .fd = p.pipe_in, .events = POLLOUT, .revents = 0, }); fds.push_back({ .fd = p.pipe_out, .events = POLLIN, .revents = 0, }); } fds.push_back({ .fd = listenfd, .events = POLLIN, .revents = 0, }); LOG_D("Waiting for fd activity"); while (poll(fds.data(), fds.size(), -1) > 0) { if (sigFatal > 0 || showProc) { return false; } if (fds.back().revents != 0) { LOG_D("New connection ready"); return true; } bool cleanup = false; for (size_t i = 0; i < fds.size() - 1; ++i) { if (fds[i].revents & POLLIN) { fds[i].events &= ~POLLIN; } if (fds[i].revents & POLLOUT) { fds[i].events &= ~POLLOUT; } } for (size_t i = 0; i < fds.size() - 3; i += 3) { const size_t pipe_no = i / 3; int in, out; const char* direction; bool closed = false; std::tuple<int, int, const char*> direction_map[] = { {i, i + 1, "in"}, {i + 2, i, "out"}}; for (const auto& entry : direction_map) { std::tie(in, out, direction) = entry; bool in_ready = (fds[in].events & POLLIN) == 0 || (fds[in].revents & POLLIN) == POLLIN; bool out_ready = (fds[out].events & POLLOUT) == 0 || (fds[out].revents & POLLOUT) == POLLOUT; if (in_ready && out_ready) { LOG_D("#%ld piping data %s", pipe_no, direction); ssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd, nullptr, 4096, SPLICE_F_NONBLOCK); if (rv == -1 && errno != EAGAIN) { PLOG_E("splice fd pair #%ld {%d, %d}\n", pipe_no, fds[in].fd, fds[out].fd); } if (rv == 0) { closed = true; } fds[in].events |= POLLIN; fds[out].events |= POLLOUT; } if ((fds[in].revents & (POLLERR | POLLHUP)) != 0 || (fds[out].revents & (POLLERR | POLLHUP)) != 0) { closed = true; } } if (closed) { LOG_D("#%ld connection closed", pipe_no); cleanup = true; close(nsjconf->pipes[pipe_no].sock_fd); close(nsjconf->pipes[pipe_no].pipe_in); close(nsjconf->pipes[pipe_no].pipe_out); nsjconf->pipes[pipe_no] = {}; } } if (cleanup) { break; } } nsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}), nsjconf->pipes.end()); return false; } static int listenMode(nsjconf_t* nsjconf) { int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port); if (listenfd == -1) { return EXIT_FAILURE; } for (;;) { if (sigFatal > 0) { subproc::killAndReapAll(nsjconf); logs::logStop(sigFatal); close(listenfd); return EXIT_SUCCESS; } if (showProc) { showProc = false; subproc::displayProc(nsjconf); } if (pipeTraffic(nsjconf, listenfd)) { int connfd = net::acceptConn(listenfd); if (connfd >= 0) { int in[2]; int out[2]; if (pipe(in) != 0 || pipe(out) != 0) { PLOG_E("pipe"); continue; } nsjconf->pipes.push_back({ .sock_fd = connfd, .pipe_in = in[1], .pipe_out = out[0], }); subproc::runChild(nsjconf, connfd, in[0], out[1], out[1]); close(in[0]); close(out[1]); } } subproc::reapProc(nsjconf); } } static int standaloneMode(nsjconf_t* nsjconf) { for (;;) { if (!subproc::runChild( nsjconf, /* netfd= */ -1, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO)) { LOG_E("Couldn't launch the child process"); return 0xff; } for (;;) { int child_status = subproc::reapProc(nsjconf); if (subproc::countProc(nsjconf) == 0) { if (nsjconf->mode == MODE_STANDALONE_ONCE) { return child_status; } break; } if (showProc) { showProc = false; subproc::displayProc(nsjconf); } if (sigFatal > 0) { subproc::killAndReapAll(nsjconf); logs::logStop(sigFatal); return (128 + sigFatal); } pause(); } } // not reached } std::unique_ptr<struct termios> getTC(int fd) { std::unique_ptr<struct termios> trm(new struct termios); if (ioctl(fd, TCGETS, trm.get()) == -1) { PLOG_D("ioctl(fd=%d, TCGETS) failed", fd); return nullptr; } LOG_D("Saved the current state of the TTY"); return trm; } void setTC(int fd, const struct termios* trm) { if (!trm) { return; } if (ioctl(fd, TCSETS, trm) == -1) { PLOG_W("ioctl(fd=%d, TCSETS) failed", fd); return; } if (tcflush(fd, TCIFLUSH) == -1) { PLOG_W("tcflush(fd=%d, TCIFLUSH) failed", fd); return; } } } // namespace nsjail int main(int argc, char* argv[]) { std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv); std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO); if (!nsjconf) { LOG_F("Couldn't parse cmdline options"); } if (nsjconf->daemonize && (daemon(0, 0) == -1)) { PLOG_F("daemon"); } cmdline::logParams(nsjconf.get()); if (!nsjail::setSigHandlers()) { LOG_F("nsjail::setSigHandlers() failed"); } if (!nsjail::setTimer(nsjconf.get())) { LOG_F("nsjail::setTimer() failed"); } if (!sandbox::preparePolicy(nsjconf.get())) { LOG_F("Couldn't prepare sandboxing policy"); } int ret = 0; if (nsjconf->mode == MODE_LISTEN_TCP) { ret = nsjail::listenMode(nsjconf.get()); } else { ret = nsjail::standaloneMode(nsjconf.get()); } sandbox::closePolicy(nsjconf.get()); /* Try to restore the underlying console's params in case some program has changed it */ if (!nsjconf->daemonize) { nsjail::setTC(STDIN_FILENO, trm.get()); } LOG_D("Returning with %d", ret); return ret; } <commit_msg>Fix format specifier for size_t<commit_after>/* nsjail ----------------------------------------- Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "nsjail.h" #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/time.h> #include <termios.h> #include <unistd.h> #include <algorithm> #include <cerrno> #include <memory> #include <vector> #include "cmdline.h" #include "logs.h" #include "macros.h" #include "net.h" #include "sandbox.h" #include "subproc.h" #include "util.h" namespace nsjail { static __thread int sigFatal = 0; static __thread bool showProc = false; static void sigHandler(int sig) { if (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) { return; } if (sig == SIGUSR1 || sig == SIGQUIT) { showProc = true; return; } sigFatal = sig; } static bool setSigHandler(int sig) { LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig); sigset_t smask; sigemptyset(&smask); struct sigaction sa; sa.sa_handler = sigHandler; sa.sa_mask = smask; sa.sa_flags = 0; sa.sa_restorer = NULL; if (sig == SIGTTIN || sig == SIGTTOU) { sa.sa_handler = SIG_IGN; } if (sigaction(sig, &sa, NULL) == -1) { PLOG_E("sigaction(%d)", sig); return false; } return true; } static bool setSigHandlers(void) { for (const auto& i : nssigs) { if (!setSigHandler(i)) { return false; } } return true; } static bool setTimer(nsjconf_t* nsjconf) { if (nsjconf->mode == MODE_STANDALONE_EXECVE) { return true; } struct itimerval it = { .it_interval = { .tv_sec = 1, .tv_usec = 0, }, .it_value = { .tv_sec = 1, .tv_usec = 0, }, }; if (setitimer(ITIMER_REAL, &it, NULL) == -1) { PLOG_E("setitimer(ITIMER_REAL)"); return false; } return true; } static bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) { std::vector<struct pollfd> fds; fds.reserve(nsjconf->pipes.size() * 3 + 1); for (const auto& p : nsjconf->pipes) { fds.push_back({ .fd = p.sock_fd, .events = POLLIN | POLLOUT, .revents = 0, }); fds.push_back({ .fd = p.pipe_in, .events = POLLOUT, .revents = 0, }); fds.push_back({ .fd = p.pipe_out, .events = POLLIN, .revents = 0, }); } fds.push_back({ .fd = listenfd, .events = POLLIN, .revents = 0, }); LOG_D("Waiting for fd activity"); while (poll(fds.data(), fds.size(), -1) > 0) { if (sigFatal > 0 || showProc) { return false; } if (fds.back().revents != 0) { LOG_D("New connection ready"); return true; } bool cleanup = false; for (size_t i = 0; i < fds.size() - 1; ++i) { if (fds[i].revents & POLLIN) { fds[i].events &= ~POLLIN; } if (fds[i].revents & POLLOUT) { fds[i].events &= ~POLLOUT; } } for (size_t i = 0; i < fds.size() - 3; i += 3) { const size_t pipe_no = i / 3; int in, out; const char* direction; bool closed = false; std::tuple<int, int, const char*> direction_map[] = { {i, i + 1, "in"}, {i + 2, i, "out"}}; for (const auto& entry : direction_map) { std::tie(in, out, direction) = entry; bool in_ready = (fds[in].events & POLLIN) == 0 || (fds[in].revents & POLLIN) == POLLIN; bool out_ready = (fds[out].events & POLLOUT) == 0 || (fds[out].revents & POLLOUT) == POLLOUT; if (in_ready && out_ready) { LOG_D("#%zu piping data %s", pipe_no, direction); ssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd, nullptr, 4096, SPLICE_F_NONBLOCK); if (rv == -1 && errno != EAGAIN) { PLOG_E("splice fd pair #%zu {%d, %d}\n", pipe_no, fds[in].fd, fds[out].fd); } if (rv == 0) { closed = true; } fds[in].events |= POLLIN; fds[out].events |= POLLOUT; } if ((fds[in].revents & (POLLERR | POLLHUP)) != 0 || (fds[out].revents & (POLLERR | POLLHUP)) != 0) { closed = true; } } if (closed) { LOG_D("#%zu connection closed", pipe_no); cleanup = true; close(nsjconf->pipes[pipe_no].sock_fd); close(nsjconf->pipes[pipe_no].pipe_in); close(nsjconf->pipes[pipe_no].pipe_out); nsjconf->pipes[pipe_no] = {}; } } if (cleanup) { break; } } nsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}), nsjconf->pipes.end()); return false; } static int listenMode(nsjconf_t* nsjconf) { int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port); if (listenfd == -1) { return EXIT_FAILURE; } for (;;) { if (sigFatal > 0) { subproc::killAndReapAll(nsjconf); logs::logStop(sigFatal); close(listenfd); return EXIT_SUCCESS; } if (showProc) { showProc = false; subproc::displayProc(nsjconf); } if (pipeTraffic(nsjconf, listenfd)) { int connfd = net::acceptConn(listenfd); if (connfd >= 0) { int in[2]; int out[2]; if (pipe(in) != 0 || pipe(out) != 0) { PLOG_E("pipe"); continue; } nsjconf->pipes.push_back({ .sock_fd = connfd, .pipe_in = in[1], .pipe_out = out[0], }); subproc::runChild(nsjconf, connfd, in[0], out[1], out[1]); close(in[0]); close(out[1]); } } subproc::reapProc(nsjconf); } } static int standaloneMode(nsjconf_t* nsjconf) { for (;;) { if (!subproc::runChild( nsjconf, /* netfd= */ -1, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO)) { LOG_E("Couldn't launch the child process"); return 0xff; } for (;;) { int child_status = subproc::reapProc(nsjconf); if (subproc::countProc(nsjconf) == 0) { if (nsjconf->mode == MODE_STANDALONE_ONCE) { return child_status; } break; } if (showProc) { showProc = false; subproc::displayProc(nsjconf); } if (sigFatal > 0) { subproc::killAndReapAll(nsjconf); logs::logStop(sigFatal); return (128 + sigFatal); } pause(); } } // not reached } std::unique_ptr<struct termios> getTC(int fd) { std::unique_ptr<struct termios> trm(new struct termios); if (ioctl(fd, TCGETS, trm.get()) == -1) { PLOG_D("ioctl(fd=%d, TCGETS) failed", fd); return nullptr; } LOG_D("Saved the current state of the TTY"); return trm; } void setTC(int fd, const struct termios* trm) { if (!trm) { return; } if (ioctl(fd, TCSETS, trm) == -1) { PLOG_W("ioctl(fd=%d, TCSETS) failed", fd); return; } if (tcflush(fd, TCIFLUSH) == -1) { PLOG_W("tcflush(fd=%d, TCIFLUSH) failed", fd); return; } } } // namespace nsjail int main(int argc, char* argv[]) { std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv); std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO); if (!nsjconf) { LOG_F("Couldn't parse cmdline options"); } if (nsjconf->daemonize && (daemon(0, 0) == -1)) { PLOG_F("daemon"); } cmdline::logParams(nsjconf.get()); if (!nsjail::setSigHandlers()) { LOG_F("nsjail::setSigHandlers() failed"); } if (!nsjail::setTimer(nsjconf.get())) { LOG_F("nsjail::setTimer() failed"); } if (!sandbox::preparePolicy(nsjconf.get())) { LOG_F("Couldn't prepare sandboxing policy"); } int ret = 0; if (nsjconf->mode == MODE_LISTEN_TCP) { ret = nsjail::listenMode(nsjconf.get()); } else { ret = nsjail::standaloneMode(nsjconf.get()); } sandbox::closePolicy(nsjconf.get()); /* Try to restore the underlying console's params in case some program has changed it */ if (!nsjconf->daemonize) { nsjail::setTC(STDIN_FILENO, trm.get()); } LOG_D("Returning with %d", ret); return ret; } <|endoftext|>
<commit_before>#include "module.h" // PUT #include <specialized/osdetect.h> #include <cxxutils/posix_helpers.h> #if defined(__linux__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(2,2,0) // Linux 2.2+ // See also: https://www.systutorials.com/docs/linux/man/2-create_module/ // See also: https://www.systutorials.com/docs/linux/man/2-query_module/ // Linux # include <linux/module.h> # include <sys/mman.h> # include <sys/syscall.h> # if KERNEL_VERSION_CODE >= KERNEL_VERSION(2,6,0) struct module; struct exception_table_entry; struct module_ref { module* dep; /* "parent" pointer */ module* ref; /* "child" pointer */ module_ref* next_ref; }; struct module_symbol { unsigned long value; const char *name; }; struct module { unsigned long size_of_struct; module* next; const char* name; unsigned long size; long usecount; unsigned long flags; unsigned int nsyms; unsigned int ndeps; module_symbol* syms; module_ref* deps; module_ref* refs; int (*init)(void); void (*cleanup)(void); const exception_table_entry* ex_table_start; const exception_table_entry* ex_table_end; # ifdef __alpha__ unsigned long gp; # endif }; # endif inline int init_module26(void* module_image, unsigned long len, const char* param_values) noexcept { return int(::syscall(SYS_init_module, module_image, len, param_values)); } inline int delete_module26(const char* name, int flags) noexcept { return int(::syscall(SYS_delete_module, name, flags)); } inline int init_module22(const char* name, module *image) noexcept { return int(::syscall(SYS_init_module, name, image)); } inline int delete_module22(const char* name) noexcept { return int(::syscall(SYS_delete_module, name)); } inline int query_module(const char* name, int which, void* buf, size_t bufsize, size_t* ret) noexcept { return int(::syscall(SYS_query_module, name, which, buf, bufsize, ret)); } inline caddr_t create_module(const char *name, size_t size) noexcept { return caddr_t(::syscall(SYS_create_module, name, size)); } inline bool is_kernel26(void) noexcept { posix::error_t oldval = errno; query_module(NULL, 0, NULL, 0, NULL); bool rval = errno == ENOSYS; errno = oldval; return rval; } int load_module(const std::string& filename, const std::string& module_arguments) noexcept { int rval = posix::error_response; posix::fd_t fd = posix::open(filename.c_str(), O_RDONLY | O_CLOEXEC); if(fd != posix::error_response) { stat state; rval = ::fstat(fd, &state); if(rval == posix::success_response) { void* mem = ::mmap(0, state.st_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0); if(mem != NULL) { if(is_kernel26()) rval = init_module26(mem, state.st_size, module_arguments.c_str()); else { const char* name; module* image; rval = init_module22(name, image); } ::munmap(mem, state.st_size); } } posix::close(fd); } return rval; } int unload_module(const std::string& name) noexcept { if(is_kernel26()) return delete_module26(name.c_str(), O_NONBLOCK); else return delete_module22(name.c_str()); } #elif defined(__aix__) // IBM AIX // https://www.ibm.com/developerworks/aix/library/au-kernelext.html # error No kernel module operations code exists in PUT for IBM AIX! Please submit a patch! #elif defined(__darwin__) // Darwin // kextload and kextunload # error No kernel module operations code exists in PUT for Darwin! Please submit a patch! #elif defined(__solaris__) // Solaris / OpenSolaris / OpenIndiana / illumos # error No kernel module operations code exists in PUT for Solaris! Please submit a patch! #elif defined(__DragonFly__) /* DragonFly BSD */ || \ (defined(__FreeBSD__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(3,0,0)) /* FreeBSD 3+ */ // POSIX++ # include <cstring> // FreeBSD / DragonFly BSD # include <sys/linker.h> # include <kenv.h> template<class T> constexpr const T& max(const T& a, const T& b) { return (a < b) ? b : a; } int load_module(const std::string& filename, const std::string& module_arguments) noexcept { int fileid = kldload(filename.c_str()); if(fileid == posix::error_response && !module_arguments.empty()) { char key[KENV_MNAMELEN], value[KENV_MVALLEN]; const char* prev = module_arguments.c_str(); const char* pos = std::strtok(prev, "= "); while(pos != NULL && *pos == '=') // if NOT at end AND found '=' instead of ' ' { std::memset(key , 0, sizeof(key )); // clear key std::memset(value, 0, sizeof(value)); // clear value std::memcpy(key, pos, min(posix::size_t(pos - prev), KENV_MNAMELEN)); // copy key prev = pos; pos = std::strtok(NULL, " "); // find next ' ' if(pos == NULL) // found end of string instead std::memcpy(value, prev, min(std::strlen(prev), KENV_MVALLEN)); // copy value else if(*pos == ' ') // found ' ' std::memcpy(value, prev, min(posix::size_t(pos - prev), KENV_MVALLEN)); // copy value kenv(KENV_SET, key, value, std::strlen(value) + 1); // set key/value pair } if(pos != NULL && *pos == ' ') return posix::error(std::errc::invalid_argument); return posix::success_response; } return posix::error_response; } int unload_module(const std::string& name) noexcept { int fileid = kldfind(name.c_str()); if(fileid == posix::error_response) return posix::error_response; return kldunload(fileid); } #elif defined(__OpenBSD__) // https://man.openbsd.org/OpenBSD-5.4/lkm.4 // https://github.com/ekouekam/openbsd-src/tree/master/sbin/modload // ioctl on /dev/lkm # error No kernel module operations code exists in PUT for OpenBSD! Please submit a patch! #elif defined(__NetBSD__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(5,0,0) // NetBSD 5+ // See also: http://netbsd.gw.com/cgi-bin/man-cgi?modctl++NetBSD-6.0 // NetBSD # include <sys/module.h> int load_module(const std::string& filename, const std::string& module_arguments) noexcept { modctl_load_t mod; mod.ml_filename = filename.c_str(); if(module_arguments.empty()) { mod.ml_flags = MODCTL_NO_PROP; mod.ml_props = NULL; mod.ml_propslen = 0; } else { mod.ml_flags = 0; mod.ml_props = module_arguments.c_str(); mod.ml_propslen = module_arguments.size(); } return ::modctl(MODCTL_LOAD, &mod); } int unload_module(const std::string& name) noexcept { return ::modctl(MODCTL_UNLOAD, name.c_str()); } #else # pragma message("Loadable Kernel Modules are not supported on this platform.") int load_module(const std::string&, const std::string&) noexcept { return posix::error(ENOSYS); } int unload_module(const std::string&) noexcept { return posix::error(ENOSYS); } #endif <commit_msg>combine errors, change error code<commit_after>#include "module.h" // PUT #include <specialized/osdetect.h> #include <cxxutils/posix_helpers.h> #if defined(__linux__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(2,2,0) // Linux 2.2+ // See also: https://www.systutorials.com/docs/linux/man/2-create_module/ // See also: https://www.systutorials.com/docs/linux/man/2-query_module/ // Linux # include <linux/module.h> # include <sys/mman.h> # include <sys/syscall.h> # include <sys/stat.h> # if KERNEL_VERSION_CODE >= KERNEL_VERSION(2,6,0) struct module; struct exception_table_entry; struct module_ref { module* dep; /* "parent" pointer */ module* ref; /* "child" pointer */ module_ref* next_ref; }; struct module_symbol { unsigned long value; const char *name; }; struct module { unsigned long size_of_struct; module* next; const char* name; unsigned long size; long usecount; unsigned long flags; unsigned int nsyms; unsigned int ndeps; module_symbol* syms; module_ref* deps; module_ref* refs; int (*init)(void); void (*cleanup)(void); const exception_table_entry* ex_table_start; const exception_table_entry* ex_table_end; # ifdef __alpha__ unsigned long gp; # endif }; # endif inline int init_module26(void* module_image, unsigned long len, const char* param_values) noexcept { return int(::syscall(SYS_init_module, module_image, len, param_values)); } inline int delete_module26(const char* name, int flags) noexcept { return int(::syscall(SYS_delete_module, name, flags)); } inline int init_module22(const char* name, module *image) noexcept { return int(::syscall(SYS_init_module, name, image)); } inline int delete_module22(const char* name) noexcept { return int(::syscall(SYS_delete_module, name)); } inline int query_module(const char* name, int which, void* buf, size_t bufsize, size_t* ret) noexcept { return int(::syscall(SYS_query_module, name, which, buf, bufsize, ret)); } inline caddr_t create_module(const char *name, size_t size) noexcept { return caddr_t(::syscall(SYS_create_module, name, size)); } inline bool is_kernel26(void) noexcept { posix::error_t oldval = errno; query_module(NULL, 0, NULL, 0, NULL); bool rval = errno == ENOSYS; errno = oldval; return rval; } int load_module(const std::string& filename, const std::string& module_arguments) noexcept { int rval = posix::error_response; posix::fd_t fd = posix::open(filename.c_str(), O_RDONLY | O_CLOEXEC); if(fd != posix::error_response) { stat state; rval = ::fstat(fd, &state); if(rval == posix::success_response) { void* mem = ::mmap(0, state.st_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0); if(mem != NULL) { if(is_kernel26()) rval = init_module26(mem, state.st_size, module_arguments.c_str()); else if (false) // 2.2+ loader code is far from complete { const char* name; module* image; rval = init_module22(name, image); } else rval = posix::error(EOPNOTSUPP); // not implemented! ::munmap(mem, state.st_size); } } posix::close(fd); } return rval; } int unload_module(const std::string& name) noexcept { if(is_kernel26()) return delete_module26(name.c_str(), O_NONBLOCK); else return delete_module22(name.c_str()); } #elif defined(__aix__) // IBM AIX // https://www.ibm.com/developerworks/aix/library/au-kernelext.html # error No kernel module operations code exists in PUT for IBM AIX! Please submit a patch! #elif defined(__solaris__) // Solaris / OpenSolaris / OpenIndiana / illumos # error No kernel module operations code exists in PUT for Solaris! Please submit a patch! #elif defined(__DragonFly__) /* DragonFly BSD */ || \ (defined(__FreeBSD__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(3,0,0)) /* FreeBSD 3+ */ // POSIX++ # include <cstring> // FreeBSD / DragonFly BSD # include <sys/linker.h> # include <kenv.h> template<class T> constexpr const T& max(const T& a, const T& b) { return (a < b) ? b : a; } int load_module(const std::string& filename, const std::string& module_arguments) noexcept { int fileid = kldload(filename.c_str()); if(fileid == posix::error_response && !module_arguments.empty()) { char key[KENV_MNAMELEN], value[KENV_MVALLEN]; const char* prev = module_arguments.c_str(); const char* pos = std::strtok(prev, "= "); while(pos != NULL && *pos == '=') // if NOT at end AND found '=' instead of ' ' { std::memset(key , 0, sizeof(key )); // clear key std::memset(value, 0, sizeof(value)); // clear value std::memcpy(key, pos, min(posix::size_t(pos - prev), KENV_MNAMELEN)); // copy key prev = pos; pos = std::strtok(NULL, " "); // find next ' ' if(pos == NULL) // found end of string instead std::memcpy(value, prev, min(std::strlen(prev), KENV_MVALLEN)); // copy value else if(*pos == ' ') // found ' ' std::memcpy(value, prev, min(posix::size_t(pos - prev), KENV_MVALLEN)); // copy value kenv(KENV_SET, key, value, std::strlen(value) + 1); // set key/value pair } if(pos != NULL && *pos == ' ') return posix::error(std::errc::invalid_argument); return posix::success_response; } return posix::error_response; } int unload_module(const std::string& name) noexcept { int fileid = kldfind(name.c_str()); if(fileid == posix::error_response) return posix::error_response; return kldunload(fileid); } #elif defined(__NetBSD__) && KERNEL_VERSION_CODE >= KERNEL_VERSION(5,0,0) // NetBSD 5+ // See also: http://netbsd.gw.com/cgi-bin/man-cgi?modctl++NetBSD-6.0 // NetBSD # include <sys/module.h> int load_module(const std::string& filename, const std::string& module_arguments) noexcept { modctl_load_t mod; mod.ml_filename = filename.c_str(); if(module_arguments.empty()) { mod.ml_flags = MODCTL_NO_PROP; mod.ml_props = NULL; mod.ml_propslen = 0; } else { mod.ml_flags = 0; mod.ml_props = module_arguments.c_str(); mod.ml_propslen = module_arguments.size(); } return ::modctl(MODCTL_LOAD, &mod); } int unload_module(const std::string& name) noexcept { return ::modctl(MODCTL_UNLOAD, name.c_str()); } #else # if defined(__darwin__) /* Darwin */ || \ defined(__OpenBSD__) /* OpenBSD */ || \ defined(__FreeBSD__) /* legacy FreeBSD */ || \ defined(__NetBSD__) /* legacy NetBSD */ // Darwin: kmodload and kmodunload (AKA kextload and kextunload) // OpenBSD: modload and modunload // https://man.openbsd.org/OpenBSD-5.4/lkm.4 // https://github.com/ekouekam/openbsd-src/tree/master/sbin/modload // OpenBSD ioctl on /dev/lkm # pragma message("No kernel module ELF loader implemented! Please submit a patch!") # pragma message("Loadable Kernel Module support is not implemented on this platform.") # else # pragma message("Loadable Kernel Modules are not supported on this platform.") # endif int load_module(const std::string&, const std::string&) noexcept { return posix::error(EOPNOTSUPP); } int unload_module(const std::string&) noexcept { return posix::error(EOPNOTSUPP); } #endif <|endoftext|>
<commit_before>//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements the info about Mips target spec. // //===----------------------------------------------------------------------===// #include "MipsTargetMachine.h" #include "Mips.h" #include "MipsFrameLowering.h" #include "MipsInstrInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/PassManager.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; extern "C" void LLVMInitializeMipsTarget() { // Register the target. RegisterTargetMachine<MipsebTargetMachine> X(TheMipsTarget); RegisterTargetMachine<MipselTargetMachine> Y(TheMipselTarget); RegisterTargetMachine<MipsebTargetMachine> A(TheMips64Target); RegisterTargetMachine<MipselTargetMachine> B(TheMips64elTarget); } // DataLayout --> Big-endian, 32-bit pointer/ABI/alignment // The stack is always 8 byte aligned // On function prologue, the stack is created by decrementing // its pointer. Once decremented, all references are done with positive // offset from the stack/frame pointer, using StackGrowsUp enables // an easier handling. // Using CodeModel::Large enables different CALL behavior. MipsTargetMachine:: MipsTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool isLittle) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, isLittle, RM), DL(isLittle ? (Subtarget.isABI_N64() ? "e-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32" : "e-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32") : (Subtarget.isABI_N64() ? "E-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32" : "E-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32")), InstrInfo(MipsInstrInfo::create(*this)), FrameLowering(MipsFrameLowering::create(*this, Subtarget)), TLInfo(*this), TSInfo(*this), JITInfo(), STTI(&TLInfo), VTTI(&TLInfo) { } void MipsebTargetMachine::anchor() { } MipsebTargetMachine:: MipsebTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} void MipselTargetMachine::anchor() { } MipselTargetMachine:: MipselTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} namespace { /// Mips Code Generator Pass Configuration Options. class MipsPassConfig : public TargetPassConfig { public: MipsPassConfig(MipsTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} MipsTargetMachine &getMipsTargetMachine() const { return getTM<MipsTargetMachine>(); } const MipsSubtarget &getMipsSubtarget() const { return *getMipsTargetMachine().getSubtargetImpl(); } virtual bool addInstSelector(); virtual bool addPreEmitPass(); }; } // namespace TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) { return new MipsPassConfig(this, PM); } // Install an instruction selector pass using // the ISelDag to gen Mips code. bool MipsPassConfig::addInstSelector() { addPass(createMipsISelDag(getMipsTargetMachine())); return false; } // Implemented by targets that want to run passes immediately before // machine code is emitted. return true if -print-machineinstrs should // print out the code after the passes. bool MipsPassConfig::addPreEmitPass() { MipsTargetMachine &TM = getMipsTargetMachine(); addPass(createMipsDelaySlotFillerPass(TM)); // NOTE: long branch has not been implemented for mips16. if (TM.getSubtarget<MipsSubtarget>().hasStandardEncoding()) addPass(createMipsLongBranchPass(TM)); return true; } bool MipsTargetMachine::addCodeEmitter(PassManagerBase &PM, JITCodeEmitter &JCE) { // Machine code emitter pass for Mips. PM.add(createMipsJITCodeEmitterPass(*this, JCE)); return false; } <commit_msg>[mips] Fix data layout string. Add 64 to the list of native integer widths and add stack alignment information.<commit_after>//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements the info about Mips target spec. // //===----------------------------------------------------------------------===// #include "MipsTargetMachine.h" #include "Mips.h" #include "MipsFrameLowering.h" #include "MipsInstrInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/PassManager.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; extern "C" void LLVMInitializeMipsTarget() { // Register the target. RegisterTargetMachine<MipsebTargetMachine> X(TheMipsTarget); RegisterTargetMachine<MipselTargetMachine> Y(TheMipselTarget); RegisterTargetMachine<MipsebTargetMachine> A(TheMips64Target); RegisterTargetMachine<MipselTargetMachine> B(TheMips64elTarget); } // DataLayout --> Big-endian, 32-bit pointer/ABI/alignment // The stack is always 8 byte aligned // On function prologue, the stack is created by decrementing // its pointer. Once decremented, all references are done with positive // offset from the stack/frame pointer, using StackGrowsUp enables // an easier handling. // Using CodeModel::Large enables different CALL behavior. MipsTargetMachine:: MipsTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool isLittle) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, isLittle, RM), DL(isLittle ? (Subtarget.isABI_N64() ? "e-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-" "n32:64-S128" : "e-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32-S64") : (Subtarget.isABI_N64() ? "E-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-" "n32:64-S128" : "E-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32-S64")), InstrInfo(MipsInstrInfo::create(*this)), FrameLowering(MipsFrameLowering::create(*this, Subtarget)), TLInfo(*this), TSInfo(*this), JITInfo(), STTI(&TLInfo), VTTI(&TLInfo) { } void MipsebTargetMachine::anchor() { } MipsebTargetMachine:: MipsebTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} void MipselTargetMachine::anchor() { } MipselTargetMachine:: MipselTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} namespace { /// Mips Code Generator Pass Configuration Options. class MipsPassConfig : public TargetPassConfig { public: MipsPassConfig(MipsTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} MipsTargetMachine &getMipsTargetMachine() const { return getTM<MipsTargetMachine>(); } const MipsSubtarget &getMipsSubtarget() const { return *getMipsTargetMachine().getSubtargetImpl(); } virtual bool addInstSelector(); virtual bool addPreEmitPass(); }; } // namespace TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) { return new MipsPassConfig(this, PM); } // Install an instruction selector pass using // the ISelDag to gen Mips code. bool MipsPassConfig::addInstSelector() { addPass(createMipsISelDag(getMipsTargetMachine())); return false; } // Implemented by targets that want to run passes immediately before // machine code is emitted. return true if -print-machineinstrs should // print out the code after the passes. bool MipsPassConfig::addPreEmitPass() { MipsTargetMachine &TM = getMipsTargetMachine(); addPass(createMipsDelaySlotFillerPass(TM)); // NOTE: long branch has not been implemented for mips16. if (TM.getSubtarget<MipsSubtarget>().hasStandardEncoding()) addPass(createMipsLongBranchPass(TM)); return true; } bool MipsTargetMachine::addCodeEmitter(PassManagerBase &PM, JITCodeEmitter &JCE) { // Machine code emitter pass for Mips. PM.add(createMipsJITCodeEmitterPass(*this, JCE)); return false; } <|endoftext|>
<commit_before>/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ArduinoSimpleLogging.h> #include <PubSubClient.h> #include "MqttClient.h" class PayloadString : public String { public: PayloadString(const uint8_t *data, unsigned int length) : String() { if (reserve(length)) { memcpy(buffer, data, length); len = length; } } }; MqttClient::MqttClient(const Settings &settings, WiFiClient &client) : settings(settings), mqttClient(new PubSubClient(client)), lastConnectAttempt(0) {} MqttClient::~MqttClient() { if (mqttClient) { mqttClient->disconnect(); delete mqttClient; } } void MqttClient::begin() { using namespace std::placeholders; mqttClient->setServer(settings.mqttBroker.c_str(), settings.mqttBrokerPort); mqttClient->setCallback(std::bind(&MqttClient::onMessage, this, _1, _2, _3)); reconnect(); } static String stateMessage(const bool online) { return String(F("{\"chipId\":\"")) + String(ESP.getChipId(), HEX) + String(F( "\",\"firmware\":\"" QUOTE(FIRMWARE_VERSION) "\",\"state\":\"")) + String(online ? F("online") : F("offline")) + String(F("\"}")); } static String stateTopic(const String &devName) { return devName + F("/state"); } bool MqttClient::connect() { if (0 == settings.mqttUser.length()) { return mqttClient->connect(settings.deviceName.c_str(), stateTopic(settings.deviceName).c_str(), 0, true, stateMessage(false).c_str()); } else { return mqttClient->connect( settings.deviceName.c_str(), settings.mqttUser.c_str(), settings.mqttPassword.c_str(), stateTopic(settings.deviceName).c_str(), 0, true, stateMessage(false).c_str()); } } void MqttClient::reconnect() { if (lastConnectAttempt > 0 && (millis() - lastConnectAttempt) < MQTT_CONNECTION_ATTEMPT_DELAY) { return; } if (!mqttClient->connected()) { Logger.debug.println(F("Try to (re)connect to MQTT broker")); if (connect()) { Logger.info.println(F("MQTT connected.")); if (subsrcibe()) { mqttClient->publish(stateTopic(settings.deviceName).c_str(), stateMessage(true).c_str(), true); Logger.info.println(F("MQTT subscribed.")); } else { Logger.error.println(F("MQTT subsrcibe failed!")); } } else { Logger.error.println(F("MQTT connect failed!")); } } lastConnectAttempt = millis(); } bool MqttClient::subsrcibe() { Logger.debug.print(F("MQTT subscribe to topic: ")); Logger.debug.println((settings.mqttSendTopic + "+")); return mqttClient->subscribe((settings.mqttSendTopic + "+").c_str()); } void MqttClient::loop() { reconnect(); mqttClient->loop(); } void MqttClient::onMessage(char *topic, uint8_t *payload, unsigned int length) { PayloadString strPayload(payload, length); String strTopic(topic); Logger.debug.print(F("New MQTT message: ")); Logger.debug.print(strTopic); Logger.debug.print(F(" .. ")); Logger.debug.println(strPayload); if (strTopic.startsWith(settings.mqttSendTopic)) { if (onSendCallback) { onSendCallback(String(topic + settings.mqttSendTopic.length()), strPayload); } } } void MqttClient::registerRfDataHandler(const MqttClient::HandlerCallback &cb) { onSendCallback = cb; } void MqttClient::publishCode(const String &protocol, const String &payload) { Logger.debug.print(F("Publish MQTT message: ")); Logger.debug.print(settings.mqttReceiveTopic + protocol); Logger.debug.print(F(" retain=")); Logger.debug.print(settings.mqttRetain); Logger.debug.print(F(" .. ")); Logger.debug.println(payload); mqttClient->publish((settings.mqttReceiveTopic + protocol).c_str(), payload.c_str(), settings.mqttRetain); } <commit_msg>MqttClient: build topic only once<commit_after>/** MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight Project home: https://github.com/puuu/MQTT433gateway/ The MIT License (MIT) Copyright (c) 2017 Jan Losinski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ArduinoSimpleLogging.h> #include <PubSubClient.h> #include "MqttClient.h" class PayloadString : public String { public: PayloadString(const uint8_t *data, unsigned int length) : String() { if (reserve(length)) { memcpy(buffer, data, length); len = length; } } }; MqttClient::MqttClient(const Settings &settings, WiFiClient &client) : settings(settings), mqttClient(new PubSubClient(client)), lastConnectAttempt(0) {} MqttClient::~MqttClient() { if (mqttClient) { mqttClient->disconnect(); delete mqttClient; } } void MqttClient::begin() { using namespace std::placeholders; mqttClient->setServer(settings.mqttBroker.c_str(), settings.mqttBrokerPort); mqttClient->setCallback(std::bind(&MqttClient::onMessage, this, _1, _2, _3)); reconnect(); } static String stateMessage(const bool online) { return String(F("{\"chipId\":\"")) + String(ESP.getChipId(), HEX) + String(F( "\",\"firmware\":\"" QUOTE(FIRMWARE_VERSION) "\",\"state\":\"")) + String(online ? F("online") : F("offline")) + String(F("\"}")); } static String stateTopic(const String &devName) { return devName + F("/state"); } bool MqttClient::connect() { if (0 == settings.mqttUser.length()) { return mqttClient->connect(settings.deviceName.c_str(), stateTopic(settings.deviceName).c_str(), 0, true, stateMessage(false).c_str()); } else { return mqttClient->connect( settings.deviceName.c_str(), settings.mqttUser.c_str(), settings.mqttPassword.c_str(), stateTopic(settings.deviceName).c_str(), 0, true, stateMessage(false).c_str()); } } void MqttClient::reconnect() { if (lastConnectAttempt > 0 && (millis() - lastConnectAttempt) < MQTT_CONNECTION_ATTEMPT_DELAY) { return; } if (!mqttClient->connected()) { Logger.debug.println(F("Try to (re)connect to MQTT broker")); if (connect()) { Logger.info.println(F("MQTT connected.")); if (subsrcibe()) { mqttClient->publish(stateTopic(settings.deviceName).c_str(), stateMessage(true).c_str(), true); Logger.info.println(F("MQTT subscribed.")); } else { Logger.error.println(F("MQTT subsrcibe failed!")); } } else { Logger.error.println(F("MQTT connect failed!")); } } lastConnectAttempt = millis(); } bool MqttClient::subsrcibe() { String topic = settings.mqttSendTopic + "+"; Logger.debug.print(F("MQTT subscribe to topic: ")); Logger.debug.println(topic); return mqttClient->subscribe(topic.c_str()); } void MqttClient::loop() { reconnect(); mqttClient->loop(); } void MqttClient::onMessage(char *topic, uint8_t *payload, unsigned int length) { PayloadString strPayload(payload, length); String strTopic(topic); Logger.debug.print(F("New MQTT message: ")); Logger.debug.print(strTopic); Logger.debug.print(F(" .. ")); Logger.debug.println(strPayload); if (strTopic.startsWith(settings.mqttSendTopic)) { if (onSendCallback) { onSendCallback(String(topic + settings.mqttSendTopic.length()), strPayload); } } } void MqttClient::registerRfDataHandler(const MqttClient::HandlerCallback &cb) { onSendCallback = cb; } void MqttClient::publishCode(const String &protocol, const String &payload) { String topic = settings.mqttReceiveTopic + protocol; Logger.debug.print(F("Publish MQTT message: ")); Logger.debug.print(topic); Logger.debug.print(F(" retain=")); Logger.debug.print(settings.mqttRetain); Logger.debug.print(F(" .. ")); Logger.debug.println(payload); mqttClient->publish(topic.c_str(), payload.c_str(), settings.mqttRetain); } <|endoftext|>
<commit_before>//===------------------------- MemLocation.cpp ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation" #include "swift/SIL/MemLocation.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// static inline void removeMemLocations(MemLocationValueMap &Values, MemLocationList &FirstLevel) { for (auto &X : FirstLevel) Values.erase(X); } //===----------------------------------------------------------------------===// // SILValue Projection //===----------------------------------------------------------------------===// void SILValueProjection::print() const { llvm::outs() << Base; llvm::outs() << Path.getValue(); } //===----------------------------------------------------------------------===// // Load Store Value //===----------------------------------------------------------------------===// SILValue LoadStoreValue::createExtract(SILValue Base, Optional<ProjectionPath> &Path, SILInstruction *Inst) { // If we found a projection path, but there are no projections, then the two // loads must be the same, return PrevLI. if (!Path || Path->empty()) return Base; // Ok, at this point we know that we can construct our aggregate projections // from our list of address projections. SILValue LastExtract = Base; SILBuilder Builder(Inst); // Construct the path! for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) { LastExtract = PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get(); continue; } // Return the last extract we created. return LastExtract; } //===----------------------------------------------------------------------===// // Memory Location //===----------------------------------------------------------------------===// void MemLocation::initialize(SILValue Dest) { Base = getUnderlyingObject(Dest); Path = ProjectionPath::getAddrProjectionPath(Base, Dest); } bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases are not must-alias, the locations may not alias. if (!AA->isMustAlias(Base, RHS.getBase())) return false; // If projection paths are different, then the locations can not alias. if (!hasIdenticalProjectionPath(RHS)) return false; return true; } bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases do not alias, then the locations can not alias. if (AA->isNoAlias(Base, RHS.getBase())) return false; // If one projection path is a prefix of another, then the locations // could alias. if (hasNonEmptySymmetricPathDifference(RHS)) return false; return true; } MemLocation MemLocation::createMemLocation(SILValue Base, ProjectionPath &P1, ProjectionPath &P2) { ProjectionPath T; T.append(P1); T.append(P2); return MemLocation(Base, T); } void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs, SILModule *Mod) { SILType Ty = getType(); llvm::SmallVector<Projection, 8> Out; Projection::getFirstLevelAddrProjections(Ty, *Mod, Out); for (auto &X : Out) { ProjectionPath P; P.append(X); P.append(Path.getValue()); Locs.push_back(MemLocation(Base, P)); } } void MemLocation::expand(MemLocation &Base, SILModule *Mod, MemLocationList &Locs, TypeExpansionMap &TECache) { // To expand a memory location to its indivisible parts, we first get the // address projection paths from the accessed type to each indivisible field, // i.e. leaf nodes, then we append these projection paths to the Base. // // NOTE: we get the address projection because the Base memory location is // initialized with address projection paths. By keeping it consistent makes // it easier to implement the getType function for MemLocation. // SILType BaseType = Base.getType(); if (TECache.find(BaseType) == TECache.end()) { // There is no cached expansion for this type, build and cache it now. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(BaseType, Mod, Paths, true); for (auto &P : Paths) { TECache[BaseType()].push_back(std::move(P.getValue())); } } // Construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. for (auto &X : TECache[BaseType]) { Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } } void MemLocation::reduce(MemLocation &Base, SILModule *Mod, MemLocationSet &Locs) { // First, construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, false); for (auto &X : Paths) { ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); // Reached the end of the projection tree, this is a leaf node. if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, check whether all its first level children are // alive. bool Alive = true; for (auto &X : FirstLevel) { if (Locs.find(X) != Locs.end()) continue; Alive = false; } // All first level locations are alive, create the new aggregated location. if (Alive) { for (auto &X : FirstLevel) Locs.erase(X); Locs.insert(*I); } } } void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val, SILModule *Mod, MemLocationList &Locs, LoadStoreValueList &Vals) { // To expand a memory location to its indivisible parts, we first get the // projection paths from the accessed type to each indivisible field, i.e. // leaf nodes, then we append these projection paths to the Base. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, true); // Construct the MemLocation and LoadStoreValues by appending the projection // path // from the accessed node to the leaf nodes. for (auto &X : Paths) { Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); Vals.push_back(LoadStoreValue(Val, X.getValue())); } } SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod, MemLocationValueMap &Values, SILInstruction *InsertPt) { // Walk bottom up the projection tree, try to reason about how to construct // a single SILValue out of all the available values for all the memory // locations. // // First, get a list of all the leaf nodes and intermediate nodes for the // Base memory location. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, false); for (auto &X : Paths) { ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { // This is a leaf node, we have a value for it. // // Reached the end of the projection tree, this is a leaf node. MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, we need to construct a value for it. // // If there are more than 1 children and all the children nodes have // LoadStoreValues with the same base. we can get away by not extracting // value // for every single field. // // Simply create a new node with all the aggregated base value, i.e. // stripping off the last level projection. // bool HasIdenticalValueBase = true; auto Iter = FirstLevel.begin(); LoadStoreValue &FirstVal = Values[*Iter]; SILValue FirstBase = FirstVal.getBase(); Iter = std::next(Iter); for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) { LoadStoreValue &V = Values[*Iter]; HasIdenticalValueBase &= (FirstBase == V.getBase()); } if (HasIdenticalValueBase && (FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) { Values[*I] = FirstVal.stripLastLevelProjection(); // We have a value for the parent, remove all the values for children. removeMemLocations(Values, FirstLevel); continue; } // In 2 cases do we need aggregation. // // 1. If there is only 1 child and we can not strip off any projections, // that means we need to create an aggregation. // // 2. Children have values from different bases, We need to create // extractions and aggregation in this case. // llvm::SmallVector<SILValue, 8> Vals; for (auto &X : FirstLevel) { Vals.push_back(Values[X].materialize(InsertPt)); } SILBuilder Builder(InsertPt); NullablePtr<swift::SILInstruction> AI = Projection::createAggFromFirstLevelProjections( Builder, InsertPt->getLoc(), I->getType(), Vals); // This is the Value for the current node. ProjectionPath P; Values[*I] = LoadStoreValue(SILValue(AI.get()), P); removeMemLocations(Values, FirstLevel); // Keep iterating until we have reach the top-most level of the projection // tree. // i.e. the memory location represented by the Base. } assert(Values.size() == 1 && "Should have a single location this point"); // Finally materialize and return the forwarding SILValue. return Values.begin()->second.materialize(InsertPt); } void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Construct a Location to represent the memory written by this instruction. MemLocation L(Mem); // If we cant figure out the Base or Projection Path for the memory location, // simply ignore it for now. if (!L.isValid()) return; // Expand the given Mem into individual fields and add them to the // locationvault. MemLocationList Locs; MemLocation::expand(L, M, Locs, TV); for (auto &Loc : Locs) { BM[Loc] = LV.size(); LV.push_back(Loc); } } void MemLocation::enumerateMemLocations(SILFunction &F, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Enumerate all locations accessed by the loads or stores. // // TODO: process more instructions as we process more instructions in // processInstruction. // SILValue Op; for (auto &B : F) { for (auto &I : B) { if (auto *LI = dyn_cast<LoadInst>(&I)) { enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV); } else if (auto *SI = dyn_cast<StoreInst>(&I)) { enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV); } } } } <commit_msg>Refactor in MemLocation. NFC<commit_after>//===------------------------- MemLocation.cpp ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation" #include "swift/SIL/MemLocation.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// static inline void removeMemLocations(MemLocationValueMap &Values, MemLocationList &FirstLevel) { for (auto &X : FirstLevel) Values.erase(X); } //===----------------------------------------------------------------------===// // SILValue Projection //===----------------------------------------------------------------------===// void SILValueProjection::print() const { llvm::outs() << Base; llvm::outs() << Path.getValue(); } //===----------------------------------------------------------------------===// // Load Store Value //===----------------------------------------------------------------------===// SILValue LoadStoreValue::createExtract(SILValue Base, Optional<ProjectionPath> &Path, SILInstruction *Inst) { // If we found a projection path, but there are no projections, then the two // loads must be the same, return PrevLI. if (!Path || Path->empty()) return Base; // Ok, at this point we know that we can construct our aggregate projections // from our list of address projections. SILValue LastExtract = Base; SILBuilder Builder(Inst); // Construct the path! for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) { LastExtract = PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get(); continue; } // Return the last extract we created. return LastExtract; } //===----------------------------------------------------------------------===// // Memory Location //===----------------------------------------------------------------------===// void MemLocation::initialize(SILValue Dest) { Base = getUnderlyingObject(Dest); Path = ProjectionPath::getAddrProjectionPath(Base, Dest); } bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases are not must-alias, the locations may not alias. if (!AA->isMustAlias(Base, RHS.getBase())) return false; // If projection paths are different, then the locations can not alias. if (!hasIdenticalProjectionPath(RHS)) return false; return true; } bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases do not alias, then the locations can not alias. if (AA->isNoAlias(Base, RHS.getBase())) return false; // If one projection path is a prefix of another, then the locations // could alias. if (hasNonEmptySymmetricPathDifference(RHS)) return false; return true; } MemLocation MemLocation::createMemLocation(SILValue Base, ProjectionPath &P1, ProjectionPath &P2) { ProjectionPath T; T.append(P1); T.append(P2); return MemLocation(Base, T); } void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs, SILModule *Mod) { SILType Ty = getType(); llvm::SmallVector<Projection, 8> Out; Projection::getFirstLevelAddrProjections(Ty, *Mod, Out); for (auto &X : Out) { ProjectionPath P; P.append(X); P.append(Path.getValue()); Locs.push_back(MemLocation(Base, P)); } } void MemLocation::expand(MemLocation &Base, SILModule *Mod, MemLocationList &Locs, TypeExpansionMap &TECache) { // To expand a memory location to its indivisible parts, we first get the // address projection paths from the accessed type to each indivisible field, // i.e. leaf nodes, then we append these projection paths to the Base. // // NOTE: we get the address projection because the Base memory location is // initialized with address projection paths. By keeping it consistent makes // it easier to implement the getType function for MemLocation. // SILType BaseTy = Base.getType(); if (TECache.find(BaseTy) == TECache.end()) { // There is no cached expansion for this type, build and cache it now. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(BaseTy, Mod, Paths, true); for (auto &P : Paths) { TECache[BaseTy].push_back(std::move(P.getValue())); } } // Construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. for (auto &X : TECache[BaseTy]) { Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } } void MemLocation::reduce(MemLocation &Base, SILModule *Mod, MemLocationSet &Locs) { // First, construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, false); for (auto &X : Paths) { ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); // Reached the end of the projection tree, this is a leaf node. if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, check whether all its first level children are // alive. bool Alive = true; for (auto &X : FirstLevel) { if (Locs.find(X) != Locs.end()) continue; Alive = false; } // All first level locations are alive, create the new aggregated location. if (Alive) { for (auto &X : FirstLevel) Locs.erase(X); Locs.insert(*I); } } } void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val, SILModule *Mod, MemLocationList &Locs, LoadStoreValueList &Vals) { // To expand a memory location to its indivisible parts, we first get the // projection paths from the accessed type to each indivisible field, i.e. // leaf nodes, then we append these projection paths to the Base. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, true); // Construct the MemLocation and LoadStoreValues by appending the projection // path // from the accessed node to the leaf nodes. for (auto &X : Paths) { Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); Vals.push_back(LoadStoreValue(Val, X.getValue())); } } SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod, MemLocationValueMap &Values, SILInstruction *InsertPt) { // Walk bottom up the projection tree, try to reason about how to construct // a single SILValue out of all the available values for all the memory // locations. // // First, get a list of all the leaf nodes and intermediate nodes for the // Base memory location. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths, false); for (auto &X : Paths) { ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(), Base.getPath().getValue())); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { // This is a leaf node, we have a value for it. // // Reached the end of the projection tree, this is a leaf node. MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, we need to construct a value for it. // // If there are more than 1 children and all the children nodes have // LoadStoreValues with the same base. we can get away by not extracting // value // for every single field. // // Simply create a new node with all the aggregated base value, i.e. // stripping off the last level projection. // bool HasIdenticalValueBase = true; auto Iter = FirstLevel.begin(); LoadStoreValue &FirstVal = Values[*Iter]; SILValue FirstBase = FirstVal.getBase(); Iter = std::next(Iter); for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) { LoadStoreValue &V = Values[*Iter]; HasIdenticalValueBase &= (FirstBase == V.getBase()); } if (HasIdenticalValueBase && (FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) { Values[*I] = FirstVal.stripLastLevelProjection(); // We have a value for the parent, remove all the values for children. removeMemLocations(Values, FirstLevel); continue; } // In 2 cases do we need aggregation. // // 1. If there is only 1 child and we can not strip off any projections, // that means we need to create an aggregation. // // 2. Children have values from different bases, We need to create // extractions and aggregation in this case. // llvm::SmallVector<SILValue, 8> Vals; for (auto &X : FirstLevel) { Vals.push_back(Values[X].materialize(InsertPt)); } SILBuilder Builder(InsertPt); NullablePtr<swift::SILInstruction> AI = Projection::createAggFromFirstLevelProjections( Builder, InsertPt->getLoc(), I->getType(), Vals); // This is the Value for the current node. ProjectionPath P; Values[*I] = LoadStoreValue(SILValue(AI.get()), P); removeMemLocations(Values, FirstLevel); // Keep iterating until we have reach the top-most level of the projection // tree. // i.e. the memory location represented by the Base. } assert(Values.size() == 1 && "Should have a single location this point"); // Finally materialize and return the forwarding SILValue. return Values.begin()->second.materialize(InsertPt); } void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Construct a Location to represent the memory written by this instruction. MemLocation L(Mem); // If we cant figure out the Base or Projection Path for the memory location, // simply ignore it for now. if (!L.isValid()) return; // Expand the given Mem into individual fields and add them to the // locationvault. MemLocationList Locs; MemLocation::expand(L, M, Locs, TV); for (auto &Loc : Locs) { BM[Loc] = LV.size(); LV.push_back(Loc); } } void MemLocation::enumerateMemLocations(SILFunction &F, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Enumerate all locations accessed by the loads or stores. // // TODO: process more instructions as we process more instructions in // processInstruction. // SILValue Op; for (auto &B : F) { for (auto &I : B) { if (auto *LI = dyn_cast<LoadInst>(&I)) { enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV); } else if (auto *SI = dyn_cast<StoreInst>(&I)) { enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV); } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org> This library 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. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "itemmodel.h" #include "itemfetchjob.h" #include "monitor.h" #include "session.h" #include <kmime/kmime_message.h> #include <kdebug.h> #include <klocale.h> #include <QtCore/QDebug> #include <QtCore/QMimeData> using namespace Akonadi; /* * This struct is used for optimization reasons. * because it embeds the row. * * Semantically, we could have used an item instead. */ struct ItemContainer { ItemContainer( const Item& i, int r ) { item = i; row = r; } Item item; int row; }; class ItemModel::Private { public: Private( ItemModel *parent ) : mParent( parent ), monitor( 0 ) { session = new Session( QByteArray("ItemModel-") + QByteArray::number( qrand() ), mParent ); } ~Private() { delete monitor; } void listingDone( KJob* ); void itemChanged( const Akonadi::Item&, const QStringList& ); void itemsAdded( const Akonadi::Item::List &list ); void itemAdded( const Akonadi::Item &item ); void itemMoved( const Akonadi::Item&, const Akonadi::Collection& src, const Akonadi::Collection& dst ); void itemRemoved( const Akonadi::DataReference& ); int rowForItem( const Akonadi::DataReference& ); ItemModel *mParent; QList<ItemContainer*> items; QHash<DataReference, ItemContainer*> itemHash; Collection collection; Monitor *monitor; Session *session; QStringList mFetchParts; }; void ItemModel::Private::listingDone( KJob * job ) { ItemFetchJob *fetch = static_cast<ItemFetchJob*>( job ); if ( job->error() ) { // TODO kWarning() <<"Item query failed:" << job->errorString(); } // start monitor monitor = new Monitor( mParent ); monitor->addFetchPart( Item::PartEnvelope ); foreach( QString part, mFetchParts ) monitor->addFetchPart( part ); monitor->ignoreSession( session ); monitor->monitorCollection( collection ); mParent->connect( monitor, SIGNAL(itemChanged( const Akonadi::Item&, const QStringList& )), mParent, SLOT(itemChanged( const Akonadi::Item&, const QStringList& )) ); mParent->connect( monitor, SIGNAL(itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& )), mParent, SLOT(itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); mParent->connect( monitor, SIGNAL(itemAdded( const Akonadi::Item&, const Akonadi::Collection& )), mParent, SLOT(itemAdded( const Akonadi::Item& )) ); mParent->connect( monitor, SIGNAL(itemRemoved(Akonadi::DataReference)), mParent, SLOT(itemRemoved(Akonadi::DataReference)) ); } int ItemModel::Private::rowForItem( const Akonadi::DataReference& ref ) { ItemContainer *container = itemHash.value( ref ); if ( !container ) return -1; /* Try to find the item directly; If items have been removed, this first try won't succeed because the ItemContainer rows have not been updated (costs too much). */ if ( container->row < items.count() && items.at( container->row ) == container ) return container->row; else { // Slow solution if the fist one has not succeeded int row = -1; for ( int i = 0; i < items.size(); ++i ) { if ( items.at( i )->item.reference() == ref ) { row = i; break; } } return row; } } void ItemModel::Private::itemChanged( const Akonadi::Item &item, const QStringList& ) { int row = rowForItem( item.reference() ); if ( row < 0 ) return; QModelIndex index = mParent->index( row, 0, QModelIndex() ); mParent->dataChanged( index, index ); } void ItemModel::Private::itemMoved( const Akonadi::Item &item, const Akonadi::Collection& colSrc, const Akonadi::Collection& colDst ) { if ( colSrc == collection && colDst != collection ) // item leaving this model { itemRemoved( item.reference() ); return; } if ( colDst == collection && colSrc != collection ) { itemAdded( item ); return; } } void ItemModel::Private::itemsAdded( const Akonadi::Item::List &list ) { if ( list.isEmpty() ) return; mParent->beginInsertRows( QModelIndex(), items.count(), items.count() + list.count() - 1 ); foreach( Item item, list ) { ItemContainer *c = new ItemContainer( item, items.count() ); items.append( c ); itemHash[ item.reference() ] = c; } mParent->endInsertRows(); } void ItemModel::Private::itemAdded( const Akonadi::Item &item ) { Item::List l; l << item; itemsAdded( l ); } void ItemModel::Private::itemRemoved( const DataReference &reference ) { int row = rowForItem( reference ); if ( row < 0 ) return; mParent->beginRemoveRows( QModelIndex(), row, row ); const Item item = items.at( row )->item; Q_ASSERT( item.isValid() ); itemHash.remove( item.reference() ); delete items.takeAt( row ); mParent->endRemoveRows(); } ItemModel::ItemModel( QObject *parent ) : QAbstractTableModel( parent ), d( new Private( this ) ) { setSupportedDragActions( Qt::MoveAction | Qt::CopyAction ); } ItemModel::~ItemModel() { delete d; } QVariant ItemModel::data( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); if ( index.row() >= d->items.count() ) return QVariant(); const Item item = d->items.at( index.row() )->item; if ( !item.isValid() ) return QVariant(); if ( role == Qt::DisplayRole ) { switch ( index.column() ) { case Id: return QString::number( item.reference().id() ); case RemoteId: return item.reference().remoteId(); case MimeType: return item.mimeType(); } } if ( role == IdRole ) { switch ( index.column() ) { case Id: return QString::number( item.reference().id() ); case RemoteId: return item.reference().remoteId(); case MimeType: return item.mimeType(); } } return QVariant(); } int ItemModel::rowCount( const QModelIndex & parent ) const { if ( !parent.isValid() ) return d->items.count(); return 0; } int ItemModel::columnCount(const QModelIndex & parent) const { if ( !parent.isValid() ) return 3; // keep in sync with Column enum return 0; } QVariant ItemModel::headerData( int section, Qt::Orientation orientation, int role ) const { if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) { switch ( section ) { case Id: return i18n( "Id" ); case RemoteId: return i18n( "Remote Id" ); case MimeType: return i18n( "MimeType" ); default: return QString(); } } return QAbstractTableModel::headerData( section, orientation, role ); } void ItemModel::setCollection( const Collection &collection ) { qWarning() << "ItemModel::setPath()"; if ( d->collection == collection ) return; d->collection = collection; // the query changed, thus everything we have already is invalid foreach( ItemContainer *c, d->items ) delete c; d->items.clear(); reset(); // stop all running jobs d->session->clear(); delete d->monitor; d->monitor = 0; // start listing job ItemFetchJob* job = new ItemFetchJob( collection, session() ); foreach( QString part, d->mFetchParts ) job->addFetchPart( part ); connect( job, SIGNAL(itemsReceived(Akonadi::Item::List)), SLOT(itemsAdded(Akonadi::Item::List)) ); connect( job, SIGNAL(result(KJob*)), SLOT(listingDone(KJob*)) ); emit collectionSet( collection ); } void ItemModel::addFetchPart( const QString &identifier ) { if ( !d->mFetchParts.contains( identifier ) ) d->mFetchParts.append( identifier ); // update the monitor if ( d->monitor ) { foreach( QString part, d->mFetchParts ) d->monitor->addFetchPart( part ); } } DataReference ItemModel::referenceForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return DataReference(); if ( index.row() >= d->items.count() ) return DataReference(); const Item item = d->items.at( index.row() )->item; Q_ASSERT( item.isValid() ); return item.reference(); } Item ItemModel::itemForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return Akonadi::Item(); if ( index.row() >= d->items.count() ) return Akonadi::Item(); Item item = d->items.at( index.row() )->item; Q_ASSERT( item.isValid() ); return item; } Qt::ItemFlags ItemModel::flags( const QModelIndex &index ) const { Qt::ItemFlags defaultFlags = QAbstractTableModel::flags(index); if (index.isValid()) return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags; else return Qt::ItemIsDropEnabled | defaultFlags; } QStringList ItemModel::mimeTypes() const { return QStringList(); } Session * ItemModel::session() const { return d->session; } QMimeData *ItemModel::mimeData( const QModelIndexList &indexes ) const { QMimeData *data = new QMimeData(); // Add item uri to the mimedata for dropping in external applications KUrl::List urls; foreach ( QModelIndex index, indexes ) { if ( index.column() != 0 ) continue; urls << itemForIndex( index ).url(); } urls.populateMimeData( data ); return data; } QModelIndex ItemModel::indexForItem( const Akonadi::DataReference& ref, const int column ) const { return index( d->rowForItem( ref ), column ); } #include "itemmodel.moc" <commit_msg>Envelope is only defined for mails, so don't fetch it in the generic model.<commit_after>/* Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org> This library 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. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "itemmodel.h" #include "itemfetchjob.h" #include "monitor.h" #include "session.h" #include <kmime/kmime_message.h> #include <kdebug.h> #include <klocale.h> #include <QtCore/QDebug> #include <QtCore/QMimeData> using namespace Akonadi; /* * This struct is used for optimization reasons. * because it embeds the row. * * Semantically, we could have used an item instead. */ struct ItemContainer { ItemContainer( const Item& i, int r ) { item = i; row = r; } Item item; int row; }; class ItemModel::Private { public: Private( ItemModel *parent ) : mParent( parent ), monitor( 0 ) { session = new Session( QByteArray("ItemModel-") + QByteArray::number( qrand() ), mParent ); } ~Private() { delete monitor; } void listingDone( KJob* ); void itemChanged( const Akonadi::Item&, const QStringList& ); void itemsAdded( const Akonadi::Item::List &list ); void itemAdded( const Akonadi::Item &item ); void itemMoved( const Akonadi::Item&, const Akonadi::Collection& src, const Akonadi::Collection& dst ); void itemRemoved( const Akonadi::DataReference& ); int rowForItem( const Akonadi::DataReference& ); ItemModel *mParent; QList<ItemContainer*> items; QHash<DataReference, ItemContainer*> itemHash; Collection collection; Monitor *monitor; Session *session; QStringList mFetchParts; }; void ItemModel::Private::listingDone( KJob * job ) { ItemFetchJob *fetch = static_cast<ItemFetchJob*>( job ); if ( job->error() ) { // TODO kWarning() <<"Item query failed:" << job->errorString(); } // start monitor monitor = new Monitor( mParent ); foreach( QString part, mFetchParts ) monitor->addFetchPart( part ); monitor->ignoreSession( session ); monitor->monitorCollection( collection ); mParent->connect( monitor, SIGNAL(itemChanged( const Akonadi::Item&, const QStringList& )), mParent, SLOT(itemChanged( const Akonadi::Item&, const QStringList& )) ); mParent->connect( monitor, SIGNAL(itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& )), mParent, SLOT(itemMoved( const Akonadi::Item&, const Akonadi::Collection&, const Akonadi::Collection& ) ) ); mParent->connect( monitor, SIGNAL(itemAdded( const Akonadi::Item&, const Akonadi::Collection& )), mParent, SLOT(itemAdded( const Akonadi::Item& )) ); mParent->connect( monitor, SIGNAL(itemRemoved(Akonadi::DataReference)), mParent, SLOT(itemRemoved(Akonadi::DataReference)) ); } int ItemModel::Private::rowForItem( const Akonadi::DataReference& ref ) { ItemContainer *container = itemHash.value( ref ); if ( !container ) return -1; /* Try to find the item directly; If items have been removed, this first try won't succeed because the ItemContainer rows have not been updated (costs too much). */ if ( container->row < items.count() && items.at( container->row ) == container ) return container->row; else { // Slow solution if the fist one has not succeeded int row = -1; for ( int i = 0; i < items.size(); ++i ) { if ( items.at( i )->item.reference() == ref ) { row = i; break; } } return row; } } void ItemModel::Private::itemChanged( const Akonadi::Item &item, const QStringList& ) { int row = rowForItem( item.reference() ); if ( row < 0 ) return; QModelIndex index = mParent->index( row, 0, QModelIndex() ); mParent->dataChanged( index, index ); } void ItemModel::Private::itemMoved( const Akonadi::Item &item, const Akonadi::Collection& colSrc, const Akonadi::Collection& colDst ) { if ( colSrc == collection && colDst != collection ) // item leaving this model { itemRemoved( item.reference() ); return; } if ( colDst == collection && colSrc != collection ) { itemAdded( item ); return; } } void ItemModel::Private::itemsAdded( const Akonadi::Item::List &list ) { if ( list.isEmpty() ) return; mParent->beginInsertRows( QModelIndex(), items.count(), items.count() + list.count() - 1 ); foreach( Item item, list ) { ItemContainer *c = new ItemContainer( item, items.count() ); items.append( c ); itemHash[ item.reference() ] = c; } mParent->endInsertRows(); } void ItemModel::Private::itemAdded( const Akonadi::Item &item ) { Item::List l; l << item; itemsAdded( l ); } void ItemModel::Private::itemRemoved( const DataReference &reference ) { int row = rowForItem( reference ); if ( row < 0 ) return; mParent->beginRemoveRows( QModelIndex(), row, row ); const Item item = items.at( row )->item; Q_ASSERT( item.isValid() ); itemHash.remove( item.reference() ); delete items.takeAt( row ); mParent->endRemoveRows(); } ItemModel::ItemModel( QObject *parent ) : QAbstractTableModel( parent ), d( new Private( this ) ) { setSupportedDragActions( Qt::MoveAction | Qt::CopyAction ); } ItemModel::~ItemModel() { delete d; } QVariant ItemModel::data( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); if ( index.row() >= d->items.count() ) return QVariant(); const Item item = d->items.at( index.row() )->item; if ( !item.isValid() ) return QVariant(); if ( role == Qt::DisplayRole ) { switch ( index.column() ) { case Id: return QString::number( item.reference().id() ); case RemoteId: return item.reference().remoteId(); case MimeType: return item.mimeType(); } } if ( role == IdRole ) { switch ( index.column() ) { case Id: return QString::number( item.reference().id() ); case RemoteId: return item.reference().remoteId(); case MimeType: return item.mimeType(); } } return QVariant(); } int ItemModel::rowCount( const QModelIndex & parent ) const { if ( !parent.isValid() ) return d->items.count(); return 0; } int ItemModel::columnCount(const QModelIndex & parent) const { if ( !parent.isValid() ) return 3; // keep in sync with Column enum return 0; } QVariant ItemModel::headerData( int section, Qt::Orientation orientation, int role ) const { if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) { switch ( section ) { case Id: return i18n( "Id" ); case RemoteId: return i18n( "Remote Id" ); case MimeType: return i18n( "MimeType" ); default: return QString(); } } return QAbstractTableModel::headerData( section, orientation, role ); } void ItemModel::setCollection( const Collection &collection ) { qWarning() << "ItemModel::setPath()"; if ( d->collection == collection ) return; d->collection = collection; // the query changed, thus everything we have already is invalid foreach( ItemContainer *c, d->items ) delete c; d->items.clear(); reset(); // stop all running jobs d->session->clear(); delete d->monitor; d->monitor = 0; // start listing job ItemFetchJob* job = new ItemFetchJob( collection, session() ); foreach( QString part, d->mFetchParts ) job->addFetchPart( part ); connect( job, SIGNAL(itemsReceived(Akonadi::Item::List)), SLOT(itemsAdded(Akonadi::Item::List)) ); connect( job, SIGNAL(result(KJob*)), SLOT(listingDone(KJob*)) ); emit collectionSet( collection ); } void ItemModel::addFetchPart( const QString &identifier ) { if ( !d->mFetchParts.contains( identifier ) ) d->mFetchParts.append( identifier ); // update the monitor if ( d->monitor ) { foreach( QString part, d->mFetchParts ) d->monitor->addFetchPart( part ); } } DataReference ItemModel::referenceForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return DataReference(); if ( index.row() >= d->items.count() ) return DataReference(); const Item item = d->items.at( index.row() )->item; Q_ASSERT( item.isValid() ); return item.reference(); } Item ItemModel::itemForIndex( const QModelIndex & index ) const { if ( !index.isValid() ) return Akonadi::Item(); if ( index.row() >= d->items.count() ) return Akonadi::Item(); Item item = d->items.at( index.row() )->item; Q_ASSERT( item.isValid() ); return item; } Qt::ItemFlags ItemModel::flags( const QModelIndex &index ) const { Qt::ItemFlags defaultFlags = QAbstractTableModel::flags(index); if (index.isValid()) return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags; else return Qt::ItemIsDropEnabled | defaultFlags; } QStringList ItemModel::mimeTypes() const { return QStringList(); } Session * ItemModel::session() const { return d->session; } QMimeData *ItemModel::mimeData( const QModelIndexList &indexes ) const { QMimeData *data = new QMimeData(); // Add item uri to the mimedata for dropping in external applications KUrl::List urls; foreach ( QModelIndex index, indexes ) { if ( index.column() != 0 ) continue; urls << itemForIndex( index ).url(); } urls.populateMimeData( data ); return data; } QModelIndex ItemModel::indexForItem( const Akonadi::DataReference& ref, const int column ) const { return index( d->rowForItem( ref ), column ); } #include "itemmodel.moc" <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- Copyright 2017 Google 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. ----------------------------------------------------------------------------- */ // Author: Kevin P. Barry [ta0kira@gmail.com] [kevinbarry@google.com] #include <condition_variable> #include <functional> #include <list> #include <mutex> #include <queue> #include <string> #include <thread> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "thread-capture.h" #include "thread-crosser.h" using testing::ElementsAre; namespace capture_thread { // Captures text log entries. class LogText : public ThreadCapture<LogText> { public: static void Log(std::string line) { if (GetCurrent()) { GetCurrent()->LogLine(std::move(line)); } } protected: LogText() = default; virtual ~LogText() = default; virtual void LogLine(std::string line) = 0; }; // Captures text log entries, without automatic thread crossing. class LogTextSingleThread : public LogText { public: LogTextSingleThread() : capture_to_(this) {} const std::list<std::string>& GetLines() { return lines_; } private: void LogLine(std::string line) override { lines_.emplace_back(std::move(line)); } std::list<std::string> lines_; const ScopedCapture capture_to_; }; // Captures text log entries, with automatic thread crossing. class LogTextMultiThread : public LogText { public: LogTextMultiThread() : cross_and_capture_to_(this) {} std::list<std::string> GetLines() { std::lock_guard<std::mutex> lock(data_lock_); return lines_; } private: void LogLine(std::string line) override { std::lock_guard<std::mutex> lock(data_lock_); lines_.emplace_back(std::move(line)); } std::mutex data_lock_; std::list<std::string> lines_; const AutoThreadCrosser cross_and_capture_to_; }; // Captures numerical log entries. class LogValues : public ThreadCapture<LogValues> { public: static void Count(int count) { if (GetCurrent()) { GetCurrent()->LogCount(count); } } protected: LogValues() = default; virtual ~LogValues() = default; virtual void LogCount(int count) = 0; }; // Captures numerical log entries, without automatic thread crossing. class LogValuesSingleThread : public LogValues { public: LogValuesSingleThread() : capture_to_(this) {} const std::list<int>& GetCounts() { return counts_; } private: void LogCount(int count) { counts_.emplace_back(count); } std::list<int> counts_; const ScopedCapture capture_to_; }; // Captures numerical log entries, with automatic thread crossing. class LogValuesMultiThread : public LogValues { public: LogValuesMultiThread() : cross_and_capture_to_(this) {} std::list<int> GetCounts() { std::lock_guard<std::mutex> lock(data_lock_); return counts_; } private: void LogCount(int count) { std::lock_guard<std::mutex> lock(data_lock_); counts_.emplace_back(count); } std::mutex data_lock_; std::list<int> counts_; const AutoThreadCrosser cross_and_capture_to_; }; // Manages a queue of callbacks shared between threads. class BlockingCallbackQueue { public: void Push(std::function<void()> callback) { std::lock_guard<std::mutex> lock(queue_lock_); queue_.push(std::move(callback)); condition_.notify_all(); } bool PopAndCall() { std::unique_lock<std::mutex> lock(queue_lock_); while (!terminated_ && queue_.empty()) { condition_.wait(lock); } if (terminated_) { return false; } else { const auto callback = queue_.front(); ++pending_; queue_.pop(); lock.unlock(); if (callback) { callback(); } lock.lock(); --pending_; condition_.notify_all(); return true; } } void WaitUntilEmpty() { std::unique_lock<std::mutex> lock(queue_lock_); while (!terminated_ && (!queue_.empty() || pending_ > 0)) { condition_.wait(lock); } } void Terminate() { std::lock_guard<std::mutex> lock(queue_lock_); terminated_ = true; condition_.notify_all(); } private: std::mutex queue_lock_; std::condition_variable condition_; int pending_ = 0; bool terminated_ = false; std::queue<std::function<void()>> queue_; }; TEST(ThreadCaptureTest, NoLoggerInterferenceWithDifferentTypes) { LogText::Log("not logged"); LogValues::Count(0); { LogTextSingleThread text_logger; LogText::Log("logged 1"); { LogValuesSingleThread count_logger; LogValues::Count(1); LogText::Log("logged 2"); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1)); } LogText::Log("logged 3"); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1", "logged 2", "logged 3")); } } TEST(ThreadCaptureTest, SameTypeOverrides) { LogTextSingleThread text_logger1; LogText::Log("logged 1"); { LogTextSingleThread text_logger2; LogText::Log("logged 2"); EXPECT_THAT(text_logger2.GetLines(), ElementsAre("logged 2")); } LogText::Log("logged 3"); EXPECT_THAT(text_logger1.GetLines(), ElementsAre("logged 1", "logged 3")); } TEST(ThreadCaptureTest, ThreadsAreNotCrossed) { LogTextSingleThread logger; LogText::Log("logged 1"); std::thread worker([] { LogText::Log("logged 2"); }); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCaptureTest, ManualThreadCrossing) { LogTextSingleThread logger; LogText::Log("logged 1"); const LogTextSingleThread::ThreadBridge bridge; std::thread worker([&bridge] { LogTextSingleThread::CrossThreads logger(bridge); LogText::Log("logged 2"); }); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1", "logged 2")); } TEST(ThreadCrosserTest, WrapCallIsFineWithoutLogger) { bool called = false; ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("not logged"); })(); EXPECT_TRUE(called); } TEST(ThreadCrosserTest, WrapCallIsNotLazy) { LogTextMultiThread logger1; bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); LogTextMultiThread logger2; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, WrapCallOnlyCapturesCrossers) { LogTextMultiThread logger1; LogTextSingleThread logger2; bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); callback(); EXPECT_TRUE(called); LogText::Log("logged 2"); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); } TEST(ThreadCrosserTest, WrapCallIsIdempotent) { LogTextMultiThread logger1; bool called = false; const auto callback = ThreadCrosser::WrapCall(ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); })); LogTextMultiThread logger2; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, WrapCallFallsThroughWithoutLogger) { bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); LogTextMultiThread logger; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCrosserTest, WrapCallWithNullCallbackIsNull) { EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr)); LogTextMultiThread logger; EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr)); } TEST(ThreadCrosserTest, SingleThreadCrossing) { LogTextMultiThread logger; LogText::Log("logged 1"); std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1", "logged 2")); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithMultipleLoggers) { LogTextMultiThread text_logger; LogText::Log("logged 1"); LogValuesMultiThread count_logger; LogValues::Count(1); std::thread worker(ThreadCrosser::WrapCall([] { std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); LogValues::Count(2); })); worker.join(); })); worker.join(); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1", "logged 2")); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1, 2)); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithDifferentLoggerScopes) { LogTextMultiThread text_logger; std::thread worker(ThreadCrosser::WrapCall([] { LogValuesMultiThread count_logger; std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); LogValues::Count(1); })); worker.join(); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1)); })); worker.join(); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithOverride) { LogTextMultiThread logger1; std::thread worker(ThreadCrosser::WrapCall([] { LogTextMultiThread logger2; std::thread worker( ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); worker.join(); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); })); worker.join(); EXPECT_THAT(logger1.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, DifferentLoggersInSameThread) { BlockingCallbackQueue queue; std::thread worker([&queue] { while (true) { LogTextMultiThread logger; if (!queue.PopAndCall()) { break; } LogText::Log("logged in thread"); EXPECT_THAT(logger.GetLines(), ElementsAre("logged in thread")); } }); LogTextMultiThread logger1; queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); { // It's important for the test case that logger2 overrides logger1, i.e., // that they are both in scope at the same time. LogTextMultiThread logger2; queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); } queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 3"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1", "logged 3")); queue.Terminate(); worker.join(); } TEST(ThreadCrosserTest, ReverseOrderOfLoggersOnStack) { LogTextMultiThread logger1; const auto callback = ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); }); LogTextMultiThread logger2; const auto worker_call = ThreadCrosser::WrapCall([callback] { // In callback(), logger1 overrides logger2, whereas in the main thread // logger2 overrides logger1. callback(); LogText::Log("logged 2"); }); LogTextMultiThread logger3; // Call using a thread. std::thread worker(worker_call); worker.join(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); EXPECT_THAT(logger3.GetLines(), ElementsAre()); // Call in the main thread. worker_call(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1", "logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2", "logged 2")); EXPECT_THAT(logger3.GetLines(), ElementsAre()); } } // namespace capture_thread int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Minor scope name fix.<commit_after>/* ----------------------------------------------------------------------------- Copyright 2017 Google 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. ----------------------------------------------------------------------------- */ // Author: Kevin P. Barry [ta0kira@gmail.com] [kevinbarry@google.com] #include <condition_variable> #include <functional> #include <list> #include <mutex> #include <queue> #include <string> #include <thread> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "thread-capture.h" #include "thread-crosser.h" using testing::ElementsAre; namespace capture_thread { // Captures text log entries. class LogText : public ThreadCapture<LogText> { public: static void Log(std::string line) { if (GetCurrent()) { GetCurrent()->LogLine(std::move(line)); } } protected: LogText() = default; virtual ~LogText() = default; virtual void LogLine(std::string line) = 0; }; // Captures text log entries, without automatic thread crossing. class LogTextSingleThread : public LogText { public: LogTextSingleThread() : capture_to_(this) {} const std::list<std::string>& GetLines() { return lines_; } private: void LogLine(std::string line) override { lines_.emplace_back(std::move(line)); } std::list<std::string> lines_; const ScopedCapture capture_to_; }; // Captures text log entries, with automatic thread crossing. class LogTextMultiThread : public LogText { public: LogTextMultiThread() : cross_and_capture_to_(this) {} std::list<std::string> GetLines() { std::lock_guard<std::mutex> lock(data_lock_); return lines_; } private: void LogLine(std::string line) override { std::lock_guard<std::mutex> lock(data_lock_); lines_.emplace_back(std::move(line)); } std::mutex data_lock_; std::list<std::string> lines_; const AutoThreadCrosser cross_and_capture_to_; }; // Captures numerical log entries. class LogValues : public ThreadCapture<LogValues> { public: static void Count(int count) { if (GetCurrent()) { GetCurrent()->LogCount(count); } } protected: LogValues() = default; virtual ~LogValues() = default; virtual void LogCount(int count) = 0; }; // Captures numerical log entries, without automatic thread crossing. class LogValuesSingleThread : public LogValues { public: LogValuesSingleThread() : capture_to_(this) {} const std::list<int>& GetCounts() { return counts_; } private: void LogCount(int count) { counts_.emplace_back(count); } std::list<int> counts_; const ScopedCapture capture_to_; }; // Captures numerical log entries, with automatic thread crossing. class LogValuesMultiThread : public LogValues { public: LogValuesMultiThread() : cross_and_capture_to_(this) {} std::list<int> GetCounts() { std::lock_guard<std::mutex> lock(data_lock_); return counts_; } private: void LogCount(int count) { std::lock_guard<std::mutex> lock(data_lock_); counts_.emplace_back(count); } std::mutex data_lock_; std::list<int> counts_; const AutoThreadCrosser cross_and_capture_to_; }; // Manages a queue of callbacks shared between threads. class BlockingCallbackQueue { public: void Push(std::function<void()> callback) { std::lock_guard<std::mutex> lock(queue_lock_); queue_.push(std::move(callback)); condition_.notify_all(); } bool PopAndCall() { std::unique_lock<std::mutex> lock(queue_lock_); while (!terminated_ && queue_.empty()) { condition_.wait(lock); } if (terminated_) { return false; } else { const auto callback = queue_.front(); ++pending_; queue_.pop(); lock.unlock(); if (callback) { callback(); } lock.lock(); --pending_; condition_.notify_all(); return true; } } void WaitUntilEmpty() { std::unique_lock<std::mutex> lock(queue_lock_); while (!terminated_ && (!queue_.empty() || pending_ > 0)) { condition_.wait(lock); } } void Terminate() { std::lock_guard<std::mutex> lock(queue_lock_); terminated_ = true; condition_.notify_all(); } private: std::mutex queue_lock_; std::condition_variable condition_; int pending_ = 0; bool terminated_ = false; std::queue<std::function<void()>> queue_; }; TEST(ThreadCaptureTest, NoLoggerInterferenceWithDifferentTypes) { LogText::Log("not logged"); LogValues::Count(0); { LogTextSingleThread text_logger; LogText::Log("logged 1"); { LogValuesSingleThread count_logger; LogValues::Count(1); LogText::Log("logged 2"); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1)); } LogText::Log("logged 3"); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1", "logged 2", "logged 3")); } } TEST(ThreadCaptureTest, SameTypeOverrides) { LogTextSingleThread text_logger1; LogText::Log("logged 1"); { LogTextSingleThread text_logger2; LogText::Log("logged 2"); EXPECT_THAT(text_logger2.GetLines(), ElementsAre("logged 2")); } LogText::Log("logged 3"); EXPECT_THAT(text_logger1.GetLines(), ElementsAre("logged 1", "logged 3")); } TEST(ThreadCaptureTest, ThreadsAreNotCrossed) { LogTextSingleThread logger; LogText::Log("logged 1"); std::thread worker([] { LogText::Log("logged 2"); }); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCaptureTest, ManualThreadCrossing) { LogTextSingleThread logger; LogText::Log("logged 1"); const LogText::ThreadBridge bridge; std::thread worker([&bridge] { LogText::CrossThreads logger(bridge); LogText::Log("logged 2"); }); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1", "logged 2")); } TEST(ThreadCrosserTest, WrapCallIsFineWithoutLogger) { bool called = false; ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("not logged"); })(); EXPECT_TRUE(called); } TEST(ThreadCrosserTest, WrapCallIsNotLazy) { LogTextMultiThread logger1; bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); LogTextMultiThread logger2; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, WrapCallOnlyCapturesCrossers) { LogTextMultiThread logger1; LogTextSingleThread logger2; bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); callback(); EXPECT_TRUE(called); LogText::Log("logged 2"); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); } TEST(ThreadCrosserTest, WrapCallIsIdempotent) { LogTextMultiThread logger1; bool called = false; const auto callback = ThreadCrosser::WrapCall(ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); })); LogTextMultiThread logger2; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, WrapCallFallsThroughWithoutLogger) { bool called = false; const auto callback = ThreadCrosser::WrapCall([&called] { called = true; LogText::Log("logged 1"); }); LogTextMultiThread logger; callback(); EXPECT_TRUE(called); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCrosserTest, WrapCallWithNullCallbackIsNull) { EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr)); LogTextMultiThread logger; EXPECT_FALSE(ThreadCrosser::WrapCall(nullptr)); } TEST(ThreadCrosserTest, SingleThreadCrossing) { LogTextMultiThread logger; LogText::Log("logged 1"); std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); worker.join(); EXPECT_THAT(logger.GetLines(), ElementsAre("logged 1", "logged 2")); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithMultipleLoggers) { LogTextMultiThread text_logger; LogText::Log("logged 1"); LogValuesMultiThread count_logger; LogValues::Count(1); std::thread worker(ThreadCrosser::WrapCall([] { std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); LogValues::Count(2); })); worker.join(); })); worker.join(); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1", "logged 2")); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1, 2)); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithDifferentLoggerScopes) { LogTextMultiThread text_logger; std::thread worker(ThreadCrosser::WrapCall([] { LogValuesMultiThread count_logger; std::thread worker(ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); LogValues::Count(1); })); worker.join(); EXPECT_THAT(count_logger.GetCounts(), ElementsAre(1)); })); worker.join(); EXPECT_THAT(text_logger.GetLines(), ElementsAre("logged 1")); } TEST(ThreadCrosserTest, MultipleThreadCrossingWithOverride) { LogTextMultiThread logger1; std::thread worker(ThreadCrosser::WrapCall([] { LogTextMultiThread logger2; std::thread worker( ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); worker.join(); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); })); worker.join(); EXPECT_THAT(logger1.GetLines(), ElementsAre()); } TEST(ThreadCrosserTest, DifferentLoggersInSameThread) { BlockingCallbackQueue queue; std::thread worker([&queue] { while (true) { LogTextMultiThread logger; if (!queue.PopAndCall()) { break; } LogText::Log("logged in thread"); EXPECT_THAT(logger.GetLines(), ElementsAre("logged in thread")); } }); LogTextMultiThread logger1; queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); { // It's important for the test case that logger2 overrides logger1, i.e., // that they are both in scope at the same time. LogTextMultiThread logger2; queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 2"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); } queue.Push(ThreadCrosser::WrapCall([] { LogText::Log("logged 3"); })); queue.WaitUntilEmpty(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1", "logged 3")); queue.Terminate(); worker.join(); } TEST(ThreadCrosserTest, ReverseOrderOfLoggersOnStack) { LogTextMultiThread logger1; const auto callback = ThreadCrosser::WrapCall([] { LogText::Log("logged 1"); }); LogTextMultiThread logger2; const auto worker_call = ThreadCrosser::WrapCall([callback] { // In callback(), logger1 overrides logger2, whereas in the main thread // logger2 overrides logger1. callback(); LogText::Log("logged 2"); }); LogTextMultiThread logger3; // Call using a thread. std::thread worker(worker_call); worker.join(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2")); EXPECT_THAT(logger3.GetLines(), ElementsAre()); // Call in the main thread. worker_call(); EXPECT_THAT(logger1.GetLines(), ElementsAre("logged 1", "logged 1")); EXPECT_THAT(logger2.GetLines(), ElementsAre("logged 2", "logged 2")); EXPECT_THAT(logger3.GetLines(), ElementsAre()); } } // namespace capture_thread int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//===-- Function.cpp - Implement the Global object classes ----------------===// // // 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 file implements the Function & GlobalVariable classes for the VMCore // library. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/Constant.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Support/LeakDetector.h" #include "SymbolTableListTraitsImpl.h" using namespace llvm; BasicBlock *ilist_traits<BasicBlock>::createNode() { BasicBlock *Ret = new BasicBlock(); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) { return F->getBasicBlockList(); } Argument *ilist_traits<Argument>::createNode() { Argument *Ret = new Argument(Type::IntTy); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<Argument> &ilist_traits<Argument>::getList(Function *F) { return F->getArgumentList(); } // Explicit instantiations of SymbolTableListTraits since some of the methods // are not in the public header file... template class SymbolTableListTraits<Argument, Function, Function>; template class SymbolTableListTraits<BasicBlock, Function, Function>; //===----------------------------------------------------------------------===// // Argument Implementation //===----------------------------------------------------------------------===// Argument::Argument(const Type *Ty, const std::string &Name, Function *Par) : Value(Ty, Value::ArgumentVal, Name) { Parent = 0; // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (Par) Par->getArgumentList().push_back(this); } // Specialize setName to take care of symbol table majik void Argument::setName(const std::string &name, SymbolTable *ST) { Function *P; assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) && "Invalid symtab argument!"); if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this); Value::setName(name); if (P && hasName()) P->getSymbolTable().insert(this); } void Argument::setParent(Function *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } //===----------------------------------------------------------------------===// // Function Implementation //===----------------------------------------------------------------------===// Function::Function(const FunctionType *Ty, LinkageTypes Linkage, const std::string &name, Module *ParentModule) : GlobalValue(PointerType::get(Ty), Value::FunctionVal, Linkage, name) { BasicBlocks.setItemParent(this); BasicBlocks.setParent(this); ArgumentList.setItemParent(this); ArgumentList.setParent(this); SymTab = new SymbolTable(); assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy) && "LLVM functions cannot return aggregate values!"); // Create the arguments vector, all arguments start out unnamed. for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) { assert(Ty->getParamType(i) != Type::VoidTy && "Cannot have void typed arguments!"); ArgumentList.push_back(new Argument(Ty->getParamType(i))); } // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (ParentModule) ParentModule->getFunctionList().push_back(this); } Function::~Function() { dropAllReferences(); // After this it is safe to delete instructions. // Delete all of the method arguments and unlink from symbol table... ArgumentList.clear(); ArgumentList.setParent(0); delete SymTab; } // Specialize setName to take care of symbol table majik void Function::setName(const std::string &name, SymbolTable *ST) { Module *P; assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) && "Invalid symtab argument!"); if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this); Value::setName(name); if (P && hasName()) P->getSymbolTable().insert(this); } void Function::setParent(Module *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } const FunctionType *Function::getFunctionType() const { return cast<FunctionType>(getType()->getElementType()); } const Type *Function::getReturnType() const { return getFunctionType()->getReturnType(); } void Function::removeFromParent() { getParent()->getFunctionList().remove(this); } void Function::eraseFromParent() { getParent()->getFunctionList().erase(this); } // dropAllReferences() - This function causes all the subinstructions to "let // go" of all references that they are maintaining. This allows one to // 'delete' a whole class at a time, even though there may be circular // references... first all references are dropped, and all use counts go to // zero. Then everything is deleted for real. Note that no operations are // valid on an object that has "dropped all references", except operator // delete. // void Function::dropAllReferences() { for (iterator I = begin(), E = end(); I != E; ++I) I->dropAllReferences(); BasicBlocks.clear(); // Delete all basic blocks... } /// getIntrinsicID - This method returns the ID number of the specified /// function, or Intrinsic::not_intrinsic if the function is not an /// intrinsic, or if the pointer is null. This value is always defined to be /// zero to allow easy checking for whether a function is intrinsic or not. The /// particular intrinsic functions which correspond to this value are defined in /// llvm/Intrinsics.h. /// unsigned Function::getIntrinsicID() const { if (getName().size() < 5 || getName()[4] != '.' || getName()[0] != 'l' || getName()[1] != 'l' || getName()[2] != 'v' || getName()[3] != 'm') return 0; // All intrinsics start with 'llvm.' assert(getName().size() != 5 && "'llvm.' is an invalid intrinsic name!"); // a table of all Alpha intrinsic functions struct { std::string name; // The name of the intrinsic unsigned id; // Its ID number } alpha_intrinsics[] = { { "llvm.alpha.ctlz", Intrinsic::alpha_ctlz }, { "llvm.alpha.cttz", Intrinsic::alpha_cttz }, { "llvm.alpha.ctpop", Intrinsic::alpha_ctpop }, { "llvm.alpha.umulh", Intrinsic::alpha_umulh }, { "llvm.alpha.vecop", Intrinsic::alpha_vecop }, { "llvm.alpha.pup", Intrinsic::alpha_pup }, { "llvm.alpha.bytezap", Intrinsic::alpha_bytezap }, { "llvm.alpha.bytemanip", Intrinsic::alpha_bytemanip }, { "llvm.alpha.dfp_bop", Intrinsic::alpha_dfpbop }, { "llvm.alpha.dfp_uop", Intrinsic::alpha_dfpuop }, { "llvm.alpha.unordered", Intrinsic::alpha_unordered }, { "llvm.alpha.uqtodfp", Intrinsic::alpha_uqtodfp }, { "llvm.alpha.uqtosfp", Intrinsic::alpha_uqtosfp }, { "llvm.alpha.dfptosq", Intrinsic::alpha_dfptosq }, { "llvm.alpha.sfptosq", Intrinsic::alpha_sfptosq }, }; const unsigned num_alpha_intrinsics = sizeof(alpha_intrinsics) / sizeof(*alpha_intrinsics); switch (getName()[5]) { case 'a': if (getName().size() > 11 && std::string(getName().begin()+4, getName().begin()+11) == ".alpha.") for (unsigned i = 0; i < num_alpha_intrinsics; ++i) if (getName() == alpha_intrinsics[i].name) return alpha_intrinsics[i].id; break; case 'd': if (getName() == "llvm.dbg.stoppoint") return Intrinsic::dbg_stoppoint; if (getName() == "llvm.dbg.region.start")return Intrinsic::dbg_region_start; if (getName() == "llvm.dbg.region.end") return Intrinsic::dbg_region_end; if (getName() == "llvm.dbg.func.start") return Intrinsic::dbg_func_start; if (getName() == "llvm.dbg.declare") return Intrinsic::dbg_declare; break; case 'f': if (getName() == "llvm.frameaddress") return Intrinsic::frameaddress; break; case 'g': if (getName() == "llvm.gcwrite") return Intrinsic::gcwrite; if (getName() == "llvm.gcread") return Intrinsic::gcread; if (getName() == "llvm.gcroot") return Intrinsic::gcroot; break; case 'i': if (getName() == "llvm.isunordered") return Intrinsic::isunordered; break; case 'l': if (getName() == "llvm.longjmp") return Intrinsic::longjmp; break; case 'm': if (getName() == "llvm.memcpy") return Intrinsic::memcpy; if (getName() == "llvm.memmove") return Intrinsic::memmove; if (getName() == "llvm.memset") return Intrinsic::memset; break; case 'r': if (getName() == "llvm.returnaddress") return Intrinsic::returnaddress; if (getName() == "llvm.readport") return Intrinsic::readport; if (getName() == "llvm.readio") return Intrinsic::readio; break; case 's': if (getName() == "llvm.setjmp") return Intrinsic::setjmp; if (getName() == "llvm.sigsetjmp") return Intrinsic::sigsetjmp; if (getName() == "llvm.siglongjmp") return Intrinsic::siglongjmp; break; case 'v': if (getName() == "llvm.va_copy") return Intrinsic::vacopy; if (getName() == "llvm.va_end") return Intrinsic::vaend; if (getName() == "llvm.va_start") return Intrinsic::vastart; case 'w': if (getName() == "llvm.writeport") return Intrinsic::writeport; if (getName() == "llvm.writeio") return Intrinsic::writeio; break; } // The "llvm." namespace is reserved! assert(0 && "Unknown LLVM intrinsic function!"); return 0; } // vim: sw=2 ai <commit_msg>Implement a new method<commit_after>//===-- Function.cpp - Implement the Global object classes ----------------===// // // 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 file implements the Function & GlobalVariable classes for the VMCore // library. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/IntrinsicInst.h" #include "llvm/Support/LeakDetector.h" #include "SymbolTableListTraitsImpl.h" using namespace llvm; BasicBlock *ilist_traits<BasicBlock>::createNode() { BasicBlock *Ret = new BasicBlock(); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<BasicBlock> &ilist_traits<BasicBlock>::getList(Function *F) { return F->getBasicBlockList(); } Argument *ilist_traits<Argument>::createNode() { Argument *Ret = new Argument(Type::IntTy); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<Argument> &ilist_traits<Argument>::getList(Function *F) { return F->getArgumentList(); } // Explicit instantiations of SymbolTableListTraits since some of the methods // are not in the public header file... template class SymbolTableListTraits<Argument, Function, Function>; template class SymbolTableListTraits<BasicBlock, Function, Function>; //===----------------------------------------------------------------------===// // Argument Implementation //===----------------------------------------------------------------------===// Argument::Argument(const Type *Ty, const std::string &Name, Function *Par) : Value(Ty, Value::ArgumentVal, Name) { Parent = 0; // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (Par) Par->getArgumentList().push_back(this); } // Specialize setName to take care of symbol table majik void Argument::setName(const std::string &name, SymbolTable *ST) { Function *P; assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) && "Invalid symtab argument!"); if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this); Value::setName(name); if (P && hasName()) P->getSymbolTable().insert(this); } void Argument::setParent(Function *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } //===----------------------------------------------------------------------===// // Function Implementation //===----------------------------------------------------------------------===// Function::Function(const FunctionType *Ty, LinkageTypes Linkage, const std::string &name, Module *ParentModule) : GlobalValue(PointerType::get(Ty), Value::FunctionVal, Linkage, name) { BasicBlocks.setItemParent(this); BasicBlocks.setParent(this); ArgumentList.setItemParent(this); ArgumentList.setParent(this); SymTab = new SymbolTable(); assert((getReturnType()->isFirstClassType() ||getReturnType() == Type::VoidTy) && "LLVM functions cannot return aggregate values!"); // Create the arguments vector, all arguments start out unnamed. for (unsigned i = 0, e = Ty->getNumParams(); i != e; ++i) { assert(Ty->getParamType(i) != Type::VoidTy && "Cannot have void typed arguments!"); ArgumentList.push_back(new Argument(Ty->getParamType(i))); } // Make sure that we get added to a function LeakDetector::addGarbageObject(this); if (ParentModule) ParentModule->getFunctionList().push_back(this); } Function::~Function() { dropAllReferences(); // After this it is safe to delete instructions. // Delete all of the method arguments and unlink from symbol table... ArgumentList.clear(); ArgumentList.setParent(0); delete SymTab; } // Specialize setName to take care of symbol table majik void Function::setName(const std::string &name, SymbolTable *ST) { Module *P; assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) && "Invalid symtab argument!"); if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this); Value::setName(name); if (P && hasName()) P->getSymbolTable().insert(this); } void Function::setParent(Module *parent) { if (getParent()) LeakDetector::addGarbageObject(this); Parent = parent; if (getParent()) LeakDetector::removeGarbageObject(this); } const FunctionType *Function::getFunctionType() const { return cast<FunctionType>(getType()->getElementType()); } const Type *Function::getReturnType() const { return getFunctionType()->getReturnType(); } void Function::removeFromParent() { getParent()->getFunctionList().remove(this); } void Function::eraseFromParent() { getParent()->getFunctionList().erase(this); } // dropAllReferences() - This function causes all the subinstructions to "let // go" of all references that they are maintaining. This allows one to // 'delete' a whole class at a time, even though there may be circular // references... first all references are dropped, and all use counts go to // zero. Then everything is deleted for real. Note that no operations are // valid on an object that has "dropped all references", except operator // delete. // void Function::dropAllReferences() { for (iterator I = begin(), E = end(); I != E; ++I) I->dropAllReferences(); BasicBlocks.clear(); // Delete all basic blocks... } /// getIntrinsicID - This method returns the ID number of the specified /// function, or Intrinsic::not_intrinsic if the function is not an /// intrinsic, or if the pointer is null. This value is always defined to be /// zero to allow easy checking for whether a function is intrinsic or not. The /// particular intrinsic functions which correspond to this value are defined in /// llvm/Intrinsics.h. /// unsigned Function::getIntrinsicID() const { if (getName().size() < 5 || getName()[4] != '.' || getName()[0] != 'l' || getName()[1] != 'l' || getName()[2] != 'v' || getName()[3] != 'm') return 0; // All intrinsics start with 'llvm.' assert(getName().size() != 5 && "'llvm.' is an invalid intrinsic name!"); // a table of all Alpha intrinsic functions struct { std::string name; // The name of the intrinsic unsigned id; // Its ID number } alpha_intrinsics[] = { { "llvm.alpha.ctlz", Intrinsic::alpha_ctlz }, { "llvm.alpha.cttz", Intrinsic::alpha_cttz }, { "llvm.alpha.ctpop", Intrinsic::alpha_ctpop }, { "llvm.alpha.umulh", Intrinsic::alpha_umulh }, { "llvm.alpha.vecop", Intrinsic::alpha_vecop }, { "llvm.alpha.pup", Intrinsic::alpha_pup }, { "llvm.alpha.bytezap", Intrinsic::alpha_bytezap }, { "llvm.alpha.bytemanip", Intrinsic::alpha_bytemanip }, { "llvm.alpha.dfp_bop", Intrinsic::alpha_dfpbop }, { "llvm.alpha.dfp_uop", Intrinsic::alpha_dfpuop }, { "llvm.alpha.unordered", Intrinsic::alpha_unordered }, { "llvm.alpha.uqtodfp", Intrinsic::alpha_uqtodfp }, { "llvm.alpha.uqtosfp", Intrinsic::alpha_uqtosfp }, { "llvm.alpha.dfptosq", Intrinsic::alpha_dfptosq }, { "llvm.alpha.sfptosq", Intrinsic::alpha_sfptosq }, }; const unsigned num_alpha_intrinsics = sizeof(alpha_intrinsics) / sizeof(*alpha_intrinsics); switch (getName()[5]) { case 'a': if (getName().size() > 11 && std::string(getName().begin()+4, getName().begin()+11) == ".alpha.") for (unsigned i = 0; i < num_alpha_intrinsics; ++i) if (getName() == alpha_intrinsics[i].name) return alpha_intrinsics[i].id; break; case 'd': if (getName() == "llvm.dbg.stoppoint") return Intrinsic::dbg_stoppoint; if (getName() == "llvm.dbg.region.start")return Intrinsic::dbg_region_start; if (getName() == "llvm.dbg.region.end") return Intrinsic::dbg_region_end; if (getName() == "llvm.dbg.func.start") return Intrinsic::dbg_func_start; if (getName() == "llvm.dbg.declare") return Intrinsic::dbg_declare; break; case 'f': if (getName() == "llvm.frameaddress") return Intrinsic::frameaddress; break; case 'g': if (getName() == "llvm.gcwrite") return Intrinsic::gcwrite; if (getName() == "llvm.gcread") return Intrinsic::gcread; if (getName() == "llvm.gcroot") return Intrinsic::gcroot; break; case 'i': if (getName() == "llvm.isunordered") return Intrinsic::isunordered; break; case 'l': if (getName() == "llvm.longjmp") return Intrinsic::longjmp; break; case 'm': if (getName() == "llvm.memcpy") return Intrinsic::memcpy; if (getName() == "llvm.memmove") return Intrinsic::memmove; if (getName() == "llvm.memset") return Intrinsic::memset; break; case 'r': if (getName() == "llvm.returnaddress") return Intrinsic::returnaddress; if (getName() == "llvm.readport") return Intrinsic::readport; if (getName() == "llvm.readio") return Intrinsic::readio; break; case 's': if (getName() == "llvm.setjmp") return Intrinsic::setjmp; if (getName() == "llvm.sigsetjmp") return Intrinsic::sigsetjmp; if (getName() == "llvm.siglongjmp") return Intrinsic::siglongjmp; break; case 'v': if (getName() == "llvm.va_copy") return Intrinsic::vacopy; if (getName() == "llvm.va_end") return Intrinsic::vaend; if (getName() == "llvm.va_start") return Intrinsic::vastart; case 'w': if (getName() == "llvm.writeport") return Intrinsic::writeport; if (getName() == "llvm.writeio") return Intrinsic::writeio; break; } // The "llvm." namespace is reserved! assert(0 && "Unknown LLVM intrinsic function!"); return 0; } Value *MemIntrinsic::StripPointerCasts(Value *Ptr) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) { if (CE->getOpcode() == Instruction::Cast) { if (isa<PointerType>(CE->getOperand(0)->getType())) return StripPointerCasts(CE->getOperand(0)); } else if (CE->getOpcode() == Instruction::GetElementPtr) { for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) if (!CE->getOperand(i)->isNullValue()) return Ptr; return StripPointerCasts(CE->getOperand(0)); } return Ptr; } if (CastInst *CI = dyn_cast<CastInst>(Ptr)) { if (isa<PointerType>(CI->getOperand(0)->getType())) return StripPointerCasts(CI->getOperand(0)); } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) if (!isa<Constant>(CE->getOperand(i)) || !cast<Constant>(CE->getOperand(i))->isNullValue()) return Ptr; return StripPointerCasts(CE->getOperand(0)); } return Ptr; } // vim: sw=2 ai <|endoftext|>
<commit_before>//===-- Metadata.cpp - Implement Metadata classes -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Metadata classes. // //===----------------------------------------------------------------------===// #include "LLVMContextImpl.h" #include "llvm/Metadata.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "SymbolTableListTraitsImpl.h" using namespace llvm; //===----------------------------------------------------------------------===// //MetadataBase implementation // /// resizeOperands - Metadata keeps track of other metadata uses using /// OperandList. Resize this list to hold anticipated number of metadata /// operands. void MetadataBase::resizeOperands(unsigned NumOps) { unsigned e = getNumOperands(); if (NumOps == 0) { NumOps = e*2; if (NumOps < 2) NumOps = 2; } else if (NumOps > NumOperands) { // No resize needed. if (ReservedSpace >= NumOps) return; } else if (NumOps == NumOperands) { if (ReservedSpace == NumOps) return; } else { return; } ReservedSpace = NumOps; Use *OldOps = OperandList; Use *NewOps = allocHungoffUses(NumOps); std::copy(OldOps, OldOps + e, NewOps); OperandList = NewOps; if (OldOps) Use::zap(OldOps, OldOps + e, true); } //===----------------------------------------------------------------------===// //MDString implementation // MDString *MDString::get(LLVMContext &Context, const StringRef &Str) { LLVMContextImpl *pImpl = Context.pImpl; sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); StringMapEntry<MDString *> &Entry = pImpl->MDStringCache.GetOrCreateValue(Str); MDString *&S = Entry.getValue(); if (!S) S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength()); return S; } //===----------------------------------------------------------------------===// //MDNode implementation // MDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { NumOperands = 0; resizeOperands(NumVals); for (unsigned i = 0; i != NumVals; ++i) { // Only record metadata uses. if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i])) OperandList[NumOperands++] = MB; else if(Vals[i] && Vals[i]->getType()->getTypeID() == Type::MetadataTyID) OperandList[NumOperands++] = Vals[i]; Node.push_back(ElementVH(Vals[i], this)); } } void MDNode::Profile(FoldingSetNodeID &ID) const { for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I) ID.AddPointer(*I); } MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; for (unsigned i = 0; i != NumVals; ++i) ID.AddPointer(Vals[i]); pImpl->ConstantsLock.reader_acquire(); void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); pImpl->ConstantsLock.reader_release(); if (!N) { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { // InsertPoint will have been set by the FindNodeOrInsertPos call. N = new MDNode(Context, Vals, NumVals); pImpl->MDNodeSet.InsertNode(N, InsertPoint); } } return N; } /// dropAllReferences - Remove all uses and clear node vector. void MDNode::dropAllReferences() { User::dropAllReferences(); Node.clear(); } MDNode::~MDNode() { getType()->getContext().pImpl->MDNodeSet.RemoveNode(this); dropAllReferences(); } // Replace value from this node's element list. void MDNode::replaceElement(Value *From, Value *To) { if (From == To || !getType()) return; LLVMContext &Context = getType()->getContext(); LLVMContextImpl *pImpl = Context.pImpl; // Find value. This is a linear search, do something if it consumes // lot of time. It is possible that to have multiple instances of // From in this MDNode's element list. SmallVector<unsigned, 4> Indexes; unsigned Index = 0; for (SmallVector<ElementVH, 4>::iterator I = Node.begin(), E = Node.end(); I != E; ++I, ++Index) { Value *V = *I; if (V && V == From) Indexes.push_back(Index); } if (Indexes.empty()) return; // Remove "this" from the context map. { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); pImpl->MDNodeSet.RemoveNode(this); } // MDNode only lists metadata elements in operand list, because MDNode // used by MDNode is considered a valid use. However on the side, MDNode // using a non-metadata value is not considered a "use" of non-metadata // value. SmallVector<unsigned, 4> OpIndexes; unsigned OpIndex = 0; for (User::op_iterator OI = op_begin(), OE = op_end(); OI != OE; ++OI, OpIndex++) { if (*OI == From) OpIndexes.push_back(OpIndex); } if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) { for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(), OE = OpIndexes.end(); OI != OE; ++OI) setOperand(*OI, MDTo); } else { for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(), OE = OpIndexes.end(); OI != OE; ++OI) setOperand(*OI, 0); } // Replace From element(s) in place. for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); I != E; ++I) { unsigned Index = *I; Node[Index] = ElementVH(To, this); } // Insert updated "this" into the context's folding node set. // If a node with same element list already exist then before inserting // updated "this" into the folding node set, replace all uses of existing // node with updated "this" node. FoldingSetNodeID ID; Profile(ID); pImpl->ConstantsLock.reader_acquire(); void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); pImpl->ConstantsLock.reader_release(); if (N) { N->replaceAllUsesWith(this); delete N; N = 0; } { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { // InsertPoint will have been set by the FindNodeOrInsertPos call. N = this; pImpl->MDNodeSet.InsertNode(N, InsertPoint); } } } //===----------------------------------------------------------------------===// //NamedMDNode implementation // NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N, MetadataBase*const* MDs, unsigned NumMDs, Module *ParentModule) : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) { setName(N); NumOperands = 0; resizeOperands(NumMDs); for (unsigned i = 0; i != NumMDs; ++i) { if (MDs[i]) OperandList[NumOperands++] = MDs[i]; Node.push_back(WeakMetadataVH(MDs[i])); } if (ParentModule) ParentModule->getNamedMDList().push_back(this); } NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) { assert (NMD && "Invalid source NamedMDNode!"); SmallVector<MetadataBase *, 4> Elems; for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) Elems.push_back(NMD->getElement(i)); return new NamedMDNode(NMD->getContext(), NMD->getName().data(), Elems.data(), Elems.size(), M); } /// eraseFromParent - Drop all references and remove the node from parent /// module. void NamedMDNode::eraseFromParent() { getParent()->getNamedMDList().erase(this); } /// dropAllReferences - Remove all uses and clear node vector. void NamedMDNode::dropAllReferences() { User::dropAllReferences(); Node.clear(); } NamedMDNode::~NamedMDNode() { dropAllReferences(); } <commit_msg>Take lock before removing a node from MDNodeSet.<commit_after>//===-- Metadata.cpp - Implement Metadata classes -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Metadata classes. // //===----------------------------------------------------------------------===// #include "LLVMContextImpl.h" #include "llvm/Metadata.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "SymbolTableListTraitsImpl.h" using namespace llvm; //===----------------------------------------------------------------------===// //MetadataBase implementation // /// resizeOperands - Metadata keeps track of other metadata uses using /// OperandList. Resize this list to hold anticipated number of metadata /// operands. void MetadataBase::resizeOperands(unsigned NumOps) { unsigned e = getNumOperands(); if (NumOps == 0) { NumOps = e*2; if (NumOps < 2) NumOps = 2; } else if (NumOps > NumOperands) { // No resize needed. if (ReservedSpace >= NumOps) return; } else if (NumOps == NumOperands) { if (ReservedSpace == NumOps) return; } else { return; } ReservedSpace = NumOps; Use *OldOps = OperandList; Use *NewOps = allocHungoffUses(NumOps); std::copy(OldOps, OldOps + e, NewOps); OperandList = NewOps; if (OldOps) Use::zap(OldOps, OldOps + e, true); } //===----------------------------------------------------------------------===// //MDString implementation // MDString *MDString::get(LLVMContext &Context, const StringRef &Str) { LLVMContextImpl *pImpl = Context.pImpl; sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); StringMapEntry<MDString *> &Entry = pImpl->MDStringCache.GetOrCreateValue(Str); MDString *&S = Entry.getValue(); if (!S) S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength()); return S; } //===----------------------------------------------------------------------===// //MDNode implementation // MDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { NumOperands = 0; resizeOperands(NumVals); for (unsigned i = 0; i != NumVals; ++i) { // Only record metadata uses. if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i])) OperandList[NumOperands++] = MB; else if(Vals[i] && Vals[i]->getType()->getTypeID() == Type::MetadataTyID) OperandList[NumOperands++] = Vals[i]; Node.push_back(ElementVH(Vals[i], this)); } } void MDNode::Profile(FoldingSetNodeID &ID) const { for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I) ID.AddPointer(*I); } MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; for (unsigned i = 0; i != NumVals; ++i) ID.AddPointer(Vals[i]); pImpl->ConstantsLock.reader_acquire(); void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); pImpl->ConstantsLock.reader_release(); if (!N) { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { // InsertPoint will have been set by the FindNodeOrInsertPos call. N = new MDNode(Context, Vals, NumVals); pImpl->MDNodeSet.InsertNode(N, InsertPoint); } } return N; } /// dropAllReferences - Remove all uses and clear node vector. void MDNode::dropAllReferences() { User::dropAllReferences(); Node.clear(); } MDNode::~MDNode() { { LLVMContextImpl *pImpl = getType()->getContext().pImpl; sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); pImpl->MDNodeSet.RemoveNode(this); } dropAllReferences(); } // Replace value from this node's element list. void MDNode::replaceElement(Value *From, Value *To) { if (From == To || !getType()) return; LLVMContext &Context = getType()->getContext(); LLVMContextImpl *pImpl = Context.pImpl; // Find value. This is a linear search, do something if it consumes // lot of time. It is possible that to have multiple instances of // From in this MDNode's element list. SmallVector<unsigned, 4> Indexes; unsigned Index = 0; for (SmallVector<ElementVH, 4>::iterator I = Node.begin(), E = Node.end(); I != E; ++I, ++Index) { Value *V = *I; if (V && V == From) Indexes.push_back(Index); } if (Indexes.empty()) return; // Remove "this" from the context map. { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); pImpl->MDNodeSet.RemoveNode(this); } // MDNode only lists metadata elements in operand list, because MDNode // used by MDNode is considered a valid use. However on the side, MDNode // using a non-metadata value is not considered a "use" of non-metadata // value. SmallVector<unsigned, 4> OpIndexes; unsigned OpIndex = 0; for (User::op_iterator OI = op_begin(), OE = op_end(); OI != OE; ++OI, OpIndex++) { if (*OI == From) OpIndexes.push_back(OpIndex); } if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) { for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(), OE = OpIndexes.end(); OI != OE; ++OI) setOperand(*OI, MDTo); } else { for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(), OE = OpIndexes.end(); OI != OE; ++OI) setOperand(*OI, 0); } // Replace From element(s) in place. for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); I != E; ++I) { unsigned Index = *I; Node[Index] = ElementVH(To, this); } // Insert updated "this" into the context's folding node set. // If a node with same element list already exist then before inserting // updated "this" into the folding node set, replace all uses of existing // node with updated "this" node. FoldingSetNodeID ID; Profile(ID); pImpl->ConstantsLock.reader_acquire(); void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); pImpl->ConstantsLock.reader_release(); if (N) { N->replaceAllUsesWith(this); delete N; N = 0; } { sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock); N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { // InsertPoint will have been set by the FindNodeOrInsertPos call. N = this; pImpl->MDNodeSet.InsertNode(N, InsertPoint); } } } //===----------------------------------------------------------------------===// //NamedMDNode implementation // NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N, MetadataBase*const* MDs, unsigned NumMDs, Module *ParentModule) : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) { setName(N); NumOperands = 0; resizeOperands(NumMDs); for (unsigned i = 0; i != NumMDs; ++i) { if (MDs[i]) OperandList[NumOperands++] = MDs[i]; Node.push_back(WeakMetadataVH(MDs[i])); } if (ParentModule) ParentModule->getNamedMDList().push_back(this); } NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) { assert (NMD && "Invalid source NamedMDNode!"); SmallVector<MetadataBase *, 4> Elems; for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) Elems.push_back(NMD->getElement(i)); return new NamedMDNode(NMD->getContext(), NMD->getName().data(), Elems.data(), Elems.size(), M); } /// eraseFromParent - Drop all references and remove the node from parent /// module. void NamedMDNode::eraseFromParent() { getParent()->getNamedMDList().erase(this); } /// dropAllReferences - Remove all uses and clear node vector. void NamedMDNode::dropAllReferences() { User::dropAllReferences(); Node.clear(); } NamedMDNode::~NamedMDNode() { dropAllReferences(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "mitkExtractSliceFilter.h" #include <vtkImageData.h> #include <vtkSmartPointer.h> mitk::ExtractSliceFilter::ExtractSliceFilter(){ m_Reslicer = vtkSmartPointer<vtkImageReslice>::New(); } mitk::ExtractSliceFilter::~ExtractSliceFilter(){ } void mitk::ExtractSliceFilter::GenerateData(){ mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() ); if ( !input){ MITK_ERROR << "mitk::ExtractSliceFilter: No input image available. Please set the input!" << std::endl; itkExceptionMacro("mitk::ExtractSliceFilter: No input image available. Please set the input!"); return; } if(!m_WorldGeometry){ MITK_ERROR << "mitk::ExtractSliceFilter: No Geometry for reslicing available." << std::endl; itkExceptionMacro("mitk::ExtractSliceFilter: No Geometry for reslicing available."); return; } /********** #BEGIN setup vtkImageRslice properties***********/ m_Reslicer->SetInput(input->GetVtkImageData()); /*setup the plane where vktImageReslice extracts the slice*/ //ResliceAxesOrigin is the ancor point of the plane double origin[3]; itk2vtk(m_WorldGeometry->GetOrigin(), origin); m_Reslicer->SetResliceAxesOrigin(origin); //the cosines define the plane: x and y are the direction vectors, n is the planes normal double cosines[9] = { 1.0, 0.0, 0.0, //x 0.0, -1.0, 0.0, //y 0.0, 0.0, 1.0 //n }; m_Reslicer->SetResliceAxesDirectionCosines(cosines); //we only have one slice, not a volume m_Reslicer->SetOutputDimensionality(2); //the default interpolation used by mitk m_Reslicer->SetInterpolationModeToNearestNeighbor(); //start the pipeline m_Reslicer->Modified(); m_Reslicer->Update(); /********** #END setup vtkImageRslice properties***********/ /********** #BEGIN Get the slice from vtkImageReslice and convert it to mitk Image***********/ vtkImageData* reslicedImage; reslicedImage = m_Reslicer->GetOutput(); if(!reslicedImage) { itkWarningMacro(<<"Reslicer returned empty image"); return; } mitk::Image::Pointer resultImage = this->GetOutput(); //initialize resultimage with the specs of the vtkImageData object returned from vtkImageReslice resultImage->Initialize(reslicedImage); ////transfer the voxel data resultImage->SetVolume(reslicedImage->GetScalarPointer()); //set the geometry from current worldgeometry for the reusultimage AffineGeometryFrame3D::Pointer originalGeometryAGF = m_WorldGeometry->Clone(); Geometry2D::Pointer originalGeometry = dynamic_cast<Geometry2D*>( originalGeometryAGF.GetPointer() ); originalGeometry->ChangeImageGeometryConsideringOriginOffset(true); resultImage->SetGeometry( originalGeometry ); resultImage->GetGeometry()->TransferItkToVtkTransform(); resultImage->GetGeometry()->Modified(); /********** #END Get the slice from vtkImageReslice and convert it to mitk Image***********/ }<commit_msg>reslicesAxesCosines set from plane<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "mitkExtractSliceFilter.h" #include <vtkImageData.h> #include <vtkSmartPointer.h> mitk::ExtractSliceFilter::ExtractSliceFilter(){ m_Reslicer = vtkSmartPointer<vtkImageReslice>::New(); } mitk::ExtractSliceFilter::~ExtractSliceFilter(){ } void mitk::ExtractSliceFilter::GenerateData(){ mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() ); if ( !input){ MITK_ERROR << "mitk::ExtractSliceFilter: No input image available. Please set the input!" << std::endl; itkExceptionMacro("mitk::ExtractSliceFilter: No input image available. Please set the input!"); return; } if(!m_WorldGeometry){ MITK_ERROR << "mitk::ExtractSliceFilter: No Geometry for reslicing available." << std::endl; itkExceptionMacro("mitk::ExtractSliceFilter: No Geometry for reslicing available."); return; } /********** #BEGIN setup vtkImageRslice properties***********/ m_Reslicer->SetInput(input->GetVtkImageData()); /*setup the plane where vktImageReslice extracts the slice*/ //ResliceAxesOrigin is the ancor point of the plane double origin[3]; itk2vtk(m_WorldGeometry->GetOrigin(), origin); m_Reslicer->SetResliceAxesOrigin(origin); //the cosines define the plane: x and y are the direction vectors, n is the planes normal double cosines[9];// = { 1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 1.0 }; Vector3D right, bottom; right = m_WorldGeometry->GetAxisVector(0); right.Normalize(); vnl2vtk(right.GetVnlVector(), cosines); bottom = m_WorldGeometry->GetAxisVector(1); bottom.Normalize(); vnl2vtk(bottom.GetVnlVector(), cosines + 3); Vector3D normalVector = CrossProduct(m_WorldGeometry->GetAxisVector(0), m_WorldGeometry->GetAxisVector(1)); normalVector.Normalize(); vnl2vtk(normalVector.GetVnlVector(), cosines + 6); m_Reslicer->SetResliceAxesDirectionCosines(cosines); //we only have one slice, not a volume m_Reslicer->SetOutputDimensionality(2); //the default interpolation used by mitk m_Reslicer->SetInterpolationModeToNearestNeighbor(); //start the pipeline m_Reslicer->Modified(); m_Reslicer->Update(); /********** #END setup vtkImageRslice properties***********/ /********** #BEGIN Get the slice from vtkImageReslice and convert it to mitk Image***********/ vtkImageData* reslicedImage; reslicedImage = m_Reslicer->GetOutput(); if(!reslicedImage) { itkWarningMacro(<<"Reslicer returned empty image"); return; } mitk::Image::Pointer resultImage = this->GetOutput(); //initialize resultimage with the specs of the vtkImageData object returned from vtkImageReslice resultImage->Initialize(reslicedImage); ////transfer the voxel data resultImage->SetVolume(reslicedImage->GetScalarPointer()); //set the geometry from current worldgeometry for the reusultimage AffineGeometryFrame3D::Pointer originalGeometryAGF = m_WorldGeometry->Clone(); Geometry2D::Pointer originalGeometry = dynamic_cast<Geometry2D*>( originalGeometryAGF.GetPointer() ); originalGeometry->ChangeImageGeometryConsideringOriginOffset(true); resultImage->SetGeometry( originalGeometry ); resultImage->GetGeometry()->TransferItkToVtkTransform(); resultImage->GetGeometry()->Modified(); /********** #END Get the slice from vtkImageReslice and convert it to mitk Image***********/ }<|endoftext|>
<commit_before>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <mutex> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. File *find(StringRef name, bool dataSymbolOnly) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; if (ci->getError()) return nullptr; // Don't return a member already returned ErrorOr<StringRef> buf = (*ci)->getBuffer(); if (!buf) return nullptr; const char *memberStart = buf->data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(ci, name)) return nullptr; _membersInstantiated.insert(memberStart); std::unique_ptr<File> result; if (instantiateMember(ci, result)) return nullptr; File *file = result.get(); _filesReturned.push_back(std::move(result)); // Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive return file; } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const AtomVector<DefinedAtom> &defined() const override { return _noDefinedAtoms; } const AtomVector<UndefinedAtom> &undefined() const override { return _noUndefinedAtoms; } const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { return _noSharedLibraryAtoms; } const AtomVector<AbsoluteAtom> &absolute() const override { return _noAbsoluteAtoms; } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; return std::error_code(); } private: std::error_code instantiateMember(Archive::child_iterator cOrErr, std::unique_ptr<File> &result) const { if (std::error_code ec = cOrErr->getError()) return ec; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); ErrorOr<std::unique_ptr<File>> fileOrErr = _registry.loadFile(std::move(memberMB)); if (std::error_code ec = fileOrErr.getError()) return ec; result = std::move(fileOrErr.get()); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(Archive::child_iterator cOrErr, StringRef symbol) const { if (cOrErr->getError()) return false; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> buf = (*member)->getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. ErrorOr<StringRef> name = sym.getName(); if (!name) return false; if (*name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. SymbolRef::Type type = sym.getType(); if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", (*member)->getBuffer()->data()) << "'" << name << "'\n"); _symbolMemberMap.insert(std::make_pair(name, member)); } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; MemberMap _symbolMemberMap; InstantiatedSet _membersInstantiated; bool _logLoading; std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; std::mutex _mutex; std::vector<std::unique_ptr<File>> _filesReturned; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, MemoryBufferRef) const override { return magic == llvm::sys::fs::file_magic::archive; } ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<File> ret = llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading); return std::move(ret); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld <commit_msg>Remove dead code.<commit_after>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "lld/Core/LinkingContext.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: FileArchive(std::unique_ptr<MemoryBuffer> mb, const Registry &reg, StringRef path, bool logLoading) : ArchiveLibraryFile(path), _mb(std::shared_ptr<MemoryBuffer>(mb.release())), _registry(reg), _logLoading(logLoading) {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. File *find(StringRef name, bool dataSymbolOnly) override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; if (ci->getError()) return nullptr; // Don't return a member already returned ErrorOr<StringRef> buf = (*ci)->getBuffer(); if (!buf) return nullptr; const char *memberStart = buf->data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly && !isDataSymbol(ci, name)) return nullptr; _membersInstantiated.insert(memberStart); std::unique_ptr<File> result; if (instantiateMember(ci, result)) return nullptr; File *file = result.get(); _filesReturned.push_back(std::move(result)); // Give up the file pointer. It was stored and will be destroyed with destruction of FileArchive return file; } /// \brief parse each member std::error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) override { if (std::error_code ec = parse()) return ec; for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { std::unique_ptr<File> file; if (std::error_code ec = instantiateMember(mf, file)) return ec; result.push_back(std::move(file)); } return std::error_code(); } const AtomVector<DefinedAtom> &defined() const override { return _noDefinedAtoms; } const AtomVector<UndefinedAtom> &undefined() const override { return _noUndefinedAtoms; } const AtomVector<SharedLibraryAtom> &sharedLibrary() const override { return _noSharedLibraryAtoms; } const AtomVector<AbsoluteAtom> &absolute() const override { return _noAbsoluteAtoms; } protected: std::error_code doParse() override { // Make Archive object which will be owned by FileArchive object. std::error_code ec; _archive.reset(new Archive(_mb->getMemBufferRef(), ec)); if (ec) return ec; if ((ec = buildTableOfContents())) return ec; return std::error_code(); } private: std::error_code instantiateMember(Archive::child_iterator cOrErr, std::unique_ptr<File> &result) const { if (std::error_code ec = cOrErr->getError()) return ec; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> mbOrErr = (*member)->getMemoryBufferRef(); if (std::error_code ec = mbOrErr.getError()) return ec; llvm::MemoryBufferRef mb = mbOrErr.get(); std::string memberPath = (_archive->getFileName() + "(" + mb.getBufferIdentifier() + ")").str(); if (_logLoading) llvm::errs() << memberPath << "\n"; std::unique_ptr<MemoryBuffer> memberMB(MemoryBuffer::getMemBuffer( mb.getBuffer(), mb.getBufferIdentifier(), false)); ErrorOr<std::unique_ptr<File>> fileOrErr = _registry.loadFile(std::move(memberMB)); if (std::error_code ec = fileOrErr.getError()) return ec; result = std::move(fileOrErr.get()); if (std::error_code ec = result->parse()) return ec; result->setArchivePath(_archive->getFileName()); // The memory buffer is co-owned by the archive file and the children, // so that the bufffer is deallocated when all the members are destructed. result->setSharedMemoryBuffer(_mb); return std::error_code(); } // Parses the given memory buffer as an object file, and returns true // code if the given symbol is a data symbol. If the symbol is not a data // symbol or does not exist, returns false. bool isDataSymbol(Archive::child_iterator cOrErr, StringRef symbol) const { if (cOrErr->getError()) return false; Archive::child_iterator member = cOrErr->get(); ErrorOr<llvm::MemoryBufferRef> buf = (*member)->getMemoryBufferRef(); if (buf.getError()) return false; std::unique_ptr<MemoryBuffer> mb(MemoryBuffer::getMemBuffer( buf.get().getBuffer(), buf.get().getBufferIdentifier(), false)); auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef())); if (objOrErr.getError()) return false; std::unique_ptr<ObjectFile> obj = std::move(objOrErr.get()); for (SymbolRef sym : obj->symbols()) { // Skip until we find the symbol. ErrorOr<StringRef> name = sym.getName(); if (!name) return false; if (*name != symbol) continue; uint32_t flags = sym.getFlags(); if (flags <= SymbolRef::SF_Undefined) continue; // Returns true if it's a data symbol. SymbolRef::Type type = sym.getType(); if (type == SymbolRef::ST_Data) return true; } return false; } std::error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (const Archive::Symbol &sym : _archive->symbols()) { StringRef name = sym.getName(); ErrorOr<Archive::child_iterator> memberOrErr = sym.getMember(); if (std::error_code ec = memberOrErr.getError()) return ec; Archive::child_iterator member = memberOrErr.get(); DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", (*member)->getBuffer()->data()) << "'" << name << "'\n"); _symbolMemberMap.insert(std::make_pair(name, member)); } return std::error_code(); } typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; std::shared_ptr<MemoryBuffer> _mb; const Registry &_registry; std::unique_ptr<Archive> _archive; MemberMap _symbolMemberMap; InstantiatedSet _membersInstantiated; bool _logLoading; std::vector<std::unique_ptr<MemoryBuffer>> _memberBuffers; std::vector<std::unique_ptr<File>> _filesReturned; }; class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} bool canParse(file_magic magic, MemoryBufferRef) const override { return magic == llvm::sys::fs::file_magic::archive; } ErrorOr<std::unique_ptr<File>> loadFile(std::unique_ptr<MemoryBuffer> mb, const Registry &reg) const override { StringRef path = mb->getBufferIdentifier(); std::unique_ptr<File> ret = llvm::make_unique<FileArchive>(std::move(mb), reg, path, _logLoading); return std::move(ret); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld <|endoftext|>
<commit_before>// // main.cpp // ResumeBuilder // // Created by Terry Black on 9/17/15. #include <iostream> using namespace std; int numOfGoals; int numOfSkills; int numOfAwards; int numOfJobs; int numOfDegrees; string age; string phoneNumber; string schoolName; string major; string concentration; string minor; string gradDate; string communityInvolvement; string name; string address; string email; string credentials; bool majorBool; bool minorBool; bool gradDateBool; int main() { cout << "Hello, Welcome to Resume Builder!\n"; cout << "Input your name:\n"; getline (cin, Name); cout << "How old are you?\n"; getline (cin, Age); cout << "What is your Address?\n"; getline (cin, Address); cout << "What is your Phone Number?\n"; getline (cin, PhoneNumber); cout << "What is your email?\n"; getline (cin, Email); cout << "What is the name of your School?\n"; getline (cin, SchoolName); cout << "What is your Major? If you don't have one, type: 'none'\n"; getline (cin, Major); if (Major == "none") { MajorBool = false; }else { MajorBool = true; } cout << "What is your Minor? If you don't have one, type 'none'\n"; getline (cin, Minor); if (Minor == "none") { MinorBool = false; } else { MinorBool = true; } cout << "What is your graduation date? If you are still enrolled or something, type: 'none'\n"; getline (cin, GradDate); if (GradDate == "none") { GradDateBool = false; } else { GradDateBool = true; } cout << "How many degrees do you have?\n"; cin >> numOfDegrees; return 0; } <commit_msg>Update ResumeBuilder.cpp<commit_after>#include <iostream> using namespace std; int numOfGoals; int numOfSkills; int numOfAwards; int numOfJobs; int numOfDegrees; string age; string phoneNumber; string schoolName; string majorr; string concentration; string minorr; string gradDate; string communityInvolvement; string name; string address; string email; string credentials; bool majorBool; bool minorBool; bool gradDateBool; int main() { cout << "Hello, Welcome to Resume Builder!\n"; cout << "Input your name:\n"; getline (cin, name); cout << "How old are you?\n"; getline (cin, age); cout << "What is your Address?\n"; getline (cin, address); cout << "What is your Phone Number?\n"; getline (cin, phoneNumber); cout << "What is your email?\n"; getline (cin, email); cout << "What is the name of your School?\n"; getline (cin, schoolName); cout << "What is your Major? If you don't have one, type: 'none'\n"; getline (cin, majorr); if (majorr == "none") { majorBool = false; }else { majorBool = true; } cout << "What is your Minor? If you don't have one, type 'none'\n"; getline (cin, minorr); if (minorr == "none") { minorBool = false; } else { minorBool = true; } cout << "What is your graduation date? If you are still enrolled or something, type: 'none'\n"; getline (cin, gradDate); if (gradDate == "none") { gradDateBool = false; } else { gradDateBool = true; } cout << "How many degrees do you have?\n"; cin >> numOfDegrees; return 0; } <|endoftext|>
<commit_before>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: virtual ~FileArchive() {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. const File *find(StringRef name, bool dataSymbolOnly) const override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; // Don't return a member already returned const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly) { std::unique_ptr<MemoryBuffer> buff; if (ci->getMemoryBuffer(buff, true)) return nullptr; if (isDataSymbol(std::move(buff), name)) return nullptr; } std::vector<std::unique_ptr<File>> result; if (instantiateMember(ci, result)) return nullptr; assert(result.size() == 1); // give up the pointer so that this object no longer manages it return result[0].release(); } /// \brief Load all members of the archive? virtual bool isWholeArchive() const { return _isWholeArchive; } /// \brief parse each member virtual error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) const override { for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { if (error_code ec = instantiateMember(mf, result)) return ec; } return error_code::success(); } const atom_collection<DefinedAtom> &defined() const override { return _definedAtoms; } const atom_collection<UndefinedAtom> &undefined() const override { return _undefinedAtoms; } const atom_collection<SharedLibraryAtom> &sharedLibrary() const override { return _sharedLibraryAtoms; } const atom_collection<AbsoluteAtom> &absolute() const override { return _absoluteAtoms; } protected: error_code instantiateMember(Archive::child_iterator member, std::vector<std::unique_ptr<File>> &result) const { std::unique_ptr<MemoryBuffer> mb; if (error_code ec = member->getMemoryBuffer(mb, true)) return ec; if (_logLoading) llvm::outs() << mb->getBufferIdentifier() << "\n"; _registry.parseFile(mb, result); const char *memberStart = member->getBuffer().data(); _membersInstantiated.insert(memberStart); return error_code::success(); } error_code isDataSymbol(std::unique_ptr<MemoryBuffer> mb, StringRef symbol) const { auto objOrErr(ObjectFile::createObjectFile(mb.release())); if (auto ec = objOrErr.getError()) return ec; std::unique_ptr<ObjectFile> obj(objOrErr.get()); SymbolRef::Type symtype; uint32_t symflags; symbol_iterator ibegin = obj->symbol_begin(); symbol_iterator iend = obj->symbol_end(); StringRef symbolname; for (symbol_iterator i = ibegin; i != iend; ++i) { error_code ec; // Get symbol name if ((ec = (i->getName(symbolname)))) return ec; if (symbolname != symbol) continue; // Get symbol flags symflags = i->getFlags(); if (symflags <= SymbolRef::SF_Undefined) continue; // Get Symbol Type if ((ec = (i->getType(symtype)))) return ec; if (symtype == SymbolRef::ST_Data) { return error_code::success(); } } return object_error::parse_failed; } private: typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; const Registry &_registry; std::unique_ptr<Archive> _archive; mutable MemberMap _symbolMemberMap; mutable InstantiatedSet _membersInstantiated; atom_collection_vector<DefinedAtom> _definedAtoms; atom_collection_vector<UndefinedAtom> _undefinedAtoms; atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms; atom_collection_vector<AbsoluteAtom> _absoluteAtoms; bool _isWholeArchive; bool _logLoading; public: /// only subclasses of ArchiveLibraryFile can be instantiated FileArchive(const Registry &registry, Archive *archive, StringRef path, bool isWholeArchive, bool logLoading) : ArchiveLibraryFile(path), _registry(registry), _archive(std::move(archive)), _isWholeArchive(isWholeArchive), _logLoading(logLoading) {} error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (auto i = _archive->symbol_begin(), e = _archive->symbol_end(); i != e; ++i) { StringRef name; error_code ec; Archive::child_iterator member; if ((ec = i->getName(name))) return ec; if ((ec = i->getMember(member))) return ec; DEBUG_WITH_TYPE( "FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", member->getBuffer().data()) << "'" << name << "'\n"); _symbolMemberMap[name] = member; } return error_code::success(); } }; // class FileArchive class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} virtual bool canParse(file_magic magic, StringRef, const MemoryBuffer &) const override { return (magic == llvm::sys::fs::file_magic::archive); } virtual error_code parseFile(std::unique_ptr<MemoryBuffer> &mb, const Registry &reg, std::vector<std::unique_ptr<File>> &result) const override { // Make Archive object which will be owned by FileArchive object. error_code ec; Archive *archive = new Archive(mb.get(), ec); if (ec) return ec; StringRef path = mb->getBufferIdentifier(); // Construct FileArchive object. std::unique_ptr<FileArchive> file( new FileArchive(reg, archive, path, false, _logLoading)); ec = file->buildTableOfContents(); if (ec) return ec; // Transfer ownership of memory buffer to Archive object. mb.release(); result.push_back(std::move(file)); return error_code::success(); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld <commit_msg>Make the variable scope narrower. No functionality change.<commit_after>//===- lib/ReaderWriter/FileArchive.cpp -----------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Core/ArchiveLibraryFile.h" #include "lld/Core/LLVM.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <set> #include <unordered_map> using llvm::object::Archive; using llvm::object::ObjectFile; using llvm::object::SymbolRef; using llvm::object::symbol_iterator; using llvm::object::object_error; namespace lld { namespace { /// \brief The FileArchive class represents an Archive Library file class FileArchive : public lld::ArchiveLibraryFile { public: virtual ~FileArchive() {} /// \brief Check if any member of the archive contains an Atom with the /// specified name and return the File object for that member, or nullptr. const File *find(StringRef name, bool dataSymbolOnly) const override { auto member = _symbolMemberMap.find(name); if (member == _symbolMemberMap.end()) return nullptr; Archive::child_iterator ci = member->second; // Don't return a member already returned const char *memberStart = ci->getBuffer().data(); if (_membersInstantiated.count(memberStart)) return nullptr; if (dataSymbolOnly) { std::unique_ptr<MemoryBuffer> buff; if (ci->getMemoryBuffer(buff, true)) return nullptr; if (isDataSymbol(std::move(buff), name)) return nullptr; } std::vector<std::unique_ptr<File>> result; if (instantiateMember(ci, result)) return nullptr; assert(result.size() == 1); // give up the pointer so that this object no longer manages it return result[0].release(); } /// \brief Load all members of the archive? virtual bool isWholeArchive() const { return _isWholeArchive; } /// \brief parse each member virtual error_code parseAllMembers(std::vector<std::unique_ptr<File>> &result) const override { for (auto mf = _archive->child_begin(), me = _archive->child_end(); mf != me; ++mf) { if (error_code ec = instantiateMember(mf, result)) return ec; } return error_code::success(); } const atom_collection<DefinedAtom> &defined() const override { return _definedAtoms; } const atom_collection<UndefinedAtom> &undefined() const override { return _undefinedAtoms; } const atom_collection<SharedLibraryAtom> &sharedLibrary() const override { return _sharedLibraryAtoms; } const atom_collection<AbsoluteAtom> &absolute() const override { return _absoluteAtoms; } protected: error_code instantiateMember(Archive::child_iterator member, std::vector<std::unique_ptr<File>> &result) const { std::unique_ptr<MemoryBuffer> mb; if (error_code ec = member->getMemoryBuffer(mb, true)) return ec; if (_logLoading) llvm::outs() << mb->getBufferIdentifier() << "\n"; _registry.parseFile(mb, result); const char *memberStart = member->getBuffer().data(); _membersInstantiated.insert(memberStart); return error_code::success(); } error_code isDataSymbol(std::unique_ptr<MemoryBuffer> mb, StringRef symbol) const { auto objOrErr(ObjectFile::createObjectFile(mb.release())); if (auto ec = objOrErr.getError()) return ec; std::unique_ptr<ObjectFile> obj(objOrErr.get()); SymbolRef::Type symtype; uint32_t symflags; symbol_iterator ibegin = obj->symbol_begin(); symbol_iterator iend = obj->symbol_end(); StringRef symbolname; for (symbol_iterator i = ibegin; i != iend; ++i) { error_code ec; // Get symbol name if ((ec = (i->getName(symbolname)))) return ec; if (symbolname != symbol) continue; // Get symbol flags symflags = i->getFlags(); if (symflags <= SymbolRef::SF_Undefined) continue; // Get Symbol Type if ((ec = (i->getType(symtype)))) return ec; if (symtype == SymbolRef::ST_Data) { return error_code::success(); } } return object_error::parse_failed; } private: typedef std::unordered_map<StringRef, Archive::child_iterator> MemberMap; typedef std::set<const char *> InstantiatedSet; const Registry &_registry; std::unique_ptr<Archive> _archive; mutable MemberMap _symbolMemberMap; mutable InstantiatedSet _membersInstantiated; atom_collection_vector<DefinedAtom> _definedAtoms; atom_collection_vector<UndefinedAtom> _undefinedAtoms; atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms; atom_collection_vector<AbsoluteAtom> _absoluteAtoms; bool _isWholeArchive; bool _logLoading; public: /// only subclasses of ArchiveLibraryFile can be instantiated FileArchive(const Registry &registry, Archive *archive, StringRef path, bool isWholeArchive, bool logLoading) : ArchiveLibraryFile(path), _registry(registry), _archive(std::move(archive)), _isWholeArchive(isWholeArchive), _logLoading(logLoading) {} error_code buildTableOfContents() { DEBUG_WITH_TYPE("FileArchive", llvm::dbgs() << "Table of contents for archive '" << _archive->getFileName() << "':\n"); for (auto i = _archive->symbol_begin(), e = _archive->symbol_end(); i != e; ++i) { StringRef name; Archive::child_iterator member; if (error_code ec = i->getName(name)) return ec; if (error_code ec = i->getMember(member)) return ec; DEBUG_WITH_TYPE( "FileArchive", llvm::dbgs() << llvm::format("0x%08llX ", member->getBuffer().data()) << "'" << name << "'\n"); _symbolMemberMap[name] = member; } return error_code::success(); } }; // class FileArchive class ArchiveReader : public Reader { public: ArchiveReader(bool logLoading) : _logLoading(logLoading) {} virtual bool canParse(file_magic magic, StringRef, const MemoryBuffer &) const override { return (magic == llvm::sys::fs::file_magic::archive); } virtual error_code parseFile(std::unique_ptr<MemoryBuffer> &mb, const Registry &reg, std::vector<std::unique_ptr<File>> &result) const override { // Make Archive object which will be owned by FileArchive object. error_code ec; Archive *archive = new Archive(mb.get(), ec); if (ec) return ec; StringRef path = mb->getBufferIdentifier(); // Construct FileArchive object. std::unique_ptr<FileArchive> file( new FileArchive(reg, archive, path, false, _logLoading)); ec = file->buildTableOfContents(); if (ec) return ec; // Transfer ownership of memory buffer to Archive object. mb.release(); result.push_back(std::move(file)); return error_code::success(); } private: bool _logLoading; }; } // anonymous namespace void Registry::addSupportArchives(bool logLoading) { add(std::unique_ptr<Reader>(new ArchiveReader(logLoading))); } } // end namespace lld <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <bh_dag.h> #include <bh_fuse_cache.h> #include <iostream> #include <fstream> #include <sstream> #include <boost/foreach.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/algorithm/string/predicate.hpp> //For iequals() #include <boost/graph/connected_components.hpp> #include <boost/range/adaptors.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <map> #include <iterator> #include <stdio.h> #include <exception> #include <omp.h> using namespace std; using namespace boost; using namespace bohrium; using namespace bohrium::dag; //FILO Task Queue thread safe class TaskQueue { public: typedef pair<vector<bool>, unsigned int> Task; private: mutex mtx; condition_variable non_empty; vector<Task> tasks; unsigned int nwaiting; const unsigned int nthreads; bool finished; public: TaskQueue(unsigned int nthreads):nwaiting(0), nthreads(nthreads), finished(false){} void push(const vector<bool> &mask, unsigned int offset) { unique_lock<mutex> lock(mtx); tasks.push_back(make_pair(mask, offset)); non_empty.notify_one(); } Task pop() { unique_lock<mutex> lock(mtx); if(++nwaiting >= nthreads and tasks.size() == 0) { finished = true; non_empty.notify_all(); throw overflow_error("Out of work"); } while(tasks.size() == 0 and not finished) non_empty.wait(lock); if(finished) throw overflow_error("Out of work"); Task ret = tasks.back(); tasks.pop_back(); --nwaiting; return ret; } }; /* Help function that fuses the edges in 'edges2explore' where the 'mask' is true */ pair<int64_t,bool> fuse_mask(int64_t best_cost, const vector<EdgeW> &edges2explore, const GraphDW &graph, const vector<bool> &mask, bh_ir &bhir, GraphD &dag) { bool fusibility=true; vector<EdgeW> edges2merge; unsigned int i=0; BOOST_FOREACH(const EdgeW &e, edges2explore) { if(mask[i++]) edges2merge.push_back(e); } //Help function to find the new location struct find_new_location { Vertex operator()(const map<Vertex, Vertex> &loc_map, Vertex v) { Vertex v_mapped = loc_map.at(v); if(v_mapped == v) return v; else return (*this)(loc_map, v_mapped); } }find_loc; //'loc_map' maps a vertex before the merge to the corresponding vertex after the merge map<Vertex, Vertex> loc_map; BOOST_FOREACH(Vertex v, vertices(dag)) { loc_map[v] = v; } //Lets record the merges into 'loc_map' BOOST_FOREACH(const EdgeW &e, edges2merge) { Vertex v1 = find_loc(loc_map, source(e, graph.bglW())); Vertex v2 = find_loc(loc_map, target(e, graph.bglW())); loc_map[v1] = v2; } //Pack 'loc_map' such that all keys maps directly to a new vertex thus after //this point there is no need to call find_loc(). BOOST_FOREACH(Vertex v, vertices(dag)) { Vertex v_mapped = find_loc(loc_map, loc_map.at(v)); if(v_mapped != v) loc_map[v] = v_mapped; } //Create the new vertices and insert instruction topologically map<Vertex, bh_ir_kernel> new_vertices; BOOST_FOREACH(Vertex v, vertices(dag)) { if(loc_map.at(v) == v) new_vertices[v] = bh_ir_kernel(bhir); } vector<Vertex> topological_order; topological_sort(dag, back_inserter(topological_order)); BOOST_REVERSE_FOREACH(Vertex vertex, topological_order) { Vertex v = loc_map.at(vertex); bh_ir_kernel &k = new_vertices.at(v); BOOST_FOREACH(uint64_t idx, dag[vertex].instr_indexes) { if(not k.fusible(idx)) fusibility = false; k.add_instr(idx); } } //TODO: Remove this assert check BOOST_FOREACH(Vertex v, vertices(dag)) { if(loc_map.at(v) == v) assert(new_vertices[v].instr_indexes.size() > 0); } //Find the total cost int64_t cost=0; BOOST_FOREACH(const bh_ir_kernel &k, new_vertices | adaptors::map_values) { cost += k.cost(); } //Check if we need to continue if(cost >= best_cost or not fusibility) return make_pair(cost,false); //Merge the vertice in the DAG BOOST_FOREACH(Vertex v, vertices(dag)) { Vertex loc_v = loc_map.at(v); if(loc_v == v) { dag[v] = new_vertices.at(v); assert(dag[v].instr_indexes.size() > 0); } else//Lets merge 'v' into 'loc_v' { BOOST_FOREACH(Vertex a, adjacent_vertices(v, dag)) { a = loc_map.at(a); if(a != loc_v) add_edge(loc_v, a, dag); } BOOST_FOREACH(Vertex a, inv_adjacent_vertices(v, dag)) { a = loc_map.at(a); if(a != loc_v) add_edge(a, loc_v, dag); } clear_vertex(v, dag); dag[v] = bh_ir_kernel(bhir); } } //TODO: remove assert check BOOST_FOREACH(Vertex v, vertices(dag)) { if(dag[loc_map.at(v)].instr_indexes.size() == 0) { cout << v << endl; cout << loc_map.at(v) << endl; assert(1 == 2); exit(-1); } } //Check for cycles if(cycles(dag)) { return make_pair(cost,false); } assert(cost == (int64_t)dag_cost(dag)); return make_pair(cost,true); } /* Find the optimal solution through branch and bound */ void branch_n_bound(bh_ir &bhir, GraphDW &dag, const vector<EdgeW> &edges2explore, FuseCache &cache, const vector<bool> &init_mask, unsigned int init_offset=0) { //We use the greedy algorithm to find a good initial guess int64_t best_cost; GraphD best_dag; { GraphDW new_dag(dag); fuse_greedy(new_dag); best_dag = new_dag.bglD(); best_cost = dag_cost(best_dag); } double purge_count=0; uint64_t explore_count=0; TaskQueue tasks(omp_get_max_threads()); tasks.push(init_mask, init_offset); #pragma omp parallel { while(1) { vector<bool> mask; unsigned int offset; try{ tie(mask, offset) = tasks.pop(); }catch(overflow_error &e){ break; } //Fuse the task GraphD new_dag(dag.bglD()); bool fusibility; int64_t cost; tie(cost, fusibility) = fuse_mask(best_cost, edges2explore, dag, mask, bhir, new_dag); if(explore_count%10000 == 0) { #pragma omp critical { cout << "[" << explore_count << "]["; BOOST_FOREACH(bool b, mask) { if(b){cout << "1";}else{cout << "0";} } cout << "] purge count: "; cout << purge_count << " / " << pow(2.0, (int)mask.size()); cout << ", cost: " << cost << ", best_cost: " << best_cost; cout << ", fusibility: " << fusibility << endl; } } #pragma omp critical ++explore_count; if(cost >= best_cost) { #pragma omp critical purge_count += pow(2.0, (int)(mask.size()-offset)); continue; } if(fusibility) { #pragma omp critical { //Lets save the new best dag best_cost = cost; best_dag = new_dag; assert(dag_validate(best_dag)); //Lets write the current best to file if(cache.enabled) { vector<bh_ir_kernel> kernel_list; fill_kernel_list(best_dag, kernel_list); const InstrIndexesList &i = cache.insert(bhir.instr_list, kernel_list); cache.write_to_files(); stringstream ss; string filename; i.get_filename(filename); ss << "new_best_dag-" << filename << ".dot"; cout << "write file: " << ss.str() << endl; pprint(best_dag, ss.str().c_str()); } purge_count += pow(2.0, (int)(mask.size()-offset)); } continue; } //for(unsigned int i=offset; i<mask.size(); ++i) //breadth first for(int i=mask.size()-1; i>= (int)offset; --i) //depth first { vector<bool> m1(mask); m1[i] = false; tasks.push(m1, i+1); } }} dag = best_dag; } void get_edges2explore(const GraphDW &dag, vector<EdgeW> &edges2explore) { //The list of edges that we should try to merge BOOST_FOREACH(const EdgeW &e, edges(dag.bglW())) { edges2explore.push_back(e); } sort_weights(dag.bglW(), edges2explore); string order; { const char *t = getenv("BH_FUSER_OPTIMAL_ORDER"); if(t == NULL) order ="regular"; else order = t; } if(not iequals(order, "regular")) { if(iequals(order, "reverse")) { reverse(edges2explore.begin(), edges2explore.end()); } else if(iequals(order, "random")) { random_shuffle(edges2explore.begin(), edges2explore.end()); } else { cerr << "FUSER-OPTIMAL: unknown BH_FUSER_OPTIMAL_ORDER: " << order << endl; order = "regular"; } } //cout << "BH_FUSER_OPTIMAL_ORDER: " << order << endl; } /* Fuse the 'dag' optimally */ void fuse_optimal(bh_ir &bhir, GraphDW &dag, FuseCache &cache) { //The list of edges that we should try to merge vector<EdgeW> edges2explore; get_edges2explore(dag, edges2explore); if(edges2explore.size() == 0) return; //Check for a preloaded initial condition vector<bool> mask(edges2explore.size(), true); unsigned int preload_offset=0; if(edges2explore.size() > 10) { const char *t = getenv("BH_FUSER_OPTIMAL_PRELOAD"); if(t != NULL) { BOOST_FOREACH(const char &c, string(t)) { mask[preload_offset++] = lexical_cast<bool>(c); if(preload_offset == mask.size()) break; } cout << "Preloaded path (" << preload_offset << "): "; for(unsigned int j=0; j<preload_offset; ++j) cout << mask[j] << ", "; cout << endl; --preload_offset; } } cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl; branch_n_bound(bhir, dag, edges2explore, cache, mask, preload_offset); } void do_fusion(bh_ir &bhir, FuseCache &cache) { GraphDW dag; from_bhir(bhir, dag); vector<GraphDW> dags; split(dag, dags); assert(dag_validate(bhir, dags)); BOOST_FOREACH(GraphDW &d, dags) { fuse_gently(d); d.transitive_reduction(); fuse_optimal(bhir, d, cache); } assert(dag_validate(bhir, dags)); BOOST_FOREACH(GraphDW &d, dags) fill_kernel_list(d.bglD(), bhir.kernel_list); } void fuser(bh_ir &bhir, FuseCache &cache) { if(bhir.kernel_list.size() != 0) throw logic_error("The kernel_list is not empty!"); if(cache.enabled) { BatchHash hash(bhir.instr_list); if(cache.lookup(hash, bhir, bhir.kernel_list)) return;//Fuse cache hit! do_fusion(bhir, cache); cache.insert(hash, bhir.kernel_list); } else { do_fusion(bhir, cache); } } <commit_msg>optimal-fuser: fix BUG where partial cache files was written to disk<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <bh_dag.h> #include <bh_fuse_cache.h> #include <iostream> #include <fstream> #include <sstream> #include <boost/foreach.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/algorithm/string/predicate.hpp> //For iequals() #include <boost/graph/connected_components.hpp> #include <boost/range/adaptors.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <map> #include <iterator> #include <stdio.h> #include <exception> #include <omp.h> using namespace std; using namespace boost; using namespace bohrium; using namespace bohrium::dag; //FILO Task Queue thread safe class TaskQueue { public: typedef pair<vector<bool>, unsigned int> Task; private: mutex mtx; condition_variable non_empty; vector<Task> tasks; unsigned int nwaiting; const unsigned int nthreads; bool finished; public: TaskQueue(unsigned int nthreads):nwaiting(0), nthreads(nthreads), finished(false){} void push(const vector<bool> &mask, unsigned int offset) { unique_lock<mutex> lock(mtx); tasks.push_back(make_pair(mask, offset)); non_empty.notify_one(); } Task pop() { unique_lock<mutex> lock(mtx); if(++nwaiting >= nthreads and tasks.size() == 0) { finished = true; non_empty.notify_all(); throw overflow_error("Out of work"); } while(tasks.size() == 0 and not finished) non_empty.wait(lock); if(finished) throw overflow_error("Out of work"); Task ret = tasks.back(); tasks.pop_back(); --nwaiting; return ret; } }; /* Help function that fuses the edges in 'edges2explore' where the 'mask' is true */ pair<int64_t,bool> fuse_mask(int64_t best_cost, const vector<EdgeW> &edges2explore, const GraphDW &graph, const vector<bool> &mask, bh_ir &bhir, GraphD &dag) { bool fusibility=true; vector<EdgeW> edges2merge; unsigned int i=0; BOOST_FOREACH(const EdgeW &e, edges2explore) { if(mask[i++]) edges2merge.push_back(e); } //Help function to find the new location struct find_new_location { Vertex operator()(const map<Vertex, Vertex> &loc_map, Vertex v) { Vertex v_mapped = loc_map.at(v); if(v_mapped == v) return v; else return (*this)(loc_map, v_mapped); } }find_loc; //'loc_map' maps a vertex before the merge to the corresponding vertex after the merge map<Vertex, Vertex> loc_map; BOOST_FOREACH(Vertex v, vertices(dag)) { loc_map[v] = v; } //Lets record the merges into 'loc_map' BOOST_FOREACH(const EdgeW &e, edges2merge) { Vertex v1 = find_loc(loc_map, source(e, graph.bglW())); Vertex v2 = find_loc(loc_map, target(e, graph.bglW())); loc_map[v1] = v2; } //Pack 'loc_map' such that all keys maps directly to a new vertex thus after //this point there is no need to call find_loc(). BOOST_FOREACH(Vertex v, vertices(dag)) { Vertex v_mapped = find_loc(loc_map, loc_map.at(v)); if(v_mapped != v) loc_map[v] = v_mapped; } //Create the new vertices and insert instruction topologically map<Vertex, bh_ir_kernel> new_vertices; BOOST_FOREACH(Vertex v, vertices(dag)) { if(loc_map.at(v) == v) new_vertices[v] = bh_ir_kernel(bhir); } vector<Vertex> topological_order; topological_sort(dag, back_inserter(topological_order)); BOOST_REVERSE_FOREACH(Vertex vertex, topological_order) { Vertex v = loc_map.at(vertex); bh_ir_kernel &k = new_vertices.at(v); BOOST_FOREACH(uint64_t idx, dag[vertex].instr_indexes) { if(not k.fusible(idx)) fusibility = false; k.add_instr(idx); } } //TODO: Remove this assert check BOOST_FOREACH(Vertex v, vertices(dag)) { if(loc_map.at(v) == v) assert(new_vertices[v].instr_indexes.size() > 0); } //Find the total cost int64_t cost=0; BOOST_FOREACH(const bh_ir_kernel &k, new_vertices | adaptors::map_values) { cost += k.cost(); } //Check if we need to continue if(cost >= best_cost or not fusibility) return make_pair(cost,false); //Merge the vertice in the DAG BOOST_FOREACH(Vertex v, vertices(dag)) { Vertex loc_v = loc_map.at(v); if(loc_v == v) { dag[v] = new_vertices.at(v); assert(dag[v].instr_indexes.size() > 0); } else//Lets merge 'v' into 'loc_v' { BOOST_FOREACH(Vertex a, adjacent_vertices(v, dag)) { a = loc_map.at(a); if(a != loc_v) add_edge(loc_v, a, dag); } BOOST_FOREACH(Vertex a, inv_adjacent_vertices(v, dag)) { a = loc_map.at(a); if(a != loc_v) add_edge(a, loc_v, dag); } clear_vertex(v, dag); dag[v] = bh_ir_kernel(bhir); } } //TODO: remove assert check BOOST_FOREACH(Vertex v, vertices(dag)) { if(dag[loc_map.at(v)].instr_indexes.size() == 0) { cout << v << endl; cout << loc_map.at(v) << endl; assert(1 == 2); exit(-1); } } //Check for cycles if(cycles(dag)) { return make_pair(cost,false); } assert(cost == (int64_t)dag_cost(dag)); return make_pair(cost,true); } /* Find the optimal solution through branch and bound */ void branch_n_bound(bh_ir &bhir, GraphDW &dag, const vector<EdgeW> &edges2explore, const vector<bool> &init_mask, unsigned int init_offset=0) { //We use the greedy algorithm to find a good initial guess int64_t best_cost; GraphD best_dag; { GraphDW new_dag(dag); fuse_greedy(new_dag); best_dag = new_dag.bglD(); best_cost = dag_cost(best_dag); } double purge_count=0; uint64_t explore_count=0; TaskQueue tasks(omp_get_max_threads()); tasks.push(init_mask, init_offset); #pragma omp parallel { while(1) { vector<bool> mask; unsigned int offset; try{ tie(mask, offset) = tasks.pop(); }catch(overflow_error &e){ break; } //Fuse the task GraphD new_dag(dag.bglD()); bool fusibility; int64_t cost; tie(cost, fusibility) = fuse_mask(best_cost, edges2explore, dag, mask, bhir, new_dag); if(explore_count%10000 == 0) { #pragma omp critical { cout << "[" << explore_count << "]["; BOOST_FOREACH(bool b, mask) { if(b){cout << "1";}else{cout << "0";} } cout << "] purge count: "; cout << purge_count << " / " << pow(2.0, (int)mask.size()); cout << ", cost: " << cost << ", best_cost: " << best_cost; cout << ", fusibility: " << fusibility << endl; } } #pragma omp critical ++explore_count; if(cost >= best_cost) { #pragma omp critical purge_count += pow(2.0, (int)(mask.size()-offset)); continue; } if(fusibility) { #pragma omp critical { //Lets save the new best dag best_cost = cost; best_dag = new_dag; assert(dag_validate(best_dag)); purge_count += pow(2.0, (int)(mask.size()-offset)); } continue; } //for(unsigned int i=offset; i<mask.size(); ++i) //breadth first for(int i=mask.size()-1; i>= (int)offset; --i) //depth first { vector<bool> m1(mask); m1[i] = false; tasks.push(m1, i+1); } }} dag = best_dag; } void get_edges2explore(const GraphDW &dag, vector<EdgeW> &edges2explore) { //The list of edges that we should try to merge BOOST_FOREACH(const EdgeW &e, edges(dag.bglW())) { edges2explore.push_back(e); } sort_weights(dag.bglW(), edges2explore); string order; { const char *t = getenv("BH_FUSER_OPTIMAL_ORDER"); if(t == NULL) order ="regular"; else order = t; } if(not iequals(order, "regular")) { if(iequals(order, "reverse")) { reverse(edges2explore.begin(), edges2explore.end()); } else if(iequals(order, "random")) { random_shuffle(edges2explore.begin(), edges2explore.end()); } else { cerr << "FUSER-OPTIMAL: unknown BH_FUSER_OPTIMAL_ORDER: " << order << endl; order = "regular"; } } //cout << "BH_FUSER_OPTIMAL_ORDER: " << order << endl; } /* Fuse the 'dag' optimally */ void fuse_optimal(bh_ir &bhir, GraphDW &dag) { //The list of edges that we should try to merge vector<EdgeW> edges2explore; get_edges2explore(dag, edges2explore); if(edges2explore.size() == 0) return; //Check for a preloaded initial condition vector<bool> mask(edges2explore.size(), true); unsigned int preload_offset=0; if(edges2explore.size() > 10) { const char *t = getenv("BH_FUSER_OPTIMAL_PRELOAD"); if(t != NULL) { BOOST_FOREACH(const char &c, string(t)) { mask[preload_offset++] = lexical_cast<bool>(c); if(preload_offset == mask.size()) break; } cout << "Preloaded path (" << preload_offset << "): "; for(unsigned int j=0; j<preload_offset; ++j) cout << mask[j] << ", "; cout << endl; --preload_offset; } } cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl; branch_n_bound(bhir, dag, edges2explore, mask, preload_offset); } void do_fusion(bh_ir &bhir) { GraphDW dag; from_bhir(bhir, dag); vector<GraphDW> dags; split(dag, dags); assert(dag_validate(bhir, dags)); BOOST_FOREACH(GraphDW &d, dags) { fuse_gently(d); d.transitive_reduction(); fuse_optimal(bhir, d); } assert(dag_validate(bhir, dags)); BOOST_FOREACH(GraphDW &d, dags) fill_kernel_list(d.bglD(), bhir.kernel_list); } void fuser(bh_ir &bhir, FuseCache &cache) { if(bhir.kernel_list.size() != 0) throw logic_error("The kernel_list is not empty!"); if(cache.enabled) { BatchHash hash(bhir.instr_list); if(cache.lookup(hash, bhir, bhir.kernel_list)) return;//Fuse cache hit! do_fusion(bhir); cache.insert(hash, bhir.kernel_list); } else { do_fusion(bhir); } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // ####### Blueberry includes ####### #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // ####### Qmitk includes ####### #include "QmitkConnectomicsStatisticsView.h" #include "QmitkStdMultiWidget.h" //#include "QmitkRenderWindow.h"//? // ####### Qt includes ####### #include <QMessageBox> #include <QStringList> // ####### ITK includes ####### #include <itkRGBAPixel.h> // ####### MITK includes ####### #include <mbilog.h> #include <mitkConnectomicsConstantsManager.h> #include <mitkConnectomicsStatisticsCalculator.h> #include <mitkConnectomicsRenderingProperties.h> //#include <mitkRenderWindowBase.h>//? //#include <mitkIRenderingManager.h>//? // Includes for image casting between ITK and MITK #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" #include <string> const std::string QmitkConnectomicsStatisticsView::VIEW_ID = "org.mitk.views.connectomicsstatistics"; QmitkConnectomicsStatisticsView::QmitkConnectomicsStatisticsView() : QmitkFunctionality() , m_Controls( nullptr ) , m_MultiWidget( nullptr ) , m_currentIndex( 0 ) { } QmitkConnectomicsStatisticsView::~QmitkConnectomicsStatisticsView() { } void QmitkConnectomicsStatisticsView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) {// create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkConnectomicsStatisticsViewControls; m_Controls-> setupUi( parent ); connect( m_Controls-> networkBalloonsNodeLabelsComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( OnNetworkBalloonsNodeLabelsComboBoxCurrentIndexChanged( int ) ) ); } this-> WipeDisplay(); } void QmitkConnectomicsStatisticsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkConnectomicsStatisticsView::StdMultiWidgetNotAvailable() { m_MultiWidget = nullptr; } void QmitkConnectomicsStatisticsView::WipeDisplay() { m_Controls->lblWarning->setVisible( true ); m_Controls->inputImageOneNameLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->inputImageOneNameLabel->setVisible( false ); m_Controls->inputImageOneLabel->setVisible( false ); m_Controls->networkStatisticsPlainTextEdit->clear(); m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->betweennessNetworkHistogramCanvas->update(); m_Controls->degreeNetworkHistogramCanvas->update(); m_Controls->shortestPathNetworkHistogramCanvas->update(); m_Controls->betweennessNetworkHistogramCanvas->Clear(); m_Controls->degreeNetworkHistogramCanvas->Clear(); m_Controls->shortestPathNetworkHistogramCanvas->Clear(); m_Controls->betweennessNetworkHistogramCanvas->Replot(); m_Controls->degreeNetworkHistogramCanvas->Replot(); m_Controls->shortestPathNetworkHistogramCanvas->Replot(); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::clear(); m_Controls-> networkBalloonsPlainTextEdit-> clear(); } void QmitkConnectomicsStatisticsView::OnNetworkBalloonsNodeLabelsComboBoxCurrentIndexChanged( int currentIndex ) { std::vector<mitk::DataNode*> nodes = this-> GetDataManagerSelection(); if( nodes.size() != 1 ) { return; } mitk::DataNode::Pointer node = *nodes.begin(); if( node.IsNotNull() ) { mitk::ConnectomicsNetwork* network = dynamic_cast< mitk::ConnectomicsNetwork* >( node-> GetData() ); if( network ) { std::string tempCurrentText = m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::currentText().toStdString(); // get text of currently selected item. if( tempCurrentText.size() > 3 && tempCurrentText.rfind( ":" ) != tempCurrentText.npos ) { // update chosenNode property. tempCurrentText = tempCurrentText.substr( tempCurrentText.rfind( ":" ) + 2 ); node-> SetProperty( mitk::connectomicsRenderingNodeChosenNodeName.c_str(), mitk::StringProperty::New( tempCurrentText.c_str() ) ); this-> m_MultiWidget-> ForceImmediateUpdate(); //RequestUpdate() is too slow. } std::stringstream balloonTextStream; node-> Update(); if( node-> GetProperty( mitk::connectomicsRenderingBalloonTextName.c_str() ) != nullptr && node-> GetProperty( mitk::connectomicsRenderingBalloonNodeStatsName.c_str() ) != nullptr && tempCurrentText != "-1" ) { balloonTextStream << node-> GetProperty( mitk::connectomicsRenderingBalloonTextName.c_str() ) -> GetValueAsString() << std::endl << node-> GetProperty( mitk::connectomicsRenderingBalloonNodeStatsName.c_str() ) -> GetValueAsString() << std::endl; QString balloonQString ( balloonTextStream.str().c_str() ); // setPlainText() overwrites, insertPlainText() appends. m_Controls-> networkBalloonsPlainTextEdit-> setPlainText( balloonQString.simplified() ); } if( tempCurrentText == "-1" ) { m_Controls-> networkBalloonsPlainTextEdit-> setPlainText( "" ); } } } return; } void QmitkConnectomicsStatisticsView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes ) { this->WipeDisplay(); // Valid options are either // 1 image (parcellation) // // 1 image (parcellation) // 1 fiber bundle // // 1 network if( nodes.size() > 2 ) { return; } bool currentFormatUnknown(true); // iterate all selected objects, adjust warning visibility for( std::vector<mitk::DataNode*>::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; currentFormatUnknown = true; if( node.IsNotNull() ) { // network section mitk::ConnectomicsNetwork* network = dynamic_cast<mitk::ConnectomicsNetwork*>( node->GetData() ); if( network ) { currentFormatUnknown = false; if( nodes.size() != 1 ) { // only valid option is a single network this->WipeDisplay(); return; } m_Controls->lblWarning->setVisible( false ); m_Controls->inputImageOneNameLabel->setText(node->GetName().c_str()); m_Controls->inputImageOneNameLabel->setVisible( true ); m_Controls->inputImageOneLabel->setVisible( true ); { std::stringstream statisticsStream; mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( network ); calculator->Update(); statisticsStream << "# Vertices: " << calculator->GetNumberOfVertices() << "\n"; statisticsStream << "# Edges: " << calculator->GetNumberOfEdges() << "\n"; statisticsStream << "Average Degree: " << calculator->GetAverageDegree() << "\n"; statisticsStream << "Density: " << calculator->GetConnectionDensity() << "\n"; statisticsStream << "Small Worldness: " << calculator->GetSmallWorldness() << "\n"; statisticsStream << "Average Path Length: " << calculator->GetAveragePathLength() << "\n"; statisticsStream << "Efficiency: " << (1 / calculator->GetAveragePathLength() ) << "\n"; statisticsStream << "# Connected Components: " << calculator->GetNumberOfConnectedComponents() << "\n"; statisticsStream << "Average Component Size: " << calculator->GetAverageComponentSize() << "\n"; statisticsStream << "Largest Component Size: " << calculator->GetLargestComponentSize() << "\n"; statisticsStream << "Average Clustering Coefficient: " << calculator->GetAverageClusteringCoefficientsC() << "\n"; statisticsStream << "Average Vertex Betweenness Centrality: " << calculator->GetAverageVertexBetweennessCentrality() << "\n"; statisticsStream << "Average Edge Betweenness Centrality: " << calculator->GetAverageEdgeBetweennessCentrality() << "\n"; statisticsStream << "# Isolated Points: " << calculator->GetNumberOfIsolatedPoints() << "\n"; statisticsStream << "# End Points: " << calculator->GetNumberOfEndPoints() << "\n"; statisticsStream << "Diameter: " << calculator->GetDiameter() << "\n"; statisticsStream << "Radius: " << calculator->GetRadius() << "\n"; statisticsStream << "Average Eccentricity: " << calculator->GetAverageEccentricity() << "\n"; statisticsStream << "# Central Points: " << calculator->GetNumberOfCentralPoints() << "\n"; QString statisticsString( statisticsStream.str().c_str() ); m_Controls-> networkStatisticsPlainTextEdit-> setPlainText( statisticsString ); } mitk::ConnectomicsNetwork::Pointer connectomicsNetwork( network ); mitk::ConnectomicsHistogramsContainer *histogramContainer = histogramCache[ connectomicsNetwork ]; if(histogramContainer) { m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( histogramContainer->GetBetweennessHistogram() ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( histogramContainer->GetDegreeHistogram() ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( histogramContainer->GetShortestPathHistogram() ); m_Controls->betweennessNetworkHistogramCanvas->DrawProfiles(); m_Controls->degreeNetworkHistogramCanvas->DrawProfiles(); m_Controls->shortestPathNetworkHistogramCanvas->DrawProfiles(); } // For the balloon overlay: if( node-> GetProperty( mitk::connectomicsRenderingBalloonAllNodeLabelsName.c_str() ) != nullptr ) { // QComboBox with node label names and numbers. QString allNodesLabel = node-> GetProperty( mitk::connectomicsRenderingBalloonAllNodeLabelsName.c_str() )-> GetValueAsString().c_str(); QStringList allNodesLabelList = allNodesLabel.simplified().split( "," ); allNodesLabelList.sort( Qt::CaseInsensitive ); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::addItem( "no node chosen: -1" ); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::addItems( allNodesLabelList ); } } } // end network section if ( currentFormatUnknown ) { this->WipeDisplay(); return; } } // end for loop } <commit_msg>removed some commented out includes<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // ####### Blueberry includes ####### #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // ####### Qmitk includes ####### #include "QmitkConnectomicsStatisticsView.h" #include "QmitkStdMultiWidget.h" // ####### Qt includes ####### #include <QMessageBox> #include <QStringList> // ####### ITK includes ####### #include <itkRGBAPixel.h> // ####### MITK includes ####### #include <mbilog.h> #include <mitkConnectomicsConstantsManager.h> #include <mitkConnectomicsStatisticsCalculator.h> #include <mitkConnectomicsRenderingProperties.h> // Includes for image casting between ITK and MITK #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" #include <string> const std::string QmitkConnectomicsStatisticsView::VIEW_ID = "org.mitk.views.connectomicsstatistics"; QmitkConnectomicsStatisticsView::QmitkConnectomicsStatisticsView() : QmitkFunctionality() , m_Controls( nullptr ) , m_MultiWidget( nullptr ) , m_currentIndex( 0 ) { } QmitkConnectomicsStatisticsView::~QmitkConnectomicsStatisticsView() { } void QmitkConnectomicsStatisticsView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) {// create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkConnectomicsStatisticsViewControls; m_Controls-> setupUi( parent ); connect( m_Controls-> networkBalloonsNodeLabelsComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( OnNetworkBalloonsNodeLabelsComboBoxCurrentIndexChanged( int ) ) ); } this-> WipeDisplay(); } void QmitkConnectomicsStatisticsView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkConnectomicsStatisticsView::StdMultiWidgetNotAvailable() { m_MultiWidget = nullptr; } void QmitkConnectomicsStatisticsView::WipeDisplay() { m_Controls->lblWarning->setVisible( true ); m_Controls->inputImageOneNameLabel->setText( mitk::ConnectomicsConstantsManager::CONNECTOMICS_GUI_DASH ); m_Controls->inputImageOneNameLabel->setVisible( false ); m_Controls->inputImageOneLabel->setVisible( false ); m_Controls->networkStatisticsPlainTextEdit->clear(); m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( nullptr ); m_Controls->betweennessNetworkHistogramCanvas->update(); m_Controls->degreeNetworkHistogramCanvas->update(); m_Controls->shortestPathNetworkHistogramCanvas->update(); m_Controls->betweennessNetworkHistogramCanvas->Clear(); m_Controls->degreeNetworkHistogramCanvas->Clear(); m_Controls->shortestPathNetworkHistogramCanvas->Clear(); m_Controls->betweennessNetworkHistogramCanvas->Replot(); m_Controls->degreeNetworkHistogramCanvas->Replot(); m_Controls->shortestPathNetworkHistogramCanvas->Replot(); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::clear(); m_Controls-> networkBalloonsPlainTextEdit-> clear(); } void QmitkConnectomicsStatisticsView::OnNetworkBalloonsNodeLabelsComboBoxCurrentIndexChanged( int currentIndex ) { std::vector<mitk::DataNode*> nodes = this-> GetDataManagerSelection(); if( nodes.size() != 1 ) { return; } mitk::DataNode::Pointer node = *nodes.begin(); if( node.IsNotNull() ) { mitk::ConnectomicsNetwork* network = dynamic_cast< mitk::ConnectomicsNetwork* >( node-> GetData() ); if( network ) { std::string tempCurrentText = m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::currentText().toStdString(); // get text of currently selected item. if( tempCurrentText.size() > 3 && tempCurrentText.rfind( ":" ) != tempCurrentText.npos ) { // update chosenNode property. tempCurrentText = tempCurrentText.substr( tempCurrentText.rfind( ":" ) + 2 ); node-> SetProperty( mitk::connectomicsRenderingNodeChosenNodeName.c_str(), mitk::StringProperty::New( tempCurrentText.c_str() ) ); this-> m_MultiWidget-> ForceImmediateUpdate(); //RequestUpdate() is too slow. } std::stringstream balloonTextStream; node-> Update(); if( node-> GetProperty( mitk::connectomicsRenderingBalloonTextName.c_str() ) != nullptr && node-> GetProperty( mitk::connectomicsRenderingBalloonNodeStatsName.c_str() ) != nullptr && tempCurrentText != "-1" ) { balloonTextStream << node-> GetProperty( mitk::connectomicsRenderingBalloonTextName.c_str() ) -> GetValueAsString() << std::endl << node-> GetProperty( mitk::connectomicsRenderingBalloonNodeStatsName.c_str() ) -> GetValueAsString() << std::endl; QString balloonQString ( balloonTextStream.str().c_str() ); // setPlainText() overwrites, insertPlainText() appends. m_Controls-> networkBalloonsPlainTextEdit-> setPlainText( balloonQString.simplified() ); } if( tempCurrentText == "-1" ) { m_Controls-> networkBalloonsPlainTextEdit-> setPlainText( "" ); } } } return; } void QmitkConnectomicsStatisticsView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes ) { this->WipeDisplay(); // Valid options are either // 1 image (parcellation) // // 1 image (parcellation) // 1 fiber bundle // // 1 network if( nodes.size() > 2 ) { return; } bool currentFormatUnknown(true); // iterate all selected objects, adjust warning visibility for( std::vector<mitk::DataNode*>::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; currentFormatUnknown = true; if( node.IsNotNull() ) { // network section mitk::ConnectomicsNetwork* network = dynamic_cast<mitk::ConnectomicsNetwork*>( node->GetData() ); if( network ) { currentFormatUnknown = false; if( nodes.size() != 1 ) { // only valid option is a single network this->WipeDisplay(); return; } m_Controls->lblWarning->setVisible( false ); m_Controls->inputImageOneNameLabel->setText(node->GetName().c_str()); m_Controls->inputImageOneNameLabel->setVisible( true ); m_Controls->inputImageOneLabel->setVisible( true ); { std::stringstream statisticsStream; mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( network ); calculator->Update(); statisticsStream << "# Vertices: " << calculator->GetNumberOfVertices() << "\n"; statisticsStream << "# Edges: " << calculator->GetNumberOfEdges() << "\n"; statisticsStream << "Average Degree: " << calculator->GetAverageDegree() << "\n"; statisticsStream << "Density: " << calculator->GetConnectionDensity() << "\n"; statisticsStream << "Small Worldness: " << calculator->GetSmallWorldness() << "\n"; statisticsStream << "Average Path Length: " << calculator->GetAveragePathLength() << "\n"; statisticsStream << "Efficiency: " << (1 / calculator->GetAveragePathLength() ) << "\n"; statisticsStream << "# Connected Components: " << calculator->GetNumberOfConnectedComponents() << "\n"; statisticsStream << "Average Component Size: " << calculator->GetAverageComponentSize() << "\n"; statisticsStream << "Largest Component Size: " << calculator->GetLargestComponentSize() << "\n"; statisticsStream << "Average Clustering Coefficient: " << calculator->GetAverageClusteringCoefficientsC() << "\n"; statisticsStream << "Average Vertex Betweenness Centrality: " << calculator->GetAverageVertexBetweennessCentrality() << "\n"; statisticsStream << "Average Edge Betweenness Centrality: " << calculator->GetAverageEdgeBetweennessCentrality() << "\n"; statisticsStream << "# Isolated Points: " << calculator->GetNumberOfIsolatedPoints() << "\n"; statisticsStream << "# End Points: " << calculator->GetNumberOfEndPoints() << "\n"; statisticsStream << "Diameter: " << calculator->GetDiameter() << "\n"; statisticsStream << "Radius: " << calculator->GetRadius() << "\n"; statisticsStream << "Average Eccentricity: " << calculator->GetAverageEccentricity() << "\n"; statisticsStream << "# Central Points: " << calculator->GetNumberOfCentralPoints() << "\n"; QString statisticsString( statisticsStream.str().c_str() ); m_Controls-> networkStatisticsPlainTextEdit-> setPlainText( statisticsString ); } mitk::ConnectomicsNetwork::Pointer connectomicsNetwork( network ); mitk::ConnectomicsHistogramsContainer *histogramContainer = histogramCache[ connectomicsNetwork ]; if(histogramContainer) { m_Controls->betweennessNetworkHistogramCanvas->SetHistogram( histogramContainer->GetBetweennessHistogram() ); m_Controls->degreeNetworkHistogramCanvas->SetHistogram( histogramContainer->GetDegreeHistogram() ); m_Controls->shortestPathNetworkHistogramCanvas->SetHistogram( histogramContainer->GetShortestPathHistogram() ); m_Controls->betweennessNetworkHistogramCanvas->DrawProfiles(); m_Controls->degreeNetworkHistogramCanvas->DrawProfiles(); m_Controls->shortestPathNetworkHistogramCanvas->DrawProfiles(); } // For the balloon overlay: if( node-> GetProperty( mitk::connectomicsRenderingBalloonAllNodeLabelsName.c_str() ) != nullptr ) { // QComboBox with node label names and numbers. QString allNodesLabel = node-> GetProperty( mitk::connectomicsRenderingBalloonAllNodeLabelsName.c_str() )-> GetValueAsString().c_str(); QStringList allNodesLabelList = allNodesLabel.simplified().split( "," ); allNodesLabelList.sort( Qt::CaseInsensitive ); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::addItem( "no node chosen: -1" ); m_Controls-> networkBalloonsNodeLabelsComboBox-> QComboBox::addItems( allNodesLabelList ); } } } // end network section if ( currentFormatUnknown ) { this->WipeDisplay(); return; } } // end for loop } <|endoftext|>
<commit_before> #include "Base.h" #include "Game.h" #include "ScriptController.h" namespace gameplay { Logger::State Logger::_state[3]; Logger::State::State() : logFunctionC(NULL), logFunctionLua(NULL), enabled(true) { } Logger::Logger() { } Logger::~Logger() { } void Logger::log(Level level, const char* message, ...) { State& state = _state[level]; if (!state.enabled) return; va_list args; va_start(args, message); // Declare a moderately sized buffer on the stack that should be // large enough to accommodate most log requests. int size = 1024; char stackBuffer[1024]; std::vector<char> dynamicBuffer; char* str = stackBuffer; for ( ; ; ) { // Pass one less than size to leave room for NULL terminator int needed = vsnprintf(str, size-1, message, args); // NOTE: Some platforms return -1 when vsnprintf runs out of room, while others return // the number of characters actually needed to fill the buffer. if (needed >= 0 && needed < size) { // Successfully wrote buffer. Added a NULL terminator in case it wasn't written. str[needed] = '\0'; break; } size = needed > 0 ? (needed + 1) : (size * 2); dynamicBuffer.resize(size); str = &dynamicBuffer[0]; } if (state.logFunctionC) { // Pass call to registered C log function (*state.logFunctionC)(level, str); } else if (state.logFunctionLua) { // Pass call to registered Lua log function Game::getInstance()->getScriptController()->executeFunction<void>(state.logFunctionLua, "[Logger::Level]s", level, str); } else { // Log to the default output gameplay::print("%s", str); } va_end(args); } bool Logger::isEnabled(Level level) { return _state[level].enabled; } void Logger::setEnabled(Level level, bool enabled) { _state[level].enabled = enabled; } void Logger::set(Level level, void (*logFunction) (Level, const char*)) { State& state = _state[level]; state.logFunctionC = logFunction; state.logFunctionLua = NULL; } void Logger::set(Level level, const char* logFunction) { State& state = _state[level]; state.logFunctionLua = logFunction; state.logFunctionC = NULL; } } <commit_msg>Fix Logger crash<commit_after> #include "Base.h" #include "Game.h" #include "ScriptController.h" namespace gameplay { Logger::State Logger::_state[3]; Logger::State::State() : logFunctionC(NULL), logFunctionLua(NULL), enabled(true) { } Logger::Logger() { } Logger::~Logger() { } void Logger::log(Level level, const char* message, ...) { State& state = _state[level]; if (!state.enabled) return; // Declare a moderately sized buffer on the stack that should be // large enough to accommodate most log requests. int size = 1024; char stackBuffer[1024]; std::vector<char> dynamicBuffer; char* str = stackBuffer; for ( ; ; ) { va_list args; va_start(args, message); // Pass one less than size to leave room for NULL terminator int needed = vsnprintf(str, size-1, message, args); // NOTE: Some platforms return -1 when vsnprintf runs out of room, while others return // the number of characters actually needed to fill the buffer. if (needed >= 0 && needed < size) { // Successfully wrote buffer. Added a NULL terminator in case it wasn't written. str[needed] = '\0'; va_end(args); break; } size = needed > 0 ? (needed + 1) : (size * 2); dynamicBuffer.resize(size); str = &dynamicBuffer[0]; va_end(args); } if (state.logFunctionC) { // Pass call to registered C log function (*state.logFunctionC)(level, str); } else if (state.logFunctionLua) { // Pass call to registered Lua log function Game::getInstance()->getScriptController()->executeFunction<void>(state.logFunctionLua, "[Logger::Level]s", level, str); } else { // Log to the default output gameplay::print("%s", str); } } bool Logger::isEnabled(Level level) { return _state[level].enabled; } void Logger::setEnabled(Level level, bool enabled) { _state[level].enabled = enabled; } void Logger::set(Level level, void (*logFunction) (Level, const char*)) { State& state = _state[level]; state.logFunctionC = logFunction; state.logFunctionLua = NULL; } void Logger::set(Level level, const char* logFunction) { State& state = _state[level]; state.logFunctionLua = logFunction; state.logFunctionC = NULL; } } <|endoftext|>
<commit_before><commit_msg>Temporary fix for a crash when going offline<commit_after><|endoftext|>
<commit_before><commit_msg>remove unnecessary german comment<commit_after><|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpInputDeviceManager.h> #include <mp/MprFromInputDevice.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprFromInputDevice::MprFromInputDevice(const UtlString& rName, int samplesPerFrame, int samplesPerSec, MpInputDeviceManager* deviceManager, MpInputDeviceHandle deviceId) : MpAudioResource(rName, 1, 1, /* inputs */ 0, 0, /* outputs */ samplesPerFrame, samplesPerSec) , mpInputDeviceManager(deviceManager) , mFrameTimeInitialized(FALSE) , mPreviousFrameTime(0) , mDeviceId(deviceId) { } // Destructor MprFromInputDevice::~MprFromInputDevice() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprFromInputDevice::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { // NOTE: Logic to react to frequent starvation is missing. assert(mpInputDeviceManager); // Milliseconds per frame: int frameTimeInterval = samplesPerFrame * 1000 / samplesPerSecond; if (!mFrameTimeInitialized) { // Start with a frame behind. Possible need smarter // decision for starting. mPreviousFrameTime = mpInputDeviceManager->getCurrentFrameTime(); mPreviousFrameTime -= (2 * frameTimeInterval); } mPreviousFrameTime += frameTimeInterval; MpBufPtr buffer; unsigned int numFramesNotPlayed; unsigned int numFramedBufferedBehind; MpFrameTime frameToFetch; // Use temp variable for frame time to prevent frame time drift in case // of device hiccup. frameToFetch = mPreviousFrameTime; OsStatus getResult = mpInputDeviceManager->getFrame(mDeviceId, frameToFetch, buffer, numFramesNotPlayed, numFramedBufferedBehind); if (!mFrameTimeInitialized) { if (getResult == OS_SUCCESS) { mFrameTimeInitialized = TRUE; } if (numFramesNotPlayed > 1) { // TODO: now is a good time to adjust and get a newer // frame // could increment mPreviousFrameTime and getFrame again } } outBufs[0] = buffer; return getResult; } /* ============================ FUNCTIONS ================================= */ <commit_msg>Multiple improvements and fixes for MprFromInputDevice:<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpInputDeviceManager.h> #include <mp/MprFromInputDevice.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprFromInputDevice::MprFromInputDevice(const UtlString& rName, int samplesPerFrame, int samplesPerSec, MpInputDeviceManager* deviceManager, MpInputDeviceHandle deviceId) : MpAudioResource(rName, 0, 0, /* inputs */ 1, 1, /* outputs */ samplesPerFrame, samplesPerSec) , mpInputDeviceManager(deviceManager) , mFrameTimeInitialized(FALSE) , mPreviousFrameTime(0) , mDeviceId(deviceId) { } // Destructor MprFromInputDevice::~MprFromInputDevice() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprFromInputDevice::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { // NOTE: Logic to react to frequent starvation is missing. assert(mpInputDeviceManager); // Milliseconds per frame: int frameTimeInterval = samplesPerFrame * 1000 / samplesPerSecond; if (!mFrameTimeInitialized) { // Start with a frame behind. Possible need smarter // decision for starting. mPreviousFrameTime = mpInputDeviceManager->getCurrentFrameTime(); // mPreviousFrameTime -= (5 * frameTimeInterval); } mPreviousFrameTime += frameTimeInterval; MpBufPtr buffer; unsigned int numFramesNotPlayed; unsigned int numFramedBufferedBehind; MpFrameTime frameToFetch; // Use temp variable for frame time to prevent frame time drift in case // of device hiccup. frameToFetch = mPreviousFrameTime; OsStatus getResult = mpInputDeviceManager->getFrame(mDeviceId, frameToFetch, buffer, numFramesNotPlayed, numFramedBufferedBehind); printf("MprFromInputDevice::doProcessFrame() frameToFetch=%d, getResult=%d, numFramesNotPlayed=%d, numFramedBufferedBehind=%d\n", frameToFetch, getResult, numFramesNotPlayed, numFramedBufferedBehind); if(getResult != OS_SUCCESS) { while (getResult == OS_NOT_FOUND && numFramedBufferedBehind == 0 && numFramesNotPlayed > 0) { printf("+ %d numFramesNotPlayed=%d, numFramedBufferedBehind=%d\n", mPreviousFrameTime, numFramesNotPlayed, numFramedBufferedBehind); mPreviousFrameTime += frameTimeInterval; frameToFetch = mPreviousFrameTime; getResult = mpInputDeviceManager->getFrame(mDeviceId, frameToFetch, buffer, numFramesNotPlayed, numFramedBufferedBehind); } while (getResult == OS_NOT_FOUND && numFramedBufferedBehind > 0 && numFramesNotPlayed == 0) { printf("- %d numFramesNotPlayed=%d, numFramedBufferedBehind=%d\n", mPreviousFrameTime, numFramesNotPlayed, numFramedBufferedBehind); mPreviousFrameTime -= frameTimeInterval; frameToFetch = mPreviousFrameTime; getResult = mpInputDeviceManager->getFrame(mDeviceId, frameToFetch, buffer, numFramesNotPlayed, numFramedBufferedBehind); } } if (!mFrameTimeInitialized) { if (getResult == OS_SUCCESS) { mPreviousFrameTime = frameToFetch; mFrameTimeInitialized = TRUE; } } outBufs[0] = buffer; return getResult; } /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before> /* Z80 Machine Emulation Module for Python. https://github.com/kosarev/z80 Copyright (C) 2019 Ivan Kosarev. ivan@kosarev.info Published under the MIT license. */ #include <Python.h> #include <algorithm> #include <cstring> #include <new> #include "../z80.h" namespace { using z80::fast_u8; using z80::fast_u16; using z80::fast_u32; using z80::least_u8; using z80::least_u16; using z80::least_u32; using z80::unused; using z80::get_low8; using z80::get_high8; using z80::make16; using z80::iregp; static inline void split16(least_u8 &h, least_u8 &l, fast_u16 n) { h = get_high8(n); l = get_low8(n); } class decref_guard { public: decref_guard(PyObject *object) : object(object) {} ~decref_guard() { if(object) Py_XDECREF(object); } explicit operator bool () const { return object != nullptr; } PyObject *get() const { return object; } private: PyObject *object; }; template<typename B, typename S> class machine : public B { public: typedef B base; typedef S machine_state; machine() {} machine_state &get_state() { return state; } fast_u8 on_read(fast_u16 addr) { assert(addr < z80::address_space_size); return state.memory[addr]; } void on_write(fast_u16 addr, fast_u8 n) { assert(addr < z80::address_space_size); state.memory[addr] = n; } fast_u8 on_input(fast_u16 addr) { const fast_u8 default_value = 0xff; if(!on_input_callback) return default_value; PyObject *arg = Py_BuildValue("(i)", addr); decref_guard arg_guard(arg); PyObject *result = PyObject_CallObject(on_input_callback, arg); decref_guard result_guard(result); if(!result) { assert(0); // TODO: stop(); return default_value; } if(!PyLong_Check(result)) { PyErr_SetString(PyExc_TypeError, "returning value must be integer"); assert(0); // TODO: stop(); return default_value; } return z80::mask8(PyLong_AsUnsignedLong(result)); } PyObject *set_input_callback(PyObject *callback) { PyObject *old_callback = on_input_callback; on_input_callback = callback; return old_callback; } fast_u8 on_get_b() const { return state.b; } void on_set_b(fast_u8 n) { state.b = n; } fast_u8 on_get_c() const { return state.c; } void on_set_c(fast_u8 n) { state.c = n; } fast_u8 on_get_d() const { return state.d; } void on_set_d(fast_u8 n) { state.d = n; } fast_u8 on_get_e() const { return state.e; } void on_set_e(fast_u8 n) { state.e = n; } fast_u8 on_get_h() const { return state.h; } void on_set_h(fast_u8 n) { state.h = n; } fast_u8 on_get_l() const { return state.l; } void on_set_l(fast_u8 n) { state.l = n; } fast_u8 on_get_a() const { return state.a; } void on_set_a(fast_u8 n) { state.a = n; } fast_u8 on_get_f() const { return state.f; } void on_set_f(fast_u8 n) { state.f = n; } fast_u8 on_get_ixh() const { return state.ixh; } void on_set_ixh(fast_u8 n) { state.ixh = n; } fast_u8 on_get_ixl() const { return state.ixl; } void on_set_ixl(fast_u8 n) { state.ixl = n; } fast_u8 on_get_iyh() const { return state.iyh; } void on_set_iyh(fast_u8 n) { state.iyh = n; } fast_u8 on_get_iyl() const { return state.iyl; } void on_set_iyl(fast_u8 n) { state.iyl = n; } fast_u16 on_get_bc() const { return make16(state.b, state.c); } void on_set_bc(fast_u16 n) { split16(state.b, state.c, n); } fast_u16 on_get_de() const { return make16(state.d, state.e); } void on_set_de(fast_u16 n) { split16(state.d, state.e, n); } fast_u16 on_get_hl() const { return make16(state.h, state.l); } void on_set_hl(fast_u16 n) { split16(state.h, state.l, n); } fast_u16 on_get_af() const { return make16(state.a, state.f); } void on_set_af(fast_u16 n) { split16(state.a, state.f, n); } fast_u16 on_get_ix() const { return make16(state.ixh, state.ixl); } void on_set_ix(fast_u16 n) { split16(state.ixh, state.ixl, n); } fast_u16 on_get_iy() const { return make16(state.iyh, state.iyl); } void on_set_iy(fast_u16 n) { split16(state.iyh, state.iyl, n); } fast_u8 on_get_i() const { return state.i; } void on_set_i(fast_u8 n) { state.i = n; } fast_u8 on_get_r() const { return state.r; } void on_set_r(fast_u8 n) { state.r = n; } fast_u16 on_get_ir() const { return make16(state.i, state.r); } fast_u16 on_get_pc() const { return state.pc; } void on_set_pc(fast_u16 n) { state.pc = n; } fast_u16 on_get_sp() const { return state.sp; } void on_set_sp(fast_u16 n) { state.sp = n; } fast_u16 on_get_wz() const { return state.wz; } void on_set_wz(fast_u16 n) { state.wz = n; } fast_u16 on_get_last_read_addr() const { return state.last_read_addr; } void on_set_last_read_addr(fast_u16 n) { state.last_read_addr = n; } iregp on_get_iregp_kind() const { return static_cast<iregp>(state.irp_kind); } void on_set_iregp_kind(iregp irp) { state.irp_kind = static_cast<least_u8>(irp); } bool on_is_int_disabled() const { return state.int_disabled; } void on_set_is_int_disabled(bool f) { state.int_disabled = f; } bool on_get_iff() const { return state.iff != 0; } void on_set_iff(bool f) { state.iff = f; } bool on_get_iff1() const { return state.iff1 != 0; } void on_set_iff1(bool f) { state.iff1 = f; } bool on_get_iff2() const { return state.iff2 != 0; } void on_set_iff2(bool f) { state.iff2 = f; } unsigned on_get_int_mode() const { return state.int_mode; } void on_set_int_mode(unsigned mode) { state.int_mode = mode; } bool on_is_halted() const { return state.halted; } void on_set_is_halted(bool f) { state.halted = f; } void on_ex_af_alt_af_regs() { std::swap(state.a, state.alt_a); std::swap(state.f, state.alt_f); } void on_ex_de_hl_regs() { std::swap(state.d, state.h); std::swap(state.e, state.l); } void on_exx_regs() { std::swap(state.b, state.alt_b); std::swap(state.c, state.alt_c); std::swap(state.d, state.alt_d); std::swap(state.e, state.alt_e); std::swap(state.h, state.alt_h); std::swap(state.l, state.alt_l); } void on_tick(unsigned t) { base::on_tick(t); // Handle stopping by hitting a specified number of ticks. if(state.ticks_to_stop) { if(state.ticks_to_stop > t) { state.ticks_to_stop -= t; } else { state.ticks_to_stop = 0; self().on_raise_events(z80::events_mask::ticks_limit_hit); } } } #if 0 // TODO void on_step() { fprintf(stderr, "PC=%04x SP=%04x BC=%04x DE=%04x HL=%04x AF=%04x %02x%02x%02x%02x\n", static_cast<unsigned>(state.pc), static_cast<unsigned>(state.sp), static_cast<unsigned>(make16(state.b, state.c)), static_cast<unsigned>(make16(state.d, state.e)), static_cast<unsigned>(make16(state.h, state.l)), static_cast<unsigned>(make16(state.a, state.f)), static_cast<unsigned>(state.memory[(state.pc + 0) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 1) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 2) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 3) & 0xffff])); base::on_step(); } #endif protected: using base::self; private: machine_state state; PyObject *on_input_callback = nullptr; }; static const unsigned max_instr_size = 4; template<typename B> class disasm_base : public B { public: typedef B base; disasm_base() {} const char *get_output() const { return output_buff; } void on_emit(const char *out) { std::snprintf(output_buff, max_output_buff_size, "%s", out); } fast_u8 on_read_next_byte() { assert(index < instr_size); return instr_code[index++]; } void set_instr_code(const least_u8 *code, unsigned size) { assert(size <= max_instr_size); std::memset(instr_code, 0, max_instr_size); std::memcpy(instr_code, code, size); index = 0; output_buff[0] = '\0'; } unsigned get_num_of_consumed_bytes() const { return index; } private: unsigned index = 0; least_u8 instr_code[max_instr_size]; static const std::size_t max_output_buff_size = 32; char output_buff[max_output_buff_size]; }; namespace i8080_machine { #define I8080_MACHINE #include "machine.inc" #undef I8080_MACHINE } namespace z80_machine { #define Z80_MACHINE #include "machine.inc" #undef Z80_MACHINE } static PyModuleDef module = { PyModuleDef_HEAD_INIT, // m_base "z80._z80", // m_name "Z80 Machine Emulation Module", // m_doc -1, // m_size nullptr, // m_methods nullptr, // m_slots nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; } // anonymous namespace extern "C" PyMODINIT_FUNC PyInit__z80(void) { PyObject *m = PyModule_Create(&module); if(!m) return nullptr; if(PyType_Ready(&z80_machine::type_object) < 0) return nullptr; if(PyType_Ready(&i8080_machine::type_object) < 0) return nullptr; Py_INCREF(&z80_machine::type_object); Py_INCREF(&i8080_machine::type_object); // TODO: Check the returning value. PyModule_AddObject(m, "_Z80Machine", &z80_machine::type_object.ob_base.ob_base); PyModule_AddObject(m, "_I8080Machine", &i8080_machine::type_object.ob_base.ob_base); return m; } <commit_msg>[disasm] Prefix operands disassembled instructions with format characters.<commit_after> /* Z80 Machine Emulation Module for Python. https://github.com/kosarev/z80 Copyright (C) 2019 Ivan Kosarev. ivan@kosarev.info Published under the MIT license. */ #include <Python.h> #include <algorithm> #include <cstring> #include <new> #include "../z80.h" namespace { using z80::fast_u8; using z80::fast_u16; using z80::fast_u32; using z80::least_u8; using z80::least_u16; using z80::least_u32; using z80::unused; using z80::get_low8; using z80::get_high8; using z80::make16; using z80::iregp; static inline void split16(least_u8 &h, least_u8 &l, fast_u16 n) { h = get_high8(n); l = get_low8(n); } class decref_guard { public: decref_guard(PyObject *object) : object(object) {} ~decref_guard() { if(object) Py_XDECREF(object); } explicit operator bool () const { return object != nullptr; } PyObject *get() const { return object; } private: PyObject *object; }; template<typename B, typename S> class machine : public B { public: typedef B base; typedef S machine_state; machine() {} machine_state &get_state() { return state; } fast_u8 on_read(fast_u16 addr) { assert(addr < z80::address_space_size); return state.memory[addr]; } void on_write(fast_u16 addr, fast_u8 n) { assert(addr < z80::address_space_size); state.memory[addr] = n; } fast_u8 on_input(fast_u16 addr) { const fast_u8 default_value = 0xff; if(!on_input_callback) return default_value; PyObject *arg = Py_BuildValue("(i)", addr); decref_guard arg_guard(arg); PyObject *result = PyObject_CallObject(on_input_callback, arg); decref_guard result_guard(result); if(!result) { assert(0); // TODO: stop(); return default_value; } if(!PyLong_Check(result)) { PyErr_SetString(PyExc_TypeError, "returning value must be integer"); assert(0); // TODO: stop(); return default_value; } return z80::mask8(PyLong_AsUnsignedLong(result)); } PyObject *set_input_callback(PyObject *callback) { PyObject *old_callback = on_input_callback; on_input_callback = callback; return old_callback; } fast_u8 on_get_b() const { return state.b; } void on_set_b(fast_u8 n) { state.b = n; } fast_u8 on_get_c() const { return state.c; } void on_set_c(fast_u8 n) { state.c = n; } fast_u8 on_get_d() const { return state.d; } void on_set_d(fast_u8 n) { state.d = n; } fast_u8 on_get_e() const { return state.e; } void on_set_e(fast_u8 n) { state.e = n; } fast_u8 on_get_h() const { return state.h; } void on_set_h(fast_u8 n) { state.h = n; } fast_u8 on_get_l() const { return state.l; } void on_set_l(fast_u8 n) { state.l = n; } fast_u8 on_get_a() const { return state.a; } void on_set_a(fast_u8 n) { state.a = n; } fast_u8 on_get_f() const { return state.f; } void on_set_f(fast_u8 n) { state.f = n; } fast_u8 on_get_ixh() const { return state.ixh; } void on_set_ixh(fast_u8 n) { state.ixh = n; } fast_u8 on_get_ixl() const { return state.ixl; } void on_set_ixl(fast_u8 n) { state.ixl = n; } fast_u8 on_get_iyh() const { return state.iyh; } void on_set_iyh(fast_u8 n) { state.iyh = n; } fast_u8 on_get_iyl() const { return state.iyl; } void on_set_iyl(fast_u8 n) { state.iyl = n; } fast_u16 on_get_bc() const { return make16(state.b, state.c); } void on_set_bc(fast_u16 n) { split16(state.b, state.c, n); } fast_u16 on_get_de() const { return make16(state.d, state.e); } void on_set_de(fast_u16 n) { split16(state.d, state.e, n); } fast_u16 on_get_hl() const { return make16(state.h, state.l); } void on_set_hl(fast_u16 n) { split16(state.h, state.l, n); } fast_u16 on_get_af() const { return make16(state.a, state.f); } void on_set_af(fast_u16 n) { split16(state.a, state.f, n); } fast_u16 on_get_ix() const { return make16(state.ixh, state.ixl); } void on_set_ix(fast_u16 n) { split16(state.ixh, state.ixl, n); } fast_u16 on_get_iy() const { return make16(state.iyh, state.iyl); } void on_set_iy(fast_u16 n) { split16(state.iyh, state.iyl, n); } fast_u8 on_get_i() const { return state.i; } void on_set_i(fast_u8 n) { state.i = n; } fast_u8 on_get_r() const { return state.r; } void on_set_r(fast_u8 n) { state.r = n; } fast_u16 on_get_ir() const { return make16(state.i, state.r); } fast_u16 on_get_pc() const { return state.pc; } void on_set_pc(fast_u16 n) { state.pc = n; } fast_u16 on_get_sp() const { return state.sp; } void on_set_sp(fast_u16 n) { state.sp = n; } fast_u16 on_get_wz() const { return state.wz; } void on_set_wz(fast_u16 n) { state.wz = n; } fast_u16 on_get_last_read_addr() const { return state.last_read_addr; } void on_set_last_read_addr(fast_u16 n) { state.last_read_addr = n; } iregp on_get_iregp_kind() const { return static_cast<iregp>(state.irp_kind); } void on_set_iregp_kind(iregp irp) { state.irp_kind = static_cast<least_u8>(irp); } bool on_is_int_disabled() const { return state.int_disabled; } void on_set_is_int_disabled(bool f) { state.int_disabled = f; } bool on_get_iff() const { return state.iff != 0; } void on_set_iff(bool f) { state.iff = f; } bool on_get_iff1() const { return state.iff1 != 0; } void on_set_iff1(bool f) { state.iff1 = f; } bool on_get_iff2() const { return state.iff2 != 0; } void on_set_iff2(bool f) { state.iff2 = f; } unsigned on_get_int_mode() const { return state.int_mode; } void on_set_int_mode(unsigned mode) { state.int_mode = mode; } bool on_is_halted() const { return state.halted; } void on_set_is_halted(bool f) { state.halted = f; } void on_ex_af_alt_af_regs() { std::swap(state.a, state.alt_a); std::swap(state.f, state.alt_f); } void on_ex_de_hl_regs() { std::swap(state.d, state.h); std::swap(state.e, state.l); } void on_exx_regs() { std::swap(state.b, state.alt_b); std::swap(state.c, state.alt_c); std::swap(state.d, state.alt_d); std::swap(state.e, state.alt_e); std::swap(state.h, state.alt_h); std::swap(state.l, state.alt_l); } void on_tick(unsigned t) { base::on_tick(t); // Handle stopping by hitting a specified number of ticks. if(state.ticks_to_stop) { if(state.ticks_to_stop > t) { state.ticks_to_stop -= t; } else { state.ticks_to_stop = 0; self().on_raise_events(z80::events_mask::ticks_limit_hit); } } } #if 0 // TODO void on_step() { fprintf(stderr, "PC=%04x SP=%04x BC=%04x DE=%04x HL=%04x AF=%04x %02x%02x%02x%02x\n", static_cast<unsigned>(state.pc), static_cast<unsigned>(state.sp), static_cast<unsigned>(make16(state.b, state.c)), static_cast<unsigned>(make16(state.d, state.e)), static_cast<unsigned>(make16(state.h, state.l)), static_cast<unsigned>(make16(state.a, state.f)), static_cast<unsigned>(state.memory[(state.pc + 0) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 1) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 2) & 0xffff]), static_cast<unsigned>(state.memory[(state.pc + 3) & 0xffff])); base::on_step(); } #endif protected: using base::self; private: machine_state state; PyObject *on_input_callback = nullptr; }; static const unsigned max_instr_size = 4; static constexpr inline unsigned get_char_code(char c) { return static_cast<unsigned char>(c); } template<typename B> class disasm_base : public B { public: typedef B base; disasm_base() {} const char *get_output() const { return output_buff; } void on_emit(const char *out) { std::snprintf(output_buff, max_output_buff_size, "%s", out); } void on_format_char(char c, const void **&args, typename base::output_buff &out) { unsigned n = get_char_code(c); if(get_char_code('A') <= n && n <= get_char_code('Z')) out.append(c); base::on_format_char(c, args, out); } fast_u8 on_read_next_byte() { assert(index < instr_size); return instr_code[index++]; } void set_instr_code(const least_u8 *code, unsigned size) { assert(size <= max_instr_size); std::memset(instr_code, 0, max_instr_size); std::memcpy(instr_code, code, size); index = 0; output_buff[0] = '\0'; } unsigned get_num_of_consumed_bytes() const { return index; } private: unsigned index = 0; least_u8 instr_code[max_instr_size]; static const std::size_t max_output_buff_size = 32; char output_buff[max_output_buff_size]; }; namespace i8080_machine { #define I8080_MACHINE #include "machine.inc" #undef I8080_MACHINE } namespace z80_machine { #define Z80_MACHINE #include "machine.inc" #undef Z80_MACHINE } static PyModuleDef module = { PyModuleDef_HEAD_INIT, // m_base "z80._z80", // m_name "Z80 Machine Emulation Module", // m_doc -1, // m_size nullptr, // m_methods nullptr, // m_slots nullptr, // m_traverse nullptr, // m_clear nullptr, // m_free }; } // anonymous namespace extern "C" PyMODINIT_FUNC PyInit__z80(void) { PyObject *m = PyModule_Create(&module); if(!m) return nullptr; if(PyType_Ready(&z80_machine::type_object) < 0) return nullptr; if(PyType_Ready(&i8080_machine::type_object) < 0) return nullptr; Py_INCREF(&z80_machine::type_object); Py_INCREF(&i8080_machine::type_object); // TODO: Check the returning value. PyModule_AddObject(m, "_Z80Machine", &z80_machine::type_object.ob_base.ob_base); PyModule_AddObject(m, "_I8080Machine", &i8080_machine::type_object.ob_base.ob_base); return m; } <|endoftext|>
<commit_before>// // This sample demonstrates the VboMesh class by creating a simple Plane mesh with a texture mapped onto it. // The mesh has static indices and texture coordinates, but its vertex positions are dynamic. // #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/VboMesh.h" #include "cinder/gl/Shader.h" #include "cinder/gl/Texture.h" #include "cinder/GeomIO.h" #include "cinder/MayaCamUI.h" #include "cinder/ImageIo.h" #include "Resources.h" using namespace ci; using namespace ci::app; using std::vector; const int VERTICES_X = 200; const int VERTICES_Z = 50; class VboSampleApp : public App { public: void setup() override; void update() override; void draw() override; void keyDown( KeyEvent event ) override; void mouseDown( MouseEvent event ) override; void mouseDrag( MouseEvent event ) override; private: gl::VboMeshRef mVboMesh; gl::TextureRef mTexture; MayaCamUI mMayaCam; }; void VboSampleApp::setup() { auto plane = geom::Plane().size( vec2( 20, 20 ) ).subdivisions( ivec2( VERTICES_X, VERTICES_Z ) ); vector<gl::VboMesh::Layout> bufferLayout = { gl::VboMesh::Layout().usage( GL_DYNAMIC_DRAW ).attrib( geom::Attrib::POSITION, 3 ), gl::VboMesh::Layout().usage( GL_STATIC_DRAW ).attrib( geom::Attrib::TEX_COORD_0, 2 ) }; mVboMesh = gl::VboMesh::create( plane, bufferLayout ); mTexture = gl::Texture::create( loadImage( loadResource( RES_IMAGE ) ), gl::Texture::Format().loadTopDown() ); } void VboSampleApp::keyDown( KeyEvent event ) { if( event.getChar() == 'w' ) gl::setWireframeEnabled( ! gl::isWireframeEnabled() ); } void VboSampleApp::mouseDown( MouseEvent event ) { mMayaCam.mouseDown( event.getPos() ); } void VboSampleApp::mouseDrag( MouseEvent event ) { #if defined( CINDER_MAC ) // remapping key modifiers so mayacam is usable on a mac touchpad bool isLeftDown = event.isLeftDown(); bool isMiddleDown = event.isAltDown(); bool isRightDown = event.isMetaDown(); if( isMiddleDown ) isLeftDown = false; mMayaCam.mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown ); #else mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); #endif } void VboSampleApp::update() { const float zFreq = 0.9325f; const float xFreq = 1.3467f; float offset = getElapsedSeconds() * 5.0f; // Dynmaically generate our new positions based on a sin(x) + cos(z) wave // We set 'orphanExisting' to false so that we can also read from the position buffer, though keep // in mind that this isn't the most efficient way to do cpu-side updates. Consider using VboMesh::bufferAttrib() as well. auto mappedPosAttrib = mVboMesh->mapAttrib3f( geom::Attrib::POSITION, false ); for( int i = 0; i < mVboMesh->getNumVertices(); i++ ) { vec3 &pos = *mappedPosAttrib; (*mappedPosAttrib).y = ( sinf( pos.x * xFreq + offset ) + cosf( pos.z * zFreq + offset ) ) / 4.0f;; ++mappedPosAttrib; } mappedPosAttrib.unmap(); } void VboSampleApp::draw() { gl::clear( Color( 0.15f, 0.15f, 0.15f ) ); gl::setMatrices( mMayaCam.getCamera() ); gl::ScopedGlslProg glslScope( gl::getStockShader( gl::ShaderDef().texture() ) ); gl::ScopedTextureBind texScope( mTexture ); gl::draw( mVboMesh ); } CINDER_APP( VboSampleApp, RendererGl ) <commit_msg>more sample improvements<commit_after>// // This sample demonstrates basic usage of the VboMesh class by creating a simple Plane mesh // with a texture mapped onto it. The mesh has static indices and texture coordinates, but // its vertex positions are dynamic. // #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/VboMesh.h" #include "cinder/GeomIO.h" #include "cinder/ImageIo.h" #include "cinder/MayaCamUI.h" #include "Resources.h" using namespace ci; using namespace ci::app; using std::vector; class VboSampleApp : public App { public: void setup() override; void update() override; void draw() override; void keyDown( KeyEvent event ) override; void mouseDown( MouseEvent event ) override; void mouseDrag( MouseEvent event ) override; private: gl::VboMeshRef mVboMesh; gl::TextureRef mTexture; MayaCamUI mMayaCam; }; void VboSampleApp::setup() { auto plane = geom::Plane().size( vec2( 20, 20 ) ).subdivisions( ivec2( 200, 50 ) ); vector<gl::VboMesh::Layout> bufferLayout = { gl::VboMesh::Layout().usage( GL_DYNAMIC_DRAW ).attrib( geom::Attrib::POSITION, 3 ), gl::VboMesh::Layout().usage( GL_STATIC_DRAW ).attrib( geom::Attrib::TEX_COORD_0, 2 ) }; mVboMesh = gl::VboMesh::create( plane, bufferLayout ); mTexture = gl::Texture::create( loadImage( loadResource( RES_IMAGE ) ), gl::Texture::Format().loadTopDown() ); } void VboSampleApp::keyDown( KeyEvent event ) { if( event.getChar() == 'w' ) gl::setWireframeEnabled( ! gl::isWireframeEnabled() ); } void VboSampleApp::mouseDown( MouseEvent event ) { mMayaCam.mouseDown( event.getPos() ); } void VboSampleApp::mouseDrag( MouseEvent event ) { #if defined( CINDER_MAC ) // remapping key modifiers so mayacam is usable on a mac touchpad bool isLeftDown = event.isLeftDown(); bool isMiddleDown = event.isAltDown(); bool isRightDown = event.isMetaDown(); if( isMiddleDown ) isLeftDown = false; mMayaCam.mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown ); #else mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); #endif } void VboSampleApp::update() { float offset = getElapsedSeconds() * 4.0f; // Dynmaically generate our new positions based on a sin(x) + cos(z) wave // We set 'orphanExisting' to false so that we can also read from the position buffer, though keep // in mind that this isn't the most efficient way to do cpu-side updates. Consider using VboMesh::bufferAttrib() as well. auto mappedPosAttrib = mVboMesh->mapAttrib3f( geom::Attrib::POSITION, false ); for( int i = 0; i < mVboMesh->getNumVertices(); i++ ) { vec3 &pos = *mappedPosAttrib; mappedPosAttrib->y = sinf( pos.x * 1.1467f + offset ) * 0.323f + cosf( pos.z * 0.7325f + offset ) * 0.431f; ++mappedPosAttrib; } mappedPosAttrib.unmap(); } void VboSampleApp::draw() { gl::clear( Color( 0.15f, 0.15f, 0.15f ) ); gl::setMatrices( mMayaCam.getCamera() ); gl::ScopedGlslProg glslScope( gl::getStockShader( gl::ShaderDef().texture() ) ); gl::ScopedTextureBind texScope( mTexture ); gl::draw( mVboMesh ); } CINDER_APP( VboSampleApp, RendererGl ) <|endoftext|>
<commit_before>/* * * Author: Jeffrey Leung * Last edited: 2015-09-17 * * This header files contains enums necessary to create and navigate a Room. * */ #pragma once enum class Direction { kNone, kNorth, kEast, kSouth, kWest, }; enum class RoomBorder { kWall, kRoom, kExit, }; enum class Inhabitant { kNone, kMinotaur, kMinotaurDead, kMirror, kMirrorCracked, }; enum class Item { kNone, kBullet, kTreasure, kTreasureGone, }; <commit_msg>Fixing typo.<commit_after>/* * * Author: Jeffrey Leung * Last edited: 2015-09-17 * * This header file contains enums necessary to create and navigate a Room. * */ #pragma once enum class Direction { kNone, kNorth, kEast, kSouth, kWest, }; enum class RoomBorder { kWall, kRoom, kExit, }; enum class Inhabitant { kNone, kMinotaur, kMinotaurDead, kMirror, kMirrorCracked, }; enum class Item { kNone, kBullet, kTreasure, kTreasureGone, }; <|endoftext|>
<commit_before>#include "parse.h" #include "lit.h" #include "lex.h" #include "expr.h" #include "token.h" #include "util.h" #include "var.h" #include "codegen.h" #include "exprtype.h" #include "func.h" AST *Parser::make_break() { if(tok.skip("break")) return new BreakAST(); return NULL; } AST *Parser::make_return() { if(tok.skip("return")) { AST *expr = expr_entry(); return new ReturnAST(expr); } return NULL; } AST *Parser::expression() { if(tok.skip("def")) return make_func(); else if(tok.is("proto")) return make_proto(); else if(tok.is("struct")) return make_struct(); else if(tok.is("module")) return make_module(); else if(tok.is("lib")) return make_lib(); else if(tok.is("for")) return make_for(); else if(tok.is("while")) return make_while(); else if(tok.is("return")) return make_return(); else if(tok.is("if")) return make_if(); else if(tok.is("break")) return make_break(); else if(tok.is("else") || tok.is("elsif") || tok.is("end")) return NULL; else return expr_entry(); return NULL; } ast_vector Parser::eval() { ast_vector block; while(tok.pos < tok.size) { while(tok.skip(";")) if(tok.pos >= tok.size) break; AST *b = expression(); while(tok.skip(";")) if(tok.pos >= tok.size) break; if(b == NULL) break; block.push_back(b); } return block; } llvm::Module *Parser::parser() { tok.pos = 0; blocksCount = 0; op_prec[".."] = 50; op_prec["..."] =50; op_prec["="] = 100; op_prec["+="] = 100; op_prec["-="] = 100; op_prec["*="] = 100; op_prec["/="] = 100; op_prec["%="] = 100; op_prec["^="] = 100; op_prec["|="] = 100; op_prec["&="] = 100; op_prec["=="] = 200; op_prec["!="] = 200; op_prec["<="] = 200; op_prec[">="] = 200; op_prec["<"] = 200; op_prec[">"] = 200; op_prec["&"] = 150; op_prec["|"] = 150; op_prec["^"] = 150; op_prec["+"] = 300; op_prec["-"] = 300; op_prec["?"] = 300; op_prec["*"] = 400; op_prec["/"] = 400; op_prec["%"] = 400; // append standard functions to a list of declared functions append_func(std::vector<std::string>(1, "Array")); append_func(std::vector<std::string>(1, "GC")); append_func(std::vector<std::string>(1, "printf")); append_func(std::vector<std::string>(1, "gets")); append_func(std::vector<std::string>(1, "strlen")); append_func(std::vector<std::string>(1, "builtinlength")); append_func(std::vector<std::string>(1, "puts")); append_func(std::vector<std::string>(1, "print")); // 'print' is almost the same as 'puts' but 'print' doesn't new line append_func(std::vector<std::string>(1, "gets")); append_func(std::vector<std::string>(1, "str_to_int")); append_func(std::vector<std::string>(1, "str_to_float")); append_func(std::vector<std::string>(1, "int_to_str")); append_func(std::vector<std::string>(1, "int64_to_str")); append_func(std::vector<std::string>(1, "float_to_str")); ast_vector a = eval(); // std::cout << "\n---------- abstract syntax tree ----------" << std::endl; // for(int i = 0; i < a.size(); i++) // visit(a[i]), std::cout << std::endl; llvm::Module *program_mod = Codegen::codegen(a); // start code generating // std::cout << "\n---------- end of abstract syntax tree --" << std::endl; return program_mod; } AST *Parser::make_lib() { if(tok.skip("lib")) { std::string name = tok.next().val; ast_vector proto = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new LibraryAST(name, proto); } return NULL; } AST *Parser::make_proto() { if(tok.skip("proto")) { std::string func_name = tok.next().val; ast_vector args; func_t function = { .name = func_name, .type = T_INT }; bool is_parentheses = false; if((is_parentheses=tok.skip("(")) || is_ident_tok()) { // get params do { args.push_back(expr_primary()); } while(tok.skip(",") || is_ident_tok()); if(is_parentheses) { if(!tok.skip(")")) error("error: %d: expected expression ')'", tok.get().nline); } } function.params = args.size(); if(tok.skip(":")) { ExprType *type = Type::str_to_type(tok.next().val); if(tok.skip("[]")) { type->change(T_ARRAY, type); } function.type = type; } std::string new_name; if(tok.skip("|")) { new_name = tok.next().val; } append_func(std::vector<std::string>(1, new_name.empty() ? func_name : new_name)); return new PrototypeAST(function, args, new_name); } return NULL; } AST *Parser::make_module() { if(tok.skip("module")) { std::string name = tok.next().val; module.push_back(name); ast_vector body = eval(); module.pop_back(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ModuleAST(name, body); } return nullptr; } AST *Parser::make_struct() { if(tok.skip("struct")) { std::string name = tok.next().val; ast_vector decl_vars = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new StructAST(name, decl_vars); } return NULL; } AST *Parser::make_if() { if(tok.skip("if")) { AST *cond = expr_entry(); ast_vector then = eval(), else_block; if(tok.skip("else")) { else_block = eval(); } else if(tok.is("elsif")) { else_block.push_back(make_elsif()); } if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); AST *i = new IfAST(cond, then, else_block); return i; } return NULL; } AST *Parser::make_elsif() { if(tok.skip("elsif")) { AST *cond = expr_entry(); ast_vector then = eval(), else_block; if(tok.is("elsif")) { else_block.push_back(make_elsif()); } else if(tok.skip("else")) { else_block = eval(); } return new IfAST(cond, then, else_block); } return NULL; } AST *Parser::make_for() { if(tok.skip("for")) { AST *asgmt = expr_entry(); if(tok.skip(",")) { AST *cond = expr_entry(); if(!tok.skip(",")) error("error: %d: expect expression ','", tok.get().nline); AST *step = expr_entry(); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ForAST(asgmt, cond, step, block); } else if(tok.skip("in")) { AST *range = expr_entry(), *cond, *step; if(range->get_type() == AST_BINARY) { BinaryAST *cond_bin = (BinaryAST *)range; AST *var = asgmt; asgmt = new VariableAsgmtAST(asgmt, cond_bin->left); cond = new BinaryAST(cond_bin->op == ".." ? "<=" : /* op=... */ "<", var, cond_bin->right); step = new VariableAsgmtAST(var, new BinaryAST("+", var, new NumberAST("1")) ); } else error("error: %d: invalid expression", tok.get().nline); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ForAST(asgmt, cond, step, block); } else { error("error: %d: unknown syntax", tok.get().nline); } } return NULL; } AST *Parser::make_while() { if(tok.skip("while")) { AST *cond = expr_entry(); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new WhileAST(cond, block); } return NULL; } AST *Parser::make_func() { uint32_t params = 0; ast_vector args, stmt; std::string func_name = tok.next().val; bool is_template = false; if(func_name == "operator") { func_name += tok.next().val; // user-defined operator } else if(func_name == "template") { // template function func_name = tok.next().val; is_template = true; } func_t function = { .name = func_name, .is_template = is_template, .type = T_INT }; { std::vector<std::string> realname = module; realname.push_back(func_name); append_func(realname); } bool is_parentheses = false; if((is_parentheses=tok.skip("(")) || is_ident_tok()) { // get params do { args.push_back(expr_primary()); } while(tok.skip(",") || is_ident_tok()); if(is_parentheses) { if(!tok.skip(")")) error("error: %d: expected expression ')'", tok.get().nline); } } if(tok.skip(":")) { int is_ary = 0; ExprType type(T_INT); type.change(Type::str_to_type(tok.next().val)); while(tok.skip("[]")) { ExprType *elem_ty = &type; type.next = new ExprType(elem_ty); type.change(T_ARRAY); } function.type = type; } stmt = eval(); if(!tok.skip("end")) { error("error: source %d", __LINE__); } return new FunctionAST(function, args, stmt); } bool Parser::is_func(std::vector<std::string> name) { return function_list.count(name) != 0 ? true : false; } void Parser::append_func(std::vector<std::string> name) { function_list[name] = true; } char *replace_escape(char *str) { int i; char *pos; char escape[14][3] = { "\\a", "\a", "\\r", "\r", "\\f", "\f", "\\n", "\n", "\\t", "\t", "\\b", "\b", "\\\"", "\"" }; for(i = 0; i < 14; i += 2) { while((pos = strstr(str, escape[i])) != NULL) { *pos = escape[i + 1][0]; memmove(pos + 1, pos + 2, strlen(str) - 2 + 1); } } return str; } <commit_msg>bug fix<commit_after>#include "parse.h" #include "lit.h" #include "lex.h" #include "expr.h" #include "token.h" #include "util.h" #include "var.h" #include "codegen.h" #include "exprtype.h" #include "func.h" AST *Parser::make_break() { if(tok.skip("break")) return new BreakAST(); return NULL; } AST *Parser::make_return() { if(tok.skip("return")) { AST *expr = expr_entry(); return new ReturnAST(expr); } return NULL; } AST *Parser::expression() { if(tok.skip("def")) return make_func(); else if(tok.is("proto")) return make_proto(); else if(tok.is("struct")) return make_struct(); else if(tok.is("module")) return make_module(); else if(tok.is("lib")) return make_lib(); else if(tok.is("for")) return make_for(); else if(tok.is("while")) return make_while(); else if(tok.is("return")) return make_return(); else if(tok.is("if")) return make_if(); else if(tok.is("break")) return make_break(); else if(tok.is("else") || tok.is("elsif") || tok.is("end")) return NULL; else return expr_entry(); return NULL; } ast_vector Parser::eval() { ast_vector block; while(tok.pos < tok.size) { while(tok.skip(";")) if(tok.pos >= tok.size) break; AST *b = expression(); while(tok.skip(";")) if(tok.pos >= tok.size) break; if(b == NULL) break; block.push_back(b); } return block; } llvm::Module *Parser::parser() { tok.pos = 0; blocksCount = 0; op_prec[".."] = 50; op_prec["..."] =50; op_prec["="] = 100; op_prec["+="] = 100; op_prec["-="] = 100; op_prec["*="] = 100; op_prec["/="] = 100; op_prec["%="] = 100; op_prec["^="] = 100; op_prec["|="] = 100; op_prec["&="] = 100; op_prec["=="] = 200; op_prec["!="] = 200; op_prec["<="] = 200; op_prec[">="] = 200; op_prec["<"] = 200; op_prec[">"] = 200; op_prec["&"] = 150; op_prec["|"] = 150; op_prec["^"] = 150; op_prec["+"] = 300; op_prec["-"] = 300; op_prec["?"] = 300; op_prec["*"] = 400; op_prec["/"] = 400; op_prec["%"] = 400; // append standard functions to a list of declared functions append_func(std::vector<std::string>(1, "Array")); append_func(std::vector<std::string>(1, "GC")); append_func(std::vector<std::string>(1, "printf")); append_func(std::vector<std::string>(1, "gets")); append_func(std::vector<std::string>(1, "strlen")); append_func(std::vector<std::string>(1, "builtinlength")); append_func(std::vector<std::string>(1, "puts")); append_func(std::vector<std::string>(1, "print")); // 'print' is almost the same as 'puts' but 'print' doesn't new line append_func(std::vector<std::string>(1, "gets")); append_func(std::vector<std::string>(1, "str_to_int")); append_func(std::vector<std::string>(1, "str_to_float")); append_func(std::vector<std::string>(1, "int_to_str")); append_func(std::vector<std::string>(1, "int64_to_str")); append_func(std::vector<std::string>(1, "float_to_str")); ast_vector a = eval(); // std::cout << "\n---------- abstract syntax tree ----------" << std::endl; // for(int i = 0; i < a.size(); i++) // visit(a[i]), std::cout << std::endl; llvm::Module *program_mod = Codegen::codegen(a); // start code generating // std::cout << "\n---------- end of abstract syntax tree --" << std::endl; return program_mod; } AST *Parser::make_lib() { if(tok.skip("lib")) { std::string name = tok.next().val; ast_vector proto = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new LibraryAST(name, proto); } return NULL; } AST *Parser::make_proto() { if(tok.skip("proto")) { std::string func_name = tok.next().val; ast_vector args; func_t function = { .name = func_name, .type = T_INT }; bool is_parentheses = false; if((is_parentheses=tok.skip("(")) || is_ident_tok()) { // get params do { args.push_back(expr_primary()); } while(tok.skip(",") || is_ident_tok()); if(is_parentheses) { if(!tok.skip(")")) error("error: %d: expected expression ')'", tok.get().nline); } } function.params = args.size(); if(tok.skip(":")) { ExprType *type = Type::str_to_type(tok.next().val); if(tok.skip("[]")) { type->change(T_ARRAY, type); } function.type = type; } std::string new_name; if(tok.skip("|")) { new_name = tok.next().val; } append_func(std::vector<std::string>(1, new_name.empty() ? func_name : new_name)); return new PrototypeAST(function, args, new_name); } return NULL; } AST *Parser::make_module() { if(tok.skip("module")) { std::string name = tok.next().val; module.push_back(name); ast_vector body = eval(); module.pop_back(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ModuleAST(name, body); } return nullptr; } AST *Parser::make_struct() { if(tok.skip("struct")) { std::string name = tok.next().val; ast_vector decl_vars = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new StructAST(name, decl_vars); } return NULL; } AST *Parser::make_if() { if(tok.skip("if")) { AST *cond = expr_entry(); ast_vector then = eval(), else_block; if(tok.skip("else")) { else_block = eval(); } else if(tok.is("elsif")) { else_block.push_back(make_elsif()); } if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); AST *i = new IfAST(cond, then, else_block); return i; } return NULL; } AST *Parser::make_elsif() { if(tok.skip("elsif")) { AST *cond = expr_entry(); ast_vector then = eval(), else_block; if(tok.is("elsif")) { else_block.push_back(make_elsif()); } else if(tok.skip("else")) { else_block = eval(); } return new IfAST(cond, then, else_block); } return NULL; } AST *Parser::make_for() { if(tok.skip("for")) { AST *asgmt = expr_entry(); if(tok.skip(",")) { AST *cond = expr_entry(); if(!tok.skip(",")) error("error: %d: expect expression ','", tok.get().nline); AST *step = expr_entry(); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ForAST(asgmt, cond, step, block); } else if(tok.skip("in")) { AST *range = expr_entry(), *cond, *step; if(range->get_type() == AST_BINARY) { BinaryAST *cond_bin = (BinaryAST *)range; AST *var = asgmt; asgmt = new VariableAsgmtAST(asgmt, cond_bin->left); cond = new BinaryAST(cond_bin->op == ".." ? "<=" : /* op=... */ "<", var, cond_bin->right); step = new VariableAsgmtAST(var, new BinaryAST("+", var, new NumberAST("1")) ); } else error("error: %d: invalid expression", tok.get().nline); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new ForAST(asgmt, cond, step, block); } else { error("error: %d: unknown syntax", tok.get().nline); } } return NULL; } AST *Parser::make_while() { if(tok.skip("while")) { AST *cond = expr_entry(); ast_vector block = eval(); if(!tok.skip("end")) error("error: %d: expected expression 'end'", tok.get().nline); return new WhileAST(cond, block); } return NULL; } AST *Parser::make_func() { uint32_t params = 0; ast_vector args, stmt; std::string func_name = tok.next().val; bool is_template = false; if(func_name == "operator") { func_name += tok.next().val; // user-defined operator } else if(func_name == "template") { // template function func_name = tok.next().val; is_template = true; } func_t function = { .name = func_name, .is_template = is_template, .type = T_INT }; { std::vector<std::string> realname = module; realname.push_back(func_name); append_func(realname); } bool is_parentheses = false; if((is_parentheses=tok.skip("(")) || is_ident_tok()) { // get params do { args.push_back(expr_primary()); } while(tok.skip(",") || is_ident_tok()); if(is_parentheses) { if(!tok.skip(")")) error("error: %d: expected expression ')'", tok.get().nline); } } if(tok.skip(":")) { int is_ary = 0; ExprType type(T_INT); type.change(Type::str_to_type(tok.next().val)); while(tok.skip("[]")) { ExprType *elem_ty = &type; type.next = new ExprType(elem_ty); type.change(T_ARRAY); } function.type = type; } stmt = eval(); if(!tok.skip("end")) { error("error: source %d", __LINE__); } local_var_list.clear(); return new FunctionAST(function, args, stmt); } bool Parser::is_func(std::vector<std::string> name) { return function_list.count(name) != 0 ? true : false; } void Parser::append_func(std::vector<std::string> name) { function_list[name] = true; } char *replace_escape(char *str) { int i; char *pos; char escape[14][3] = { "\\a", "\a", "\\r", "\r", "\\f", "\f", "\\n", "\n", "\\t", "\t", "\\b", "\b", "\\\"", "\"" }; for(i = 0; i < 14; i += 2) { while((pos = strstr(str, escape[i])) != NULL) { *pos = escape[i + 1][0]; memmove(pos + 1, pos + 2, strlen(str) - 2 + 1); } } return str; } <|endoftext|>
<commit_before>#include "md_parser.hpp" #include "text_line_element.hpp" #include "text_paragraph.hpp" #include "title1_paragraph.hpp" #include "title2_paragraph.hpp" #include "ulist1_paragraph.hpp" using namespace std; namespace { bool string_has_only(const std::string & s, const char & c) { return (s.find_first_not_of(c) == std::string::npos); } template<class T> T max(const T & a, const T & b) { if (a > b) { return a; } else { return b; } } size_t string_startswith(const std::string & s, const char & c) { size_t i(0); while (s[i] == c and i < s.length()){ ++i; } return i; } bool string_startswith(const std::string & s, const std::string & c) { if (s.length() < c.length()) { return false; } size_t i(0); while (s[i] == c[i] and i < c.length() ){ ++i; } if (i != c.length()) { return false; } return true; } std::string string_clear_leading(const std::string & s, const std::string & subset) { return s.substr(s.find_first_not_of(subset)); } }; MdParser::MdParser(const std::string & filename) : Parser(filename) { parse(); } MdParser::~MdParser() { // dtor } void MdParser::parse() { std::string line; _document = new Document(_filename); Paragraph *p0(nullptr), *p1(nullptr); LineElement *e = nullptr, *last_e = nullptr; size_t sharps(0); while (getline(_input_file, line)) { if (line.empty()) { // end of line, change paragraph if (p0 and p0->size()) { _document->append_paragraph(p0); p0 = nullptr; } p0 = new TextParagraph(); } else { sharps = string_startswith(line, '#'); if (!p0) { p0 = new TextParagraph(); } if (sharps != 0) { switch(sharps) { case 1: delete p0; p0 = new Title1Paragraph(); break; case 2: delete p0; p0 = new Title2Paragraph(); break; default: break; } e = new TextLineElement(string_clear_leading(line," \t#")); p0->append_line_element(e); } else if (string_has_only(line, '=')) { // title 1 delimiter p1 = new Title1Paragraph(p0); delete p0; p0 = nullptr; _document->append_paragraph(p1); p1 = nullptr; } else if (string_has_only(line, '-')) { // title 2 delimiter p1 = new Title2Paragraph(p0); delete p0; p0 = nullptr; _document->append_paragraph(p1); p1 = nullptr; } else if (string_startswith(line, "* ")) { // level 1 list delimiter if (p0 and p0->size()) { _document->append_paragraph(p0); delete p0; } p0 = new UList1Paragraph(); e = new TextLineElement(string_clear_leading(line,"* \t#")); p0->append_line_element(e); } else { // other content if (p0->size() && last_e && (last_e->content()).back() != ' ' && line.front() != ' ') { line = " "+line; } e = new TextLineElement(line); p0->append_line_element(e); last_e = e; e = nullptr; } } } if (p0 and p0->size()) { _document->append_paragraph(p0); } } <commit_msg>Do not delete the newly created UList1Paragraph<commit_after>#include "md_parser.hpp" #include "text_line_element.hpp" #include "text_paragraph.hpp" #include "title1_paragraph.hpp" #include "title2_paragraph.hpp" #include "ulist1_paragraph.hpp" using namespace std; namespace { bool string_has_only(const std::string & s, const char & c) { return (s.find_first_not_of(c) == std::string::npos); } template<class T> T max(const T & a, const T & b) { if (a > b) { return a; } else { return b; } } size_t string_startswith(const std::string & s, const char & c) { size_t i(0); while (s[i] == c and i < s.length()){ ++i; } return i; } bool string_startswith(const std::string & s, const std::string & c) { if (s.length() < c.length()) { return false; } size_t i(0); while (s[i] == c[i] and i < c.length() ){ ++i; } if (i != c.length()) { return false; } return true; } std::string string_clear_leading(const std::string & s, const std::string & subset) { return s.substr(s.find_first_not_of(subset)); } }; MdParser::MdParser(const std::string & filename) : Parser(filename) { parse(); } MdParser::~MdParser() { // dtor } void MdParser::parse() { std::string line; _document = new Document(_filename); Paragraph *p0(nullptr), *p1(nullptr); LineElement *e = nullptr, *last_e = nullptr; size_t sharps(0); while (getline(_input_file, line)) { if (line.empty()) { // end of line, change paragraph if (p0 and p0->size()) { _document->append_paragraph(p0); p0 = nullptr; } p0 = new TextParagraph(); } else { sharps = string_startswith(line, '#'); if (!p0) { p0 = new TextParagraph(); } if (sharps != 0) { switch(sharps) { case 1: delete p0; p0 = new Title1Paragraph(); break; case 2: delete p0; p0 = new Title2Paragraph(); break; default: break; } e = new TextLineElement(string_clear_leading(line," \t#")); p0->append_line_element(e); } else if (string_has_only(line, '=')) { // title 1 delimiter p1 = new Title1Paragraph(p0); delete p0; p0 = nullptr; _document->append_paragraph(p1); p1 = nullptr; } else if (string_has_only(line, '-')) { // title 2 delimiter p1 = new Title2Paragraph(p0); delete p0; p0 = nullptr; _document->append_paragraph(p1); p1 = nullptr; } else if (string_startswith(line, "* ")) { // level 1 list delimiter if (p0 and p0->size()) { _document->append_paragraph(p0); p0=nullptr; } p0 = new UList1Paragraph(); e = new TextLineElement(string_clear_leading(line,"* \t#")); p0->append_line_element(e); } else { // other content if (p0->size() && last_e && (last_e->content()).back() != ' ' && line.front() != ' ') { line = " "+line; } e = new TextLineElement(line); p0->append_line_element(e); last_e = e; e = nullptr; } } } if (p0 and p0->size()) { _document->append_paragraph(p0); } } <|endoftext|>
<commit_before>#include "nil.h" #include "nilUtil.h" #include <math.h> HANDLE stopEvent = NULL; // Cosine wave table for color cycling; not really needed for anything BYTE costable[256]={ 0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,3, 3,4,4,5,5,6,7,7,8,9,9,10,11,12,13,13, 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, 31,32,33,34,35,36,38,39,40,41,42,44,45,46,47,49, 50,51,52,53,55,56,57,58,60,61,62,63,64,66,67,68, 69,70,71,72,73,74,76,77,78,79,80,81,82,82,83,84, 85,86,87,88,88,89,90,91,91,92,93,93,94,94,95,95, 96,96,97,97,98,98,98,98,99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,98,98,98,98,97,97,96,96, 95,95,94,94,93,93,92,91,91,90,89,88,88,87,86,85, 84,83,82,82,81,80,79,78,77,76,75,73,72,71,70,69, 68,67,66,64,63,62,61,60,58,57,56,55,53,52,51,50, 49,47,46,45,44,42,41,40,39,38,36,35,34,33,32,31, 29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14, 13,13,12,11,10,9,9,8,7,7,6,5,5,4,4,3, 3,2,2,2,1,1,1,0,0,0,0,0,0,0,0,0 }; // Shared mouse listener class DummyMouseListener: public Nil::MouseListener { public: virtual void onMouseMoved( Nil::Mouse* mouse, const Nil::MouseState& state ) { // } virtual void onMouseButtonPressed( Nil::Mouse* mouse, const Nil::MouseState& state, size_t button ) { printf_s( "Mouse button pressed: %d (%s)\r\n", button, mouse->getDevice()->getName().c_str() ); } virtual void onMouseButtonReleased( Nil::Mouse* mouse, const Nil::MouseState& state, size_t button ) { printf_s( "Mouse button released: %d (%s)\r\n", button, mouse->getDevice()->getName().c_str() ); } virtual void onMouseWheelMoved( Nil::Mouse* mouse, const Nil::MouseState& state ) { printf_s( "Mouse wheel moved: %d (%s)\r\n", state.mWheel.relative, mouse->getDevice()->getName().c_str() ); } }; DummyMouseListener gDummyMouseListener; // Shared keyboard listener class DummyKeyboardListener: public Nil::KeyboardListener { public: virtual void onKeyPressed( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key pressed: 0x%X (%s)\r\n", keycode, keyboard->getDevice()->getName().c_str() ); } virtual void onKeyRepeat( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key repeat: 0x%X (%s)\r\n", keycode, keyboard->getDevice()->getName().c_str() ); } virtual void onKeyReleased( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key released: 0x%X (%s)\r\n", keycode, keyboard->getDevice()->getName().c_str() ); } }; DummyKeyboardListener gDummyKeyboardListener; // Shared controller listener; // A controller is any input device that is not a mouse nor a keyboard class DummyControllerListener: public Nil::ControllerListener { public: virtual void onControllerButtonPressed( Nil::Controller* controller, const Nil::ControllerState& state, size_t button ) { printf_s( "Controller button %d pressed (%s)\r\n", button, controller->getDevice()->getName().c_str() ); } virtual void onControllerButtonReleased( Nil::Controller* controller, const Nil::ControllerState& state, size_t button ) { printf_s( "Controller button %d released (%s)\r\n", button, controller->getDevice()->getName().c_str() ); } virtual void onControllerAxisMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t axis ) { printf_s( "Controller axis %d moved: %f (%s)\r\n", axis, state.mAxes[axis].absolute, controller->getDevice()->getName().c_str() ); } virtual void onControllerSliderMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t slider ) { printf_s( "Controller slider %d moved (%s)\r\n", slider, controller->getDevice()->getName().c_str() ); } virtual void onControllerPOVMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t pov ) { printf_s( "Controller POV %d moved: 0x%08X (%s)\r\n", pov, state.mPOVs[pov].direction, controller->getDevice()->getName().c_str() ); } }; DummyControllerListener gDummyControllerListener; // This is a listener for Logitech's proprietary G-keys on // support keyboard & mice class DummyGKeyListener: public Nil::Logitech::GKeyListener { public: virtual void onGKeyPressed( Nil::Logitech::GKey key ) { printf_s( "G-Key pressed: %d\r\n", key ); } virtual void onGKeyReleased( Nil::Logitech::GKey key ) { printf_s( "G-Key released: %d\r\n", key ); } }; DummyGKeyListener gDummyGKeyListener; // This is the main system listener, which must always exist class MyListener: public Nil::SystemListener { public: virtual void onDeviceConnected( Nil::Device* device ) { printf_s( "Connected: %s\r\n", device->getName().c_str() ); // Enable any device instantly when it is connected device->enable(); } virtual void onDeviceDisconnected( Nil::Device* device ) { printf_s( "Disconnected: %s\r\n", device->getName().c_str() ); } virtual void onMouseEnabled( Nil::Device* device, Nil::Mouse* instance ) { printf_s( "Mouse enabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Add our listener for every mouse that is enabled instance->addListener( &gDummyMouseListener ); } virtual void onKeyboardEnabled( Nil::Device* device, Nil::Keyboard* instance ) { printf_s( "Keyboard enabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Add our listener for every keyboard that is enabled instance->addListener( &gDummyKeyboardListener ); } virtual void onControllerEnabled( Nil::Device* device, Nil::Controller* instance ) { printf_s( "Controller enabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Add our listener for every controller that is enabled instance->addListener( &gDummyControllerListener ); } virtual void onMouseDisabled( Nil::Device* device, Nil::Mouse* instance ) { printf_s( "Mouse disabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } virtual void onKeyboardDisabled( Nil::Device* device, Nil::Keyboard* instance ) { printf_s( "Keyboard disabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } virtual void onControllerDisabled( Nil::Device* device, Nil::Controller* instance ) { printf_s( "Controller disabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } }; MyListener gMyListener; BOOL WINAPI consoleHandler( DWORD ctrl ) { if ( ctrl == CTRL_C_EVENT || ctrl == CTRL_CLOSE_EVENT ) { SetEvent( stopEvent ); return TRUE; } return FALSE; } int wmain( int argc, wchar_t* argv[], wchar_t* envp[] ) { #ifndef _DEBUG try { #endif // Create quit event & set handler stopEvent = CreateEventW( 0, FALSE, FALSE, 0 ); SetConsoleCtrlHandler( consoleHandler, TRUE ); // Init system Nil::System* system = new Nil::System( GetModuleHandleW( nullptr ), GetConsoleWindow(), // Using background cooperation mode, because the default console window // is actually not owned by our process (it is owned by cmd.exe) and thus // we would not receive any mouse & keyboard events in foreground mode. // For applications that own their own window foreground mode works fine. Nil::Cooperation_Background, &gMyListener ); // Init Logitech G-keys subsystem, if available Nil::ExternalModule::InitReturn ret = system->getLogitechGKeys()->initialize(); if ( ret == Nil::ExternalModule::Initialization_OK ) { printf_s( "G-keys initialized\r\n" ); system->getLogitechGKeys()->addListener( &gDummyGKeyListener ); } else printf_s( "G-keys initialization failed with 0x%X\r\n", ret ); // Init Logitech LED subsytem, if available ret = system->getLogitechLEDs()->initialize(); if ( ret == Nil::ExternalModule::Initialization_OK ) printf_s( "LEDs initialized\r\n" ); else printf_s( "LEDs initialization failed with 0x%X\r\n", ret ); // Enable all initially connected devices for ( auto device : system->getDevices() ) device->enable(); // Color cycling helpers int x = 0; int y = 85; int z = 170; // "60 fps" DWORD timeout = (DWORD)( ( 1.0 / 60.0 ) * 1000.0 ); // Run main loop while ( WaitForSingleObject( stopEvent, timeout ) == WAIT_TIMEOUT ) { // Cycle some LED colors for fun if ( system->getLogitechLEDs()->isInitialized() ) { Nil::Color clr; clr.r = (float)costable[x] / 99.0f; clr.g = (float)costable[y] / 99.0f; clr.b = (float)costable[z] / 99.0f; system->getLogitechLEDs()->setLighting( clr ); if ( x++ > 256 ) { x = 0; } if ( y++ > 256 ) { y = 0; } if ( z++ > 256 ) { z = 0; } } // Update the system // This will trigger all the callbacks system->update(); } // Done, shut down SetConsoleCtrlHandler( NULL, FALSE ); CloseHandle( stopEvent ); delete system; #ifndef _DEBUG } catch ( Nil::Exception& e ) { wprintf_s( L"Exception: %s\r\n", e.getFullDescription() ); return EXIT_FAILURE; } catch ( std::exception& e ) { wprintf_s( L"Exception: %S\r\n", e.what() ); return EXIT_FAILURE; } catch ( ... ) { wprintf_s( L"Unknown exception\r\n" ); return EXIT_FAILURE; } #endif return EXIT_SUCCESS; }<commit_msg>Fix test application for utf8string exceptions<commit_after>#include "nil.h" #include "nilUtil.h" #include <math.h> HANDLE stopEvent = NULL; // Cosine wave table for color cycling; not really needed for anything BYTE costable[256]={ 0,0,0,0,0,0,0,0,0,1,1,1,2,2,2,3, 3,4,4,5,5,6,7,7,8,9,9,10,11,12,13,13, 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, 31,32,33,34,35,36,38,39,40,41,42,44,45,46,47,49, 50,51,52,53,55,56,57,58,60,61,62,63,64,66,67,68, 69,70,71,72,73,74,76,77,78,79,80,81,82,82,83,84, 85,86,87,88,88,89,90,91,91,92,93,93,94,94,95,95, 96,96,97,97,98,98,98,98,99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,98,98,98,98,97,97,96,96, 95,95,94,94,93,93,92,91,91,90,89,88,88,87,86,85, 84,83,82,82,81,80,79,78,77,76,75,73,72,71,70,69, 68,67,66,64,63,62,61,60,58,57,56,55,53,52,51,50, 49,47,46,45,44,42,41,40,39,38,36,35,34,33,32,31, 29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14, 13,13,12,11,10,9,9,8,7,7,6,5,5,4,4,3, 3,2,2,2,1,1,1,0,0,0,0,0,0,0,0,0 }; // Shared mouse listener class DummyMouseListener: public Nil::MouseListener { public: virtual void onMouseMoved( Nil::Mouse* mouse, const Nil::MouseState& state ) { // } virtual void onMouseButtonPressed( Nil::Mouse* mouse, const Nil::MouseState& state, size_t button ) { printf_s( "Mouse button pressed: %d (%s)\n", button, mouse->getDevice()->getName().c_str() ); } virtual void onMouseButtonReleased( Nil::Mouse* mouse, const Nil::MouseState& state, size_t button ) { printf_s( "Mouse button released: %d (%s)\n", button, mouse->getDevice()->getName().c_str() ); } virtual void onMouseWheelMoved( Nil::Mouse* mouse, const Nil::MouseState& state ) { printf_s( "Mouse wheel moved: %d (%s)\n", state.mWheel.relative, mouse->getDevice()->getName().c_str() ); } }; DummyMouseListener gDummyMouseListener; // Shared keyboard listener class DummyKeyboardListener: public Nil::KeyboardListener { public: virtual void onKeyPressed( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key pressed: 0x%X (%s)\n", keycode, keyboard->getDevice()->getName().c_str() ); } virtual void onKeyRepeat( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key repeat: 0x%X (%s)\n", keycode, keyboard->getDevice()->getName().c_str() ); } virtual void onKeyReleased( Nil::Keyboard* keyboard, const Nil::VirtualKeyCode keycode ) { printf_s( "Key released: 0x%X (%s)\n", keycode, keyboard->getDevice()->getName().c_str() ); } }; DummyKeyboardListener gDummyKeyboardListener; // Shared controller listener; // A controller is any input device that is not a mouse nor a keyboard class DummyControllerListener: public Nil::ControllerListener { public: virtual void onControllerButtonPressed( Nil::Controller* controller, const Nil::ControllerState& state, size_t button ) { printf_s( "Controller button %d pressed (%s)\n", button, controller->getDevice()->getName().c_str() ); } virtual void onControllerButtonReleased( Nil::Controller* controller, const Nil::ControllerState& state, size_t button ) { printf_s( "Controller button %d released (%s)\n", button, controller->getDevice()->getName().c_str() ); } virtual void onControllerAxisMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t axis ) { printf_s( "Controller axis %d moved: %f (%s)\n", axis, state.mAxes[axis].absolute, controller->getDevice()->getName().c_str() ); } virtual void onControllerSliderMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t slider ) { printf_s( "Controller slider %d moved (%s)\n", slider, controller->getDevice()->getName().c_str() ); } virtual void onControllerPOVMoved( Nil::Controller* controller, const Nil::ControllerState& state, size_t pov ) { printf_s( "Controller POV %d moved: 0x%08X (%s)\n", pov, state.mPOVs[pov].direction, controller->getDevice()->getName().c_str() ); } }; DummyControllerListener gDummyControllerListener; // This is a listener for Logitech's proprietary G-keys on // support keyboard & mice class DummyGKeyListener: public Nil::Logitech::GKeyListener { public: virtual void onGKeyPressed( Nil::Logitech::GKey key ) { printf_s( "G-Key pressed: %d\n", key ); } virtual void onGKeyReleased( Nil::Logitech::GKey key ) { printf_s( "G-Key released: %d\n", key ); } }; DummyGKeyListener gDummyGKeyListener; // This is the main system listener, which must always exist class MyListener: public Nil::SystemListener { public: virtual void onDeviceConnected( Nil::Device* device ) { printf_s( "Connected: %s\r\n", device->getName().c_str() ); // Enable any device instantly when it is connected device->enable(); } virtual void onDeviceDisconnected( Nil::Device* device ) { printf_s( "Disconnected: %s\n", device->getName().c_str() ); } virtual void onMouseEnabled( Nil::Device* device, Nil::Mouse* instance ) { printf_s( "Mouse enabled: %s\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\n", device->getStaticID() ); // Add our listener for every mouse that is enabled instance->addListener( &gDummyMouseListener ); } virtual void onKeyboardEnabled( Nil::Device* device, Nil::Keyboard* instance ) { printf_s( "Keyboard enabled: %s\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\n", device->getStaticID() ); // Add our listener for every keyboard that is enabled instance->addListener( &gDummyKeyboardListener ); } virtual void onControllerEnabled( Nil::Device* device, Nil::Controller* instance ) { printf_s( "Controller enabled: %s\r\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\r\n", device->getStaticID() ); // Add our listener for every controller that is enabled instance->addListener( &gDummyControllerListener ); } virtual void onMouseDisabled( Nil::Device* device, Nil::Mouse* instance ) { printf_s( "Mouse disabled: %s\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } virtual void onKeyboardDisabled( Nil::Device* device, Nil::Keyboard* instance ) { printf_s( "Keyboard disabled: %s\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } virtual void onControllerDisabled( Nil::Device* device, Nil::Controller* instance ) { printf_s( "Controller disabled: %s\n", device->getName().c_str() ); printf_s( "Static ID: 0x%08X\n", device->getStaticID() ); // Removing listeners at this point is unnecessary, // as the device instance is destroyed anyway } }; MyListener gMyListener; BOOL WINAPI consoleHandler( DWORD ctrl ) { if ( ctrl == CTRL_C_EVENT || ctrl == CTRL_CLOSE_EVENT ) { SetEvent( stopEvent ); return TRUE; } return FALSE; } int wmain( int argc, wchar_t* argv[], wchar_t* envp[] ) { #ifndef _DEBUG try { #endif // Create quit event & set handler stopEvent = CreateEventW( 0, FALSE, FALSE, 0 ); SetConsoleCtrlHandler( consoleHandler, TRUE ); // Init system Nil::System* system = new Nil::System( GetModuleHandleW( nullptr ), GetConsoleWindow(), // Using background cooperation mode, because the default console window // is actually not owned by our process (it is owned by cmd.exe) and thus // we would not receive any mouse & keyboard events in foreground mode. // For applications that own their own window foreground mode works fine. Nil::Cooperation_Background, &gMyListener ); // Init Logitech G-keys subsystem, if available Nil::ExternalModule::InitReturn ret = system->getLogitechGKeys()->initialize(); if ( ret == Nil::ExternalModule::Initialization_OK ) { printf_s( "G-keys initialized\n" ); system->getLogitechGKeys()->addListener( &gDummyGKeyListener ); } else printf_s( "G-keys initialization failed with 0x%X\n", ret ); // Init Logitech LED subsytem, if available ret = system->getLogitechLEDs()->initialize(); if ( ret == Nil::ExternalModule::Initialization_OK ) printf_s( "LEDs initialized\r\n" ); else printf_s( "LEDs initialization failed with 0x%X\n", ret ); // Enable all initially connected devices for ( auto device : system->getDevices() ) device->enable(); // Color cycling helpers int x = 0; int y = 85; int z = 170; // "60 fps" DWORD timeout = (DWORD)( ( 1.0 / 60.0 ) * 1000.0 ); // Run main loop while ( WaitForSingleObject( stopEvent, timeout ) == WAIT_TIMEOUT ) { // Cycle some LED colors for fun if ( system->getLogitechLEDs()->isInitialized() ) { Nil::Color clr; clr.r = (float)costable[x] / 99.0f; clr.g = (float)costable[y] / 99.0f; clr.b = (float)costable[z] / 99.0f; system->getLogitechLEDs()->setLighting( clr ); if ( x++ > 256 ) { x = 0; } if ( y++ > 256 ) { y = 0; } if ( z++ > 256 ) { z = 0; } } // Update the system // This will trigger all the callbacks system->update(); } // Done, shut down SetConsoleCtrlHandler( NULL, FALSE ); CloseHandle( stopEvent ); delete system; #ifndef _DEBUG } catch ( Nil::Exception& e ) { printf_s( "Exception: %s\n", e.getFullDescription().c_str() ); return EXIT_FAILURE; } catch ( std::exception& e ) { printf_s( "Exception: %s\n", e.what() ); return EXIT_FAILURE; } catch ( ... ) { printf_s( "Unknown exception\n" ); return EXIT_FAILURE; } #endif return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_DETAIL_APPLY_ARGS_HPP #define CAF_DETAIL_APPLY_ARGS_HPP #include "caf/detail/int_list.hpp" #include "caf/detail/type_list.hpp" namespace caf { namespace detail { // this utterly useless function works around a bug in Clang that causes // the compiler to reject the trailing return type of apply_args because // "get" is not defined (it's found during ADL) template<long Pos, class... Ts> typename tl_at<type_list<Ts...>, Pos>::type get(const type_list<Ts...>&); template <class F, long... Is, class Tuple> inline auto apply_args(F& f, detail::int_list<Is...>, Tuple&& tup) -> decltype(f(get<Is>(tup)...)) { return f(get<Is>(tup)...); } template <class F, class Tuple, class... Ts> inline auto apply_args_prefixed(F& f, detail::int_list<>, Tuple&, Ts&&... args) -> decltype(f(std::forward<Ts>(args)...)) { return f(std::forward<Ts>(args)...); } template <class F, long... Is, class Tuple, class... Ts> inline auto apply_args_prefixed(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... args) -> decltype(f(std::forward<Ts>(args)..., get<Is>(tup)...)) { return f(std::forward<Ts>(args)..., get<Is>(tup)...); } template <class F, long... Is, class Tuple, class... Ts> inline auto apply_args_suffxied(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... args) -> decltype(f(get<Is>(tup)..., std::forward<Ts>(args)...)) { return f(get<Is>(tup)..., std::forward<Ts>(args)...); } } // namespace detail } // namespace caf #endif // CAF_DETAIL_APPLY_ARGS_HPP <commit_msg>Add missing include<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_DETAIL_APPLY_ARGS_HPP #define CAF_DETAIL_APPLY_ARGS_HPP #include <utility> #include "caf/detail/int_list.hpp" #include "caf/detail/type_list.hpp" namespace caf { namespace detail { // this utterly useless function works around a bug in Clang that causes // the compiler to reject the trailing return type of apply_args because // "get" is not defined (it's found during ADL) template<long Pos, class... Ts> typename tl_at<type_list<Ts...>, Pos>::type get(const type_list<Ts...>&); template <class F, long... Is, class Tuple> inline auto apply_args(F& f, detail::int_list<Is...>, Tuple&& tup) -> decltype(f(get<Is>(tup)...)) { return f(get<Is>(tup)...); } template <class F, class Tuple, class... Ts> inline auto apply_args_prefixed(F& f, detail::int_list<>, Tuple&, Ts&&... args) -> decltype(f(std::forward<Ts>(args)...)) { return f(std::forward<Ts>(args)...); } template <class F, long... Is, class Tuple, class... Ts> inline auto apply_args_prefixed(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... args) -> decltype(f(std::forward<Ts>(args)..., get<Is>(tup)...)) { return f(std::forward<Ts>(args)..., get<Is>(tup)...); } template <class F, long... Is, class Tuple, class... Ts> inline auto apply_args_suffxied(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... args) -> decltype(f(get<Is>(tup)..., std::forward<Ts>(args)...)) { return f(get<Is>(tup)..., std::forward<Ts>(args)...); } } // namespace detail } // namespace caf #endif // CAF_DETAIL_APPLY_ARGS_HPP <|endoftext|>
<commit_before>/* * helpers.c - Helper methods for the gateway * CSC 652 - 2014 */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <netinet/in.h> #include <sys/socket.h> #include "gateway.hpp" #include "helpers.hpp" /* * This method creates an appropriate CQL error packet to send on a specified socket. This does not close the socket before returning. */ void SendCQLError(int sock, uint32_t tid, uint32_t err, char* msg) { int p_len = sizeof(cql_packet_t) + 4 + 2 + strlen(msg); // Header + int + short + msg length cql_packet_t *p = (cql_packet_t *)malloc(p_len); memset(p, 0, p_len); p->version = CQL_V1_RESPONSE; p->opcode = CQL_OPCODE_ERROR; p->length = htonl(6 + strlen(msg)); err = htonl(err); memcpy((char *)p + sizeof(cql_packet_t), &err, 1); uint16_t str_len = htons(strlen(msg)); memcpy((char *)p + sizeof(cql_packet_t) + 4, &str_len, 1); memcpy((char *)p + sizeof(cql_packet_t) + 6, msg, strlen(msg)); #if DEBUG printf("%u: Sending error to client: '%s'.\n", (uint32_t)tid, msg); #endif if (send(sock, p, p_len, 0) < 0) { // Send the packet fprintf(stderr, "%u: Error sending error packet to client: %s\n", tid, strerror(errno)); exit(1); } free(p); } /* * Coverts a CQL string map into a linked list of key/value strings. */ cql_string_map_t * ReadStringMap(char *buf) { if (buf == NULL) { return NULL; } uint16_t num_pairs; memcpy(&num_pairs, buf, 2); num_pairs = ntohs(num_pairs); if (num_pairs == 0) { return NULL; // An empty string map can sometimes be sent, like in the cpp driver when sending no auth data } int offset = 2; // Keep track as we move through the buffer uint16_t str_len = 0; // Length of each string we process cql_string_map_t *sm = (cql_string_map_t *)malloc(sizeof(cql_string_map_t)); cql_string_map_t *head = sm; while (num_pairs > 0) { // Key memcpy(&str_len, buf + offset, 2); offset += 2; str_len = ntohs(str_len); sm->key = (char *)malloc(str_len + 1); memset(sm->key, 0, str_len + 1); memcpy(sm->key, buf + offset, str_len); offset += str_len; // Value memcpy(&str_len, buf + offset, 2); offset += 2; str_len = ntohs(str_len); sm->value = (char *)malloc(str_len + 1); memset(sm->value, 0, str_len + 1); memcpy(sm->value, buf + offset, str_len); offset += str_len; num_pairs--; if (num_pairs > 0) { sm->next = (cql_string_map_t *)malloc(sizeof(cql_string_map_t)); sm = sm->next; } else { sm->next = NULL; } } return head; } /* * Coverts a linked list of key/value strings into the CQL string map format. Returns size of new buffer. */ char* WriteStringMap(cql_string_map_t *sm, uint32_t *new_len) { if (sm == NULL) { *new_len = 0; return NULL; } cql_string_map_t *head = sm; uint16_t num_pairs = 0; uint32_t buf_size = 2; int offset = 2; uint16_t str_len = 0; while (sm != NULL) { num_pairs++; buf_size += strlen(sm->key) + 2; // Length of string plus two byte short in front of it buf_size += strlen(sm->value) + 2; sm = sm->next; } char *buf = (char *)malloc(buf_size); num_pairs = htons(num_pairs); memcpy(buf, &num_pairs, 2); sm = head; while (sm != NULL) { // Key str_len = strlen(sm->key); str_len = htons(str_len); memcpy(buf + offset, &str_len, 2); offset += 2; memcpy(buf + offset, sm->key, strlen(sm->key)); offset += strlen(sm->key); // Value str_len = strlen(sm->value); str_len = htons(str_len); memcpy(buf + offset, &str_len, 2); offset += 2; memcpy(buf + offset, sm->value, strlen(sm->value)); offset += strlen(sm->value); sm = sm->next; } *new_len = buf_size; return buf; } void FreeStringMap(cql_string_map_t *sm) { while (sm != NULL) { cql_string_map_t *next = sm->next; free(sm->key); free(sm->value); free(sm); sm = next; } } void gracefulExit(int sig) { fprintf(stderr, "\nCaught sig %d -- exiting.\n", sig); exit(0); } bool addNode(node *head, node *toAdd){ node *tmp; if(head == NULL){ head = toAdd; return true; }else{ tmp = head; while(tmp->next != NULL){ tmp = tmp->next; } tmp->next = toAdd; return true; } return false; } bool removeNode(node *head, node *toRemove){ node *tmp; node *tmp2; if(head->id == toRemove->id){ if(head->next == NULL){ free(head); return true; }else{ tmp = head->next; free(head); head = tmp; return true; } }else{ tmp = head; while(tmp->next != NULL){ if(tmp->next->id != toRemove->id){ tmp2 = tmp->next->next; free(tmp->next); tmp->next = tmp2; // Works even if tmp->next is the end, it will be null return true; } tmp = tmp->next; } // if we got here, we never found it return false; } return false; } bool findNode(node *head, int8_t stream_id){ node *tmp = head; while(tmp != NULL){ if(tmp->id == stream_id){ removeNode(head, tmp); return true; } } return false; } <commit_msg>Fixing a bug that caused infinite loop --kkd<commit_after>/* * helpers.c - Helper methods for the gateway * CSC 652 - 2014 */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <netinet/in.h> #include <sys/socket.h> #include "gateway.hpp" #include "helpers.hpp" /* * This method creates an appropriate CQL error packet to send on a specified socket. This does not close the socket before returning. */ void SendCQLError(int sock, uint32_t tid, uint32_t err, char* msg) { int p_len = sizeof(cql_packet_t) + 4 + 2 + strlen(msg); // Header + int + short + msg length cql_packet_t *p = (cql_packet_t *)malloc(p_len); memset(p, 0, p_len); p->version = CQL_V1_RESPONSE; p->opcode = CQL_OPCODE_ERROR; p->length = htonl(6 + strlen(msg)); err = htonl(err); memcpy((char *)p + sizeof(cql_packet_t), &err, 1); uint16_t str_len = htons(strlen(msg)); memcpy((char *)p + sizeof(cql_packet_t) + 4, &str_len, 1); memcpy((char *)p + sizeof(cql_packet_t) + 6, msg, strlen(msg)); #if DEBUG printf("%u: Sending error to client: '%s'.\n", (uint32_t)tid, msg); #endif if (send(sock, p, p_len, 0) < 0) { // Send the packet fprintf(stderr, "%u: Error sending error packet to client: %s\n", tid, strerror(errno)); exit(1); } free(p); } /* * Coverts a CQL string map into a linked list of key/value strings. */ cql_string_map_t * ReadStringMap(char *buf) { if (buf == NULL) { return NULL; } uint16_t num_pairs; memcpy(&num_pairs, buf, 2); num_pairs = ntohs(num_pairs); if (num_pairs == 0) { return NULL; // An empty string map can sometimes be sent, like in the cpp driver when sending no auth data } int offset = 2; // Keep track as we move through the buffer uint16_t str_len = 0; // Length of each string we process cql_string_map_t *sm = (cql_string_map_t *)malloc(sizeof(cql_string_map_t)); cql_string_map_t *head = sm; while (num_pairs > 0) { // Key memcpy(&str_len, buf + offset, 2); offset += 2; str_len = ntohs(str_len); sm->key = (char *)malloc(str_len + 1); memset(sm->key, 0, str_len + 1); memcpy(sm->key, buf + offset, str_len); offset += str_len; // Value memcpy(&str_len, buf + offset, 2); offset += 2; str_len = ntohs(str_len); sm->value = (char *)malloc(str_len + 1); memset(sm->value, 0, str_len + 1); memcpy(sm->value, buf + offset, str_len); offset += str_len; num_pairs--; if (num_pairs > 0) { sm->next = (cql_string_map_t *)malloc(sizeof(cql_string_map_t)); sm = sm->next; } else { sm->next = NULL; } } return head; } /* * Coverts a linked list of key/value strings into the CQL string map format. Returns size of new buffer. */ char* WriteStringMap(cql_string_map_t *sm, uint32_t *new_len) { if (sm == NULL) { *new_len = 0; return NULL; } cql_string_map_t *head = sm; uint16_t num_pairs = 0; uint32_t buf_size = 2; int offset = 2; uint16_t str_len = 0; while (sm != NULL) { num_pairs++; buf_size += strlen(sm->key) + 2; // Length of string plus two byte short in front of it buf_size += strlen(sm->value) + 2; sm = sm->next; } char *buf = (char *)malloc(buf_size); num_pairs = htons(num_pairs); memcpy(buf, &num_pairs, 2); sm = head; while (sm != NULL) { // Key str_len = strlen(sm->key); str_len = htons(str_len); memcpy(buf + offset, &str_len, 2); offset += 2; memcpy(buf + offset, sm->key, strlen(sm->key)); offset += strlen(sm->key); // Value str_len = strlen(sm->value); str_len = htons(str_len); memcpy(buf + offset, &str_len, 2); offset += 2; memcpy(buf + offset, sm->value, strlen(sm->value)); offset += strlen(sm->value); sm = sm->next; } *new_len = buf_size; return buf; } void FreeStringMap(cql_string_map_t *sm) { while (sm != NULL) { cql_string_map_t *next = sm->next; free(sm->key); free(sm->value); free(sm); sm = next; } } void gracefulExit(int sig) { fprintf(stderr, "\nCaught sig %d -- exiting.\n", sig); exit(0); } bool addNode(node *head, node *toAdd){ node *tmp; if(head == NULL){ head = toAdd; return true; }else{ tmp = head; while(tmp->next != NULL){ tmp = tmp->next; } tmp->next = toAdd; return true; } return false; } bool removeNode(node *head, node *toRemove){ node *tmp; node *tmp2; if(head->id == toRemove->id){ if(head->next == NULL){ free(head); return true; }else{ tmp = head->next; free(head); head = tmp; return true; } }else{ tmp = head; while(tmp->next != NULL){ if(tmp->next->id != toRemove->id){ tmp2 = tmp->next->next; free(tmp->next); tmp->next = tmp2; // Works even if tmp->next is the end, it will be null return true; } tmp = tmp->next; } // if we got here, we never found it return false; } return false; } bool findNode(node *head, int8_t stream_id){ node *tmp = head; while(tmp != NULL){ if(tmp->id == stream_id){ removeNode(head, tmp); return true; } tmp = tmp->next; } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconcustomshape.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2007-05-10 16:56:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------------ #ifndef SC_FUCONCUSTOMSHAPE_HXX #include <fuconcustomshape.hxx> #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif #ifndef _GALLERY_HXX_ #include <svx/gallery.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _FM_FMMODEL_HXX #include <svx/fmmodel.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SVDPAGE_HXX #include <svx/svdpage.hxx> #endif #ifndef _SVDOASHP_HXX #include <svx/svdoashp.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #ifndef _SDTAGITM_HXX #include <svx/sdtagitm.hxx> #endif #include <svx/svdview.hxx> #include "fuconuno.hxx" #include "tabvwsh.hxx" #include "sc.hrc" #ifndef _SVX_ADJITEM_HXX #include <svx/adjitem.hxx> #endif #include <math.h> //------------------------------------------------------------------------ FuConstCustomShape::FuConstCustomShape( ScTabViewShell* pViewSh, Window* pWin, SdrView* pViewP, SdrModel* pDoc, SfxRequest& rReq ) : FuConstruct( pViewSh, pWin, pViewP, pDoc, rReq ) { const SfxItemSet* pArgs = rReq.GetArgs(); if ( pArgs ) { const SfxStringItem& rItm = (const SfxStringItem&)pArgs->Get( rReq.GetSlot() ); aCustomShape = rItm.GetValue(); } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstCustomShape::~FuConstCustomShape() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt); if ( rMEvt.IsLeft() && !pView->IsAction() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pWindow->CaptureMouse(); pView->BegCreateObj(aPnt); SdrObject* pObj = pView->GetCreateObj(); if ( pObj ) { SetAttributes( pObj ); sal_Bool bForceFillStyle = sal_True; sal_Bool bForceNoFillStyle = sal_False; if ( ((SdrObjCustomShape*)pObj)->UseNoFillStyle() ) { bForceFillStyle = sal_False; bForceNoFillStyle = sal_True; } if ( bForceNoFillStyle ) pObj->SetMergedItem( XFillStyleItem( XFILL_NONE ) ); } bReturn = TRUE; } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseMove(const MouseEvent& rMEvt) { return FuConstruct::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; if ( pView->IsCreateObj() && rMEvt.IsLeft() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj(SDRCREATE_FORCEEND); bReturn = TRUE; } return (FuConstruct::MouseButtonUp(rMEvt) || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstCustomShape::Activate() { pView->SetCurrentObj( OBJ_CUSTOMSHAPE, SdrInventor ); aNewPointer = Pointer( POINTER_DRAW_RECT ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); SdrLayer* pLayer = pView->GetModel()->GetLayerAdmin().GetLayerPerID(SC_LAYER_CONTROLS); if (pLayer) pView->SetActiveLayer( pLayer->GetName() ); FuConstruct::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstCustomShape::Deactivate() { FuConstruct::Deactivate(); SdrLayer* pLayer = pView->GetModel()->GetLayerAdmin().GetLayerPerID(SC_LAYER_FRONT); if (pLayer) pView->SetActiveLayer( pLayer->GetName() ); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstCustomShape::CreateDefaultObject(const sal_uInt16 /* nID */, const Rectangle& rRectangle) { SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if( pObj ) { Rectangle aRectangle( rRectangle ); SetAttributes( pObj ); if ( SdrObjCustomShape::doConstructOrthogonal( aCustomShape ) ) ImpForceQuadratic( aRectangle ); pObj->SetLogicRect( aRectangle ); } return pObj; } /************************************************************************* |* |* applying attributes |* \************************************************************************/ void FuConstCustomShape::SetAttributes( SdrObject* pObj ) { sal_Bool bAttributesAppliedFromGallery = sal_False; if ( GalleryExplorer::GetSdrObjCount( GALLERY_THEME_POWERPOINT ) ) { std::vector< rtl::OUString > aObjList; if ( GalleryExplorer::FillObjListTitle( GALLERY_THEME_POWERPOINT, aObjList ) ) { sal_uInt16 i; for ( i = 0; i < aObjList.size(); i++ ) { if ( aObjList[ i ].equalsIgnoreAsciiCase( aCustomShape ) ) { FmFormModel aFormModel; SfxItemPool& rPool = aFormModel.GetItemPool(); rPool.FreezeIdRanges(); if ( GalleryExplorer::GetSdrObj( GALLERY_THEME_POWERPOINT, i, &aFormModel ) ) { const SdrObject* pSourceObj = aFormModel.GetPage( 0 )->GetObj( 0 ); if( pSourceObj ) { const SfxItemSet& rSource = pSourceObj->GetMergedItemSet(); SfxItemSet aDest( pObj->GetModel()->GetItemPool(), // ranges from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // Graphic Attributes SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // 3d Properties SDRATTR_3D_FIRST, SDRATTR_3D_LAST, // CustomShape properties SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0); aDest.Set( rSource ); pObj->SetMergedItemSet( aDest ); sal_Int32 nAngle = pSourceObj->GetRotateAngle(); if ( nAngle ) { double a = nAngle * F_PI18000; pObj->NbcRotate( pObj->GetSnapRect().Center(), nAngle, sin( a ), cos( a ) ); } bAttributesAppliedFromGallery = sal_True; } } break; } } } } if ( !bAttributesAppliedFromGallery ) { pObj->SetMergedItem( SvxAdjustItem( SVX_ADJUST_CENTER, 0 ) ); pObj->SetMergedItem( SdrTextVertAdjustItem( SDRTEXTVERTADJUST_CENTER ) ); pObj->SetMergedItem( SdrTextHorzAdjustItem( SDRTEXTHORZADJUST_BLOCK ) ); pObj->SetMergedItem( SdrTextAutoGrowHeightItem( sal_False ) ); ((SdrObjCustomShape*)pObj)->MergeDefaultAttributes( &aCustomShape ); } } // #i33136# bool FuConstCustomShape::doConstructOrthogonal() const { return SdrObjCustomShape::doConstructOrthogonal(aCustomShape); } // eof <commit_msg>INTEGRATION: CWS changefileheader (1.12.300); FILE MERGED 2008/04/01 15:30:45 thb 1.12.300.3: #i85898# Stripping all external header guards 2008/04/01 12:36:41 thb 1.12.300.2: #i85898# Stripping all external header guards 2008/03/31 17:15:31 rt 1.12.300.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconcustomshape.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------------ #include <fuconcustomshape.hxx> #include <svx/svxenum.hxx> #include <svx/gallery.hxx> #include <sfx2/request.hxx> #ifndef _FM_FMMODEL_HXX #include <svx/fmmodel.hxx> #endif #include <svtools/itempool.hxx> #include <svx/svdpage.hxx> #include <svx/svdoashp.hxx> #include <svx/eeitem.hxx> #include <svx/sdtagitm.hxx> #include <svx/svdview.hxx> #include "fuconuno.hxx" #include "tabvwsh.hxx" #include "sc.hrc" #include <svx/adjitem.hxx> #include <math.h> //------------------------------------------------------------------------ FuConstCustomShape::FuConstCustomShape( ScTabViewShell* pViewSh, Window* pWin, SdrView* pViewP, SdrModel* pDoc, SfxRequest& rReq ) : FuConstruct( pViewSh, pWin, pViewP, pDoc, rReq ) { const SfxItemSet* pArgs = rReq.GetArgs(); if ( pArgs ) { const SfxStringItem& rItm = (const SfxStringItem&)pArgs->Get( rReq.GetSlot() ); aCustomShape = rItm.GetValue(); } } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuConstCustomShape::~FuConstCustomShape() { } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt); if ( rMEvt.IsLeft() && !pView->IsAction() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pWindow->CaptureMouse(); pView->BegCreateObj(aPnt); SdrObject* pObj = pView->GetCreateObj(); if ( pObj ) { SetAttributes( pObj ); sal_Bool bForceFillStyle = sal_True; sal_Bool bForceNoFillStyle = sal_False; if ( ((SdrObjCustomShape*)pObj)->UseNoFillStyle() ) { bForceFillStyle = sal_False; bForceNoFillStyle = sal_True; } if ( bForceNoFillStyle ) pObj->SetMergedItem( XFillStyleItem( XFILL_NONE ) ); } bReturn = TRUE; } return bReturn; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseMove(const MouseEvent& rMEvt) { return FuConstruct::MouseMove(rMEvt); } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); BOOL bReturn = FALSE; if ( pView->IsCreateObj() && rMEvt.IsLeft() ) { Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); pView->EndCreateObj(SDRCREATE_FORCEEND); bReturn = TRUE; } return (FuConstruct::MouseButtonUp(rMEvt) || bReturn); } /************************************************************************* |* |* Tastaturereignisse bearbeiten |* |* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls |* FALSE. |* \************************************************************************/ BOOL __EXPORT FuConstCustomShape::KeyInput(const KeyEvent& rKEvt) { BOOL bReturn = FuConstruct::KeyInput(rKEvt); return(bReturn); } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuConstCustomShape::Activate() { pView->SetCurrentObj( OBJ_CUSTOMSHAPE, SdrInventor ); aNewPointer = Pointer( POINTER_DRAW_RECT ); aOldPointer = pWindow->GetPointer(); pViewShell->SetActivePointer( aNewPointer ); SdrLayer* pLayer = pView->GetModel()->GetLayerAdmin().GetLayerPerID(SC_LAYER_CONTROLS); if (pLayer) pView->SetActiveLayer( pLayer->GetName() ); FuConstruct::Activate(); } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuConstCustomShape::Deactivate() { FuConstruct::Deactivate(); SdrLayer* pLayer = pView->GetModel()->GetLayerAdmin().GetLayerPerID(SC_LAYER_FRONT); if (pLayer) pView->SetActiveLayer( pLayer->GetName() ); pViewShell->SetActivePointer( aOldPointer ); } // #98185# Create default drawing objects via keyboard SdrObject* FuConstCustomShape::CreateDefaultObject(const sal_uInt16 /* nID */, const Rectangle& rRectangle) { SdrObject* pObj = SdrObjFactory::MakeNewObject( pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(), 0L, pDrDoc); if( pObj ) { Rectangle aRectangle( rRectangle ); SetAttributes( pObj ); if ( SdrObjCustomShape::doConstructOrthogonal( aCustomShape ) ) ImpForceQuadratic( aRectangle ); pObj->SetLogicRect( aRectangle ); } return pObj; } /************************************************************************* |* |* applying attributes |* \************************************************************************/ void FuConstCustomShape::SetAttributes( SdrObject* pObj ) { sal_Bool bAttributesAppliedFromGallery = sal_False; if ( GalleryExplorer::GetSdrObjCount( GALLERY_THEME_POWERPOINT ) ) { std::vector< rtl::OUString > aObjList; if ( GalleryExplorer::FillObjListTitle( GALLERY_THEME_POWERPOINT, aObjList ) ) { sal_uInt16 i; for ( i = 0; i < aObjList.size(); i++ ) { if ( aObjList[ i ].equalsIgnoreAsciiCase( aCustomShape ) ) { FmFormModel aFormModel; SfxItemPool& rPool = aFormModel.GetItemPool(); rPool.FreezeIdRanges(); if ( GalleryExplorer::GetSdrObj( GALLERY_THEME_POWERPOINT, i, &aFormModel ) ) { const SdrObject* pSourceObj = aFormModel.GetPage( 0 )->GetObj( 0 ); if( pSourceObj ) { const SfxItemSet& rSource = pSourceObj->GetMergedItemSet(); SfxItemSet aDest( pObj->GetModel()->GetItemPool(), // ranges from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // Graphic Attributes SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // 3d Properties SDRATTR_3D_FIRST, SDRATTR_3D_LAST, // CustomShape properties SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0); aDest.Set( rSource ); pObj->SetMergedItemSet( aDest ); sal_Int32 nAngle = pSourceObj->GetRotateAngle(); if ( nAngle ) { double a = nAngle * F_PI18000; pObj->NbcRotate( pObj->GetSnapRect().Center(), nAngle, sin( a ), cos( a ) ); } bAttributesAppliedFromGallery = sal_True; } } break; } } } } if ( !bAttributesAppliedFromGallery ) { pObj->SetMergedItem( SvxAdjustItem( SVX_ADJUST_CENTER, 0 ) ); pObj->SetMergedItem( SdrTextVertAdjustItem( SDRTEXTVERTADJUST_CENTER ) ); pObj->SetMergedItem( SdrTextHorzAdjustItem( SDRTEXTHORZADJUST_BLOCK ) ); pObj->SetMergedItem( SdrTextAutoGrowHeightItem( sal_False ) ); ((SdrObjCustomShape*)pObj)->MergeDefaultAttributes( &aCustomShape ); } } // #i33136# bool FuConstCustomShape::doConstructOrthogonal() const { return SdrObjCustomShape::doConstructOrthogonal(aCustomShape); } // eof <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: autofmt.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:30:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_AUTOFMT_HXX #define SC_AUTOFMT_HXX #ifndef _VIRDEV_HXX //autogen #include <vcl/virdev.hxx> #endif #ifndef SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef SV_MOREBTN_HXX #include <vcl/morebtn.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SVTOOLS_SCRIPTEDTEXT_HXX #include <svtools/scriptedtext.hxx> #endif //------------------------------------------------------------------------ class ScAutoFormat; class ScAutoFormatData; class SvxBoxItem; class SvxBorderLine; class AutoFmtPreview; // s.u. class SvNumberFormatter; class ScDocument; //------------------------------------------------------------------------ enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE }; //======================================================================== //CHINA001 class ScAutoFormatDlg : public ModalDialog //CHINA001 { //CHINA001 public: //CHINA001 ScAutoFormatDlg( Window* pParent, //CHINA001 ScAutoFormat* pAutoFormat, //CHINA001 const ScAutoFormatData* pSelFormatData, //CHINA001 ScDocument* pDoc ); //CHINA001 ~ScAutoFormatDlg(); //CHINA001 //CHINA001 USHORT GetIndex() const { return nIndex; } //CHINA001 String GetCurrFormatName(); //CHINA001 //CHINA001 private: //CHINA001 FixedLine aFlFormat; //CHINA001 ListBox aLbFormat; //CHINA001 AutoFmtPreview* pWndPreview; //CHINA001 OKButton aBtnOk; //CHINA001 CancelButton aBtnCancel; //CHINA001 HelpButton aBtnHelp; //CHINA001 PushButton aBtnAdd; //CHINA001 PushButton aBtnRemove; //CHINA001 MoreButton aBtnMore; //CHINA001 FixedLine aFlFormatting; //CHINA001 CheckBox aBtnNumFormat; //CHINA001 CheckBox aBtnBorder; //CHINA001 CheckBox aBtnFont; //CHINA001 CheckBox aBtnPattern; //CHINA001 CheckBox aBtnAlignment; //CHINA001 CheckBox aBtnAdjust; //CHINA001 PushButton aBtnRename; //CHINA001 String aStrTitle; //CHINA001 String aStrLabel; //CHINA001 String aStrClose; //CHINA001 String aStrDelTitle; //CHINA001 String aStrDelMsg; //CHINA001 String aStrRename; //CHINA001 //CHINA001 //------------------------ //CHINA001 ScAutoFormat* pFormat; //CHINA001 const ScAutoFormatData* pSelFmtData; //CHINA001 USHORT nIndex; //CHINA001 BOOL bCoreDataChanged; //CHINA001 BOOL bFmtInserted; //CHINA001 //CHINA001 void Init (); //CHINA001 void UpdateChecks (); //CHINA001 //------------------------ //CHINA001 DECL_LINK( CheckHdl, Button * ); //CHINA001 DECL_LINK( AddHdl, void * ); //CHINA001 DECL_LINK( RemoveHdl, void * ); //CHINA001 DECL_LINK( SelFmtHdl, void * ); //CHINA001 DECL_LINK( CloseHdl, PushButton * ); //CHINA001 DECL_LINK( DblClkHdl, void * ); //CHINA001 DECL_LINK( RenameHdl, void *); //CHINA001 //CHINA001 }; //CHINA001 //======================================================================== class AutoFmtPreview : public Window { public: AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc ); ~AutoFmtPreview(); void NotifyChange( ScAutoFormatData* pNewData ); protected: virtual void Paint( const Rectangle& rRect ); private: ScAutoFormatData* pCurData; VirtualDevice aVD; SvtScriptedTextHelper aScriptedText; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter; BOOL bFitWidth; static USHORT aFmtMap[25]; // Zuordnung: Zelle->Format Rectangle aCellArray[25]; // Position und Groesse der Zellen SvxBoxItem* aLinePtrArray[49]; // LinienAttribute Size aPrvSize; const USHORT nLabelColWidth; const USHORT nDataColWidth1; const USHORT nDataColWidth2; const USHORT nRowHeight; const String aStrJan; const String aStrFeb; const String aStrMar; const String aStrNorth; const String aStrMid; const String aStrSouth; const String aStrSum; SvNumberFormatter* pNumFmt; //------------------------------------------- void Init (); void DoPaint ( const Rectangle& rRect ); void CalcCellArray ( BOOL bFitWidth ); void CalcLineMap (); void PaintCells (); void DrawBackground ( USHORT nIndex ); void DrawFrame ( USHORT nIndex ); void DrawString ( USHORT nIndex ); void MakeFonts ( USHORT nIndex, Font& rFont, Font& rCJKFont, Font& rCTLFont ); String MakeNumberString( String cellString, BOOL bAddDec ); void DrawFrameLine ( const SvxBorderLine& rLineD, Point from, Point to, BOOL bHorizontal, const SvxBorderLine& rLineLT, const SvxBorderLine& rLineL, const SvxBorderLine& rLineLB, const SvxBorderLine& rLineRT, const SvxBorderLine& rLineR, const SvxBorderLine& rLineRB ); void CheckPriority ( USHORT nCurLine, AutoFmtLine eLine, SvxBorderLine& rLine ); void GetLines ( USHORT nIndex, AutoFmtLine eLine, SvxBorderLine& rLineD, SvxBorderLine& rLineLT, SvxBorderLine& rLineL, SvxBorderLine& rLineLB, SvxBorderLine& rLineRT, SvxBorderLine& rLineR, SvxBorderLine& rLineRB ); }; #endif // SC_AUTOFMT_HXX <commit_msg>INTEGRATION: CWS dr14 (1.3.326); FILE MERGED 2004/06/10 18:20:45 dr 1.3.326.6: RESYNC: (1.4-1.5); FILE MERGED 2004/05/28 12:20:10 dr 1.3.326.5: #100000# dialogdiet changes 2004/05/19 12:44:58 dr 1.3.326.4: RESYNC: (1.3-1.4); FILE MERGED 2004/04/14 15:58:49 dr 1.3.326.3: #i23675# diagonal borders step 7d: support for merged cells improved 2004/03/12 17:17:30 dr 1.3.326.2: #i23675# diagonal borders step 6: Calc AutoFormats use diagonal frame lines 2004/03/12 15:32:20 dr 1.3.326.1: #i23675# diagonal borders step 5: AutoFormat dialog uses new svx frame drawing functionality<commit_after>/************************************************************************* * * $RCSfile: autofmt.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-08-02 17:02:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_AUTOFMT_HXX #define SC_AUTOFMT_HXX #ifndef _VIRDEV_HXX //autogen #include <vcl/virdev.hxx> #endif #ifndef SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef SV_MOREBTN_HXX #include <vcl/morebtn.hxx> #endif #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SVTOOLS_SCRIPTEDTEXT_HXX #include <svtools/scriptedtext.hxx> #endif #ifndef SVX_FRAMELINKARRAY_HXX #include <svx/framelinkarray.hxx> #endif //------------------------------------------------------------------------ class ScAutoFormat; class ScAutoFormatData; class SvxBoxItem; class SvxLineItem; class AutoFmtPreview; // s.u. class SvNumberFormatter; class ScDocument; //------------------------------------------------------------------------ enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE }; //======================================================================== //CHINA001 class ScAutoFormatDlg : public ModalDialog //CHINA001 { //CHINA001 public: //CHINA001 ScAutoFormatDlg( Window* pParent, //CHINA001 ScAutoFormat* pAutoFormat, //CHINA001 const ScAutoFormatData* pSelFormatData, //CHINA001 ScDocument* pDoc ); //CHINA001 ~ScAutoFormatDlg(); //CHINA001 //CHINA001 USHORT GetIndex() const { return nIndex; } //CHINA001 String GetCurrFormatName(); //CHINA001 //CHINA001 private: //CHINA001 FixedLine aFlFormat; //CHINA001 ListBox aLbFormat; //CHINA001 AutoFmtPreview* pWndPreview; //CHINA001 OKButton aBtnOk; //CHINA001 CancelButton aBtnCancel; //CHINA001 HelpButton aBtnHelp; //CHINA001 PushButton aBtnAdd; //CHINA001 PushButton aBtnRemove; //CHINA001 MoreButton aBtnMore; //CHINA001 FixedLine aFlFormatting; //CHINA001 CheckBox aBtnNumFormat; //CHINA001 CheckBox aBtnBorder; //CHINA001 CheckBox aBtnFont; //CHINA001 CheckBox aBtnPattern; //CHINA001 CheckBox aBtnAlignment; //CHINA001 CheckBox aBtnAdjust; //CHINA001 PushButton aBtnRename; //CHINA001 String aStrTitle; //CHINA001 String aStrLabel; //CHINA001 String aStrClose; //CHINA001 String aStrDelTitle; //CHINA001 String aStrDelMsg; //CHINA001 String aStrRename; //CHINA001 //CHINA001 //------------------------ //CHINA001 ScAutoFormat* pFormat; //CHINA001 const ScAutoFormatData* pSelFmtData; //CHINA001 USHORT nIndex; //CHINA001 BOOL bCoreDataChanged; //CHINA001 BOOL bFmtInserted; //CHINA001 //CHINA001 void Init (); //CHINA001 void UpdateChecks (); //CHINA001 //------------------------ //CHINA001 DECL_LINK( CheckHdl, Button * ); //CHINA001 DECL_LINK( AddHdl, void * ); //CHINA001 DECL_LINK( RemoveHdl, void * ); //CHINA001 DECL_LINK( SelFmtHdl, void * ); //CHINA001 DECL_LINK( CloseHdl, PushButton * ); //CHINA001 DECL_LINK( DblClkHdl, void * ); //CHINA001 DECL_LINK( RenameHdl, void *); //CHINA001 //CHINA001 }; //CHINA001 //======================================================================== class AutoFmtPreview : public Window { public: AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc ); ~AutoFmtPreview(); void NotifyChange( ScAutoFormatData* pNewData ); protected: virtual void Paint( const Rectangle& rRect ); private: ScAutoFormatData* pCurData; VirtualDevice aVD; SvtScriptedTextHelper aScriptedText; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter; BOOL bFitWidth; svx::frame::Array maArray; /// Implementation to draw the frame borders. Size aPrvSize; long mnLabelColWidth; long mnDataColWidth1; long mnDataColWidth2; long mnRowHeight; const String aStrJan; const String aStrFeb; const String aStrMar; const String aStrNorth; const String aStrMid; const String aStrSouth; const String aStrSum; SvNumberFormatter* pNumFmt; //------------------------------------------- void Init (); void DoPaint ( const Rectangle& rRect ); void CalcCellArray ( BOOL bFitWidth ); void CalcLineMap (); void PaintCells (); /* Usage of type size_t instead of SCCOL/SCROW is correct here - used in conjunction with class svx::frame::Array (svx/framelinkarray.hxx), which expects size_t coordinates. */ USHORT GetFormatIndex( size_t nCol, size_t nRow ) const; const SvxBoxItem& GetBoxItem( size_t nCol, size_t nRow ) const; const SvxLineItem& GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const; void DrawString( size_t nCol, size_t nRow ); void DrawStrings(); void DrawBackground(); void MakeFonts ( USHORT nIndex, Font& rFont, Font& rCJKFont, Font& rCTLFont ); String MakeNumberString( String cellString, BOOL bAddDec ); }; #endif // SC_AUTOFMT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: docfunc.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:31:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DOCFUNC_HXX #define SC_DOCFUNC_HXX #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif class EditEngine; class SfxUndoAction; class ScAddress; class ScDocShell; class ScMarkData; class ScPatternAttr; class ScRange; class ScRangeName; class ScBaseCell; struct ScTabOpParam; // --------------------------------------------------------------------------- class ScDocFunc { private: ScDocShell& rDocShell; BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE ); void CreateOneName( ScRangeName& rList, SCCOL nPosX, SCROW nPosY, SCTAB nTab, SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2, BOOL& rCancel, BOOL bApi ); void NotifyInputHandler( const ScAddress& rPos ); public: ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {} ~ScDocFunc() {} DECL_LINK( NotifyDrawUndo, SfxUndoAction* ); BOOL DetectiveAddPred(const ScAddress& rPos); BOOL DetectiveDelPred(const ScAddress& rPos); BOOL DetectiveAddSucc(const ScAddress& rPos); BOOL DetectiveDelSucc(const ScAddress& rPos); BOOL DetectiveAddError(const ScAddress& rPos); BOOL DetectiveMarkInvalid(SCTAB nTab); BOOL DetectiveDelAll(SCTAB nTab); BOOL DetectiveRefresh(BOOL bAutomatic = FALSE); BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags, BOOL bRecord, BOOL bApi ); BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType, BOOL bRecord, BOOL bApi ); BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi ); BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi ); BOOL PutData( const ScAddress& rPos, EditEngine& rEngine, BOOL bInterpret, BOOL bApi ); BOOL SetCellText( const ScAddress& rPos, const String& rText, BOOL bInterpret, BOOL bEnglish, BOOL bApi ); // creates a new cell for use with PutCell ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText ); BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi ); BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern, BOOL bRecord, BOOL bApi ); BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName, BOOL bRecord, BOOL bApi ); BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi, BOOL bPartOfPaste = FALSE ); BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi ); BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos, BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi ); BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi ); BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi ); BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi ); BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi ); BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi ); BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges, SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips, BOOL bRecord, BOOL bApi ); BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos, BOOL bRecord, BOOL bSetModified, BOOL bApi ); BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos, BOOL bRecord, BOOL bSetModified, BOOL bApi ); BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi ); BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi ); BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi ); BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi ); BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark, USHORT nFormatNo, BOOL bRecord, BOOL bApi ); BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark, const String& rString, BOOL bApi, BOOL bEnglish ); BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark, const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi ); BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, BOOL bRecord, BOOL bApi ); BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd, double fStart, double fStep, double fMax, BOOL bRecord, BOOL bApi ); // FillAuto: rRange wird von Source-Range auf Dest-Range angepasst BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi ); BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi ); BOOL MergeCells( const ScRange& rRange, BOOL bContents, BOOL bRecord, BOOL bApi ); BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi ); BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi ); BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi ); BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi ); BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi ); BOOL InsertAreaLink( const String& rFile, const String& rFilter, const String& rOptions, const String& rSource, const ScRange& rDestRange, ULONG nRefresh, BOOL bFitBlock, BOOL bApi ); }; #endif <commit_msg>INTEGRATION: CWS dr12 (1.7.170); FILE MERGED 2004/07/27 02:04:17 sab 1.7.170.3: RESYNC: (1.8-1.9); FILE MERGED 2004/02/25 10:18:18 dr 1.7.170.2: RESYNC: (1.7-1.8); FILE MERGED 2004/02/24 10:00:10 jmarmion 1.7.170.1: #i21255# text formatting for cell notes<commit_after>/************************************************************************* * * $RCSfile: docfunc.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:55:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DOCFUNC_HXX #define SC_DOCFUNC_HXX #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_POSTIT_HXX #include "postit.hxx" #endif class EditEngine; class SfxUndoAction; class ScAddress; class ScDocShell; class ScMarkData; class ScPatternAttr; class ScRange; class ScRangeName; class ScBaseCell; struct ScTabOpParam; // --------------------------------------------------------------------------- class ScDocFunc { private: ScDocShell& rDocShell; BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE ); void CreateOneName( ScRangeName& rList, SCCOL nPosX, SCROW nPosY, SCTAB nTab, SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2, BOOL& rCancel, BOOL bApi ); void NotifyInputHandler( const ScAddress& rPos ); public: ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {} ~ScDocFunc() {} DECL_LINK( NotifyDrawUndo, SfxUndoAction* ); BOOL DetectiveAddPred(const ScAddress& rPos); BOOL DetectiveDelPred(const ScAddress& rPos); BOOL DetectiveAddSucc(const ScAddress& rPos); BOOL DetectiveDelSucc(const ScAddress& rPos); BOOL DetectiveAddError(const ScAddress& rPos); BOOL DetectiveMarkInvalid(SCTAB nTab); BOOL DetectiveDelAll(SCTAB nTab); BOOL DetectiveRefresh(BOOL bAutomatic = FALSE); BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags, BOOL bRecord, BOOL bApi ); BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType, BOOL bRecord, BOOL bApi ); BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi ); BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi ); BOOL PutData( const ScAddress& rPos, EditEngine& rEngine, BOOL bInterpret, BOOL bApi ); BOOL SetCellText( const ScAddress& rPos, const String& rText, BOOL bInterpret, BOOL bEnglish, BOOL bApi ); // creates a new cell for use with PutCell ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText ); BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi ); BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern, BOOL bRecord, BOOL bApi ); BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName, BOOL bRecord, BOOL bApi ); BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi, BOOL bPartOfPaste = FALSE ); BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi ); BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos, BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi ); BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi ); BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi ); BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi ); BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi ); BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi ); BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges, SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips, BOOL bRecord, BOOL bApi ); BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos, BOOL bRecord, BOOL bSetModified, BOOL bApi ); BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos, BOOL bRecord, BOOL bSetModified, BOOL bApi ); BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi ); BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi ); BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi ); BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi ); BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark, USHORT nFormatNo, BOOL bRecord, BOOL bApi ); BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark, const String& rString, BOOL bApi, BOOL bEnglish ); BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark, const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi ); BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, BOOL bRecord, BOOL bApi ); BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd, double fStart, double fStep, double fMax, BOOL bRecord, BOOL bApi ); // FillAuto: rRange wird von Source-Range auf Dest-Range angepasst BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark, FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi ); BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi ); BOOL MergeCells( const ScRange& rRange, BOOL bContents, BOOL bRecord, BOOL bApi ); BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi ); BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi ); BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi ); BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi ); BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi ); BOOL InsertAreaLink( const String& rFile, const String& rFilter, const String& rOptions, const String& rSource, const ScRange& rDestRange, ULONG nRefresh, BOOL bFitBlock, BOOL bApi ); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: namedlg.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:38:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_NAMEDLG_HXX #define SC_NAMEDLG_HXX #ifndef _MOREBTN_HXX //autogen #include <vcl/morebtn.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef SC_RANGENAM_HXX #include "rangenam.hxx" #endif #ifndef SC_ANYREFDG_HXX #include "anyrefdg.hxx" #endif class ScViewData; class ScDocument; //================================================================== class ScNameDlg : public ScAnyRefDlg { private: FixedLine aFlName; ComboBox aEdName; FixedLine aFlAssign; ScRefEdit aEdAssign; ScRefButton aRbAssign; FixedLine aFlType; CheckBox aBtnPrintArea; CheckBox aBtnColHeader; CheckBox aBtnCriteria; CheckBox aBtnRowHeader; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; PushButton aBtnAdd; PushButton aBtnRemove; MoreButton aBtnMore; BOOL bSaved; const String aStrAdd; // "Hinzufuegen" const String aStrModify; // "Aendern" const String errMsgInvalidSym; ScViewData* pViewData; ScDocument* pDoc; ScRangeName aLocalRangeName; const ScAddress theCursorPos; Selection theCurSel; #ifdef _NAMEDLG_CXX private: void Init(); void UpdateChecks(); void UpdateNames(); void CalcCurTableAssign( String& aAssign, USHORT nPos ); // Handler: DECL_LINK( OkBtnHdl, void * ); DECL_LINK( CancelBtnHdl, void * ); DECL_LINK( AddBtnHdl, void * ); DECL_LINK( RemoveBtnHdl, void * ); DECL_LINK( EdModifyHdl, Edit * ); DECL_LINK( NameSelectHdl, void * ); DECL_LINK( AssignGetFocusHdl, void * ); #endif protected: virtual void RefInputDone( BOOL bForced = FALSE ); public: ScNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData, const ScAddress& aCursorPos ); ~ScNameDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual BOOL IsRefInputMode() const; virtual void SetActive(); virtual BOOL Close(); }; #endif // SC_NAMEDLG_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.700); FILE MERGED 2008/04/01 15:30:57 thb 1.6.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:47 thb 1.6.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:44 rt 1.6.700.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: namedlg.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_NAMEDLG_HXX #define SC_NAMEDLG_HXX #ifndef _MOREBTN_HXX //autogen #include <vcl/morebtn.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _GROUP_HXX //autogen #include <vcl/group.hxx> #endif #include <vcl/fixed.hxx> #include "rangenam.hxx" #include "anyrefdg.hxx" class ScViewData; class ScDocument; //================================================================== class ScNameDlg : public ScAnyRefDlg { private: FixedLine aFlName; ComboBox aEdName; FixedLine aFlAssign; ScRefEdit aEdAssign; ScRefButton aRbAssign; FixedLine aFlType; CheckBox aBtnPrintArea; CheckBox aBtnColHeader; CheckBox aBtnCriteria; CheckBox aBtnRowHeader; OKButton aBtnOk; CancelButton aBtnCancel; HelpButton aBtnHelp; PushButton aBtnAdd; PushButton aBtnRemove; MoreButton aBtnMore; BOOL bSaved; const String aStrAdd; // "Hinzufuegen" const String aStrModify; // "Aendern" const String errMsgInvalidSym; ScViewData* pViewData; ScDocument* pDoc; ScRangeName aLocalRangeName; const ScAddress theCursorPos; Selection theCurSel; #ifdef _NAMEDLG_CXX private: void Init(); void UpdateChecks(); void UpdateNames(); void CalcCurTableAssign( String& aAssign, USHORT nPos ); // Handler: DECL_LINK( OkBtnHdl, void * ); DECL_LINK( CancelBtnHdl, void * ); DECL_LINK( AddBtnHdl, void * ); DECL_LINK( RemoveBtnHdl, void * ); DECL_LINK( EdModifyHdl, Edit * ); DECL_LINK( NameSelectHdl, void * ); DECL_LINK( AssignGetFocusHdl, void * ); #endif protected: virtual void RefInputDone( BOOL bForced = FALSE ); public: ScNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScViewData* ptrViewData, const ScAddress& aCursorPos ); ~ScNameDlg(); virtual void SetReference( const ScRange& rRef, ScDocument* pDoc ); virtual BOOL IsRefInputMode() const; virtual void SetActive(); virtual BOOL Close(); }; #endif // SC_NAMEDLG_HXX <|endoftext|>
<commit_before>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file PhaseWindup.cpp * Implement computations of phase windup, solar ephemeris, satellite attitude * and eclipse at the satellite. */ // ----------------------------------------------------------------------------------- // GPSTk includes #include "Matrix.hpp" #include "geometry.hpp" // DEG_TO_RAD #include "icd_200_constants.hpp" // TWO_PI // geomatics #include "PhaseWindup.hpp" #include "SunEarthSatGeometry.hpp" using namespace std; namespace gpstk { // ----------------------------------------------------------------------------------- // Compute the phase windup, in cycles, given the time, the unit vector from receiver // to transmitter, and the west and north unit vectors at the receiver, all in ECEF. // YR is the West unit vector, XR is the North unit vector, at the receiver. // shadow is the fraction of the sun's area not visible at the satellite. // Previous value is needed to ensure continuity and prevent 1-cycle ambiguities. double PhaseWindup(double& prev, // previous return value DayTime& tt, // epoch of interest Position& SV, // satellite position Position& Rx2Tx, // unit vector from receiver to satellite Position& YR, // west unit vector at receiver Position& XR, // north unit vector at receiver SolarSystem& SSEph, // solar system ephemeris EarthOrientation& EO, // earth orientation at tt double& shadow, // fraction of sun not visible at satellite bool isBlockR) // true for Block IIR satellites throw(Exception) { try { double d,windup; Position DR,DT; Position TR = -1.0 * Rx2Tx; // transmitter to receiver // get satellite attitude Position XT,YT,ZT; Matrix<double> Att = SatelliteAttitude(tt, SV, SSEph, EO, shadow); XT = Position(Att(0,0),Att(0,1),Att(0,2)); // Cartesian is default YT = Position(Att(1,0),Att(1,1),Att(1,2)); ZT = Position(Att(2,0),Att(2,1),Att(2,2)); // NB. Block IIR has X (ie the effective dipole orientation) in the -XT direction. // Ref. Kouba(2009) GPS Solutions 13, pp1-12. // In fact it should be a rotation by pi about Z, producing a constant offset. //if(isBlockR) { // XT = Position(-Att(0,0),-Att(0,1),-Att(0,2)); // YT = Position(-Att(1,0),-Att(1,1),-Att(1,2)); //} // compute effective dipoles at receiver and transmitter // Ref Kouba(2009) Using IGS Products; switching last signs <=> overall sign windup DR = XR - TR * TR.dot(XR) + Position(TR.cross(YR)); DT = XT - TR * TR.dot(XT) - Position(TR.cross(YT)); // normalize d = 1.0/DR.mag(); DR = d * DR; d = 1.0/DT.mag(); DT = d * DT; windup = ::acos(DT.dot(DR)) / TWO_PI; // cycles if(TR.dot(DR.cross(DT)) < 0.) windup *= -1.0; // adjust by 2pi if necessary d = windup-prev; windup -= int(d + (d < 0.0 ? -0.5 : 0.5)); return windup; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // ----------------------------------------------------------------------------------- // Version without JPL solar system ephemeris - uses a lower quality solar position. // Compute the phase windup, in cycles, given the time, the unit vector from receiver // to transmitter, and the west and north unit vectors at the receiver, all in ECEF. // YR is the West unit vector, XR is the North unit vector, at the receiver. // shadow is the fraction of the sun's area not visible at the satellite. double PhaseWindup(double& prev, // previous return value DayTime& tt, // epoch of interest Position& SV, // satellite position Position& Rx2Tx, // unit vector from receiver to satellite Position& YR, // west unit vector at receiver Position& XR, // north unit vector at receiver double& shadow, // fraction of sun not visible at satellite bool isBlockR) // true for Block IIR satellites throw(Exception) { try { double d,windup=0.0; Position DR,DT; Position TR = -1.0 * Rx2Tx; // transmitter to receiver // get satellite attitude Position XT,YT,ZT; Matrix<double> Att = SatelliteAttitude(tt, SV, shadow); XT = Position(Att(0,0),Att(0,1),Att(0,2)); // Cartesian is default YT = Position(Att(1,0),Att(1,1),Att(1,2)); ZT = Position(Att(2,0),Att(2,1),Att(2,2)); // NB. Block IIR has X (ie the effective dipole orientation) in the -XT direction. // Ref. Kouba(2009) GPS Solutions 13, pp1-12. if(isBlockR) XT = Position(-Att(0,0),-Att(0,1),-Att(0,2)); // compute effective dipoles at receiver and transmitter // Ref Kouba(2009) Using IGS Products; switching last signs <=> overall sign windup DR = XR - TR * TR.dot(XR) + Position(TR.cross(YR)); DT = XT - TR * TR.dot(XT) - Position(TR.cross(YT)); // normalize d = 1.0/DR.mag(); DR = d * DR; d = 1.0/DT.mag(); DT = d * DT; windup = ::acos(DT.dot(DR)) / TWO_PI; if(TR.dot(DR.cross(DT)) < 0.) windup *= -1.0; // adjust by 2pi if necessary d = windup-prev; windup -= int(d + (d < 0.0 ? -0.5 : 0.5)); return windup; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } } // end namespace gpstk //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ <commit_msg>Clarify documentation only; update RINEX3 version to main branch version<commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file PhaseWindup.cpp * Implement computations of phase windup, solar ephemeris, satellite attitude * and eclipse at the satellite. */ // ----------------------------------------------------------------------------------- // GPSTk includes #include "Matrix.hpp" #include "geometry.hpp" // DEG_TO_RAD #include "icd_200_constants.hpp" // TWO_PI // geomatics #include "PhaseWindup.hpp" #include "SunEarthSatGeometry.hpp" using namespace std; namespace gpstk { // ----------------------------------------------------------------------------------- // Compute the phase windup, in cycles, given the time, the unit vector from receiver // to transmitter, and the west and north unit vectors at the receiver, all in ECEF. // YR is the West unit vector, XR is the North unit vector, at the receiver. // shadow is the fraction of the sun's area not visible at the satellite. // Previous value is needed to ensure continuity and prevent 1-cycle ambiguities. double PhaseWindup(double& prev, // previous return value DayTime& tt, // epoch of interest Position& SV, // satellite position Position& Rx2Tx, // unit vector from receiver to satellite Position& YR, // west unit vector at receiver Position& XR, // north unit vector at receiver SolarSystem& SSEph, // solar system ephemeris EarthOrientation& EO, // earth orientation at tt double& shadow, // fraction of sun not visible at satellite bool isBlockR) // true for Block IIR satellites throw(Exception) { try { double d,windup; Position DR,DT; Position TR = -1.0 * Rx2Tx; // transmitter to receiver // get satellite attitude Position XT,YT,ZT; Matrix<double> Att = SatelliteAttitude(tt, SV, SSEph, EO, shadow); XT = Position(Att(0,0),Att(0,1),Att(0,2)); // Cartesian is default YT = Position(Att(1,0),Att(1,1),Att(1,2)); ZT = Position(Att(2,0),Att(2,1),Att(2,2)); // NB. Block IIR has X (ie the effective dipole orientation) in the -XT direction. // Ref. Kouba(2009) GPS Solutions 13, pp1-12. // In fact it should be a rotation by pi about Z, producing a constant offset. //if(isBlockR) { // XT = Position(-Att(0,0),-Att(0,1),-Att(0,2)); // YT = Position(-Att(1,0),-Att(1,1),-Att(1,2)); //} // compute effective dipoles at receiver and transmitter // Ref Kouba(2009) Using IGS Products; note sign diff. <=> East(ref) West(here) // NB. switching second sign between the two eqns <=> overall sign windup DR = XR - TR * TR.dot(XR) + Position(TR.cross(YR)); DT = XT - TR * TR.dot(XT) - Position(TR.cross(YT)); // normalize d = 1.0/DR.mag(); DR = d * DR; d = 1.0/DT.mag(); DT = d * DT; windup = ::acos(DT.dot(DR)) / TWO_PI; // cycles if(TR.dot(DR.cross(DT)) < 0.) windup *= -1.0; // adjust by 2pi if necessary d = windup-prev; windup -= int(d + (d < 0.0 ? -0.5 : 0.5)); return windup; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // ----------------------------------------------------------------------------------- // Version without JPL solar system ephemeris - uses a lower quality solar position. // Compute the phase windup, in cycles, given the time, the unit vector from receiver // to transmitter, and the west and north unit vectors at the receiver, all in ECEF. // YR is the West unit vector, XR is the North unit vector, at the receiver. // shadow is the fraction of the sun's area not visible at the satellite. double PhaseWindup(double& prev, // previous return value DayTime& tt, // epoch of interest Position& SV, // satellite position Position& Rx2Tx, // unit vector from receiver to satellite Position& YR, // west unit vector at receiver Position& XR, // north unit vector at receiver double& shadow, // fraction of sun not visible at satellite bool isBlockR) // true for Block IIR satellites throw(Exception) { try { double d,windup=0.0; Position DR,DT; Position TR = -1.0 * Rx2Tx; // transmitter to receiver // get satellite attitude Position XT,YT,ZT; Matrix<double> Att = SatelliteAttitude(tt, SV, shadow); XT = Position(Att(0,0),Att(0,1),Att(0,2)); // Cartesian is default YT = Position(Att(1,0),Att(1,1),Att(1,2)); ZT = Position(Att(2,0),Att(2,1),Att(2,2)); // NB. Block IIR has X (ie the effective dipole orientation) in the -XT direction. // Ref. Kouba(2009) GPS Solutions 13, pp1-12. if(isBlockR) XT = Position(-Att(0,0),-Att(0,1),-Att(0,2)); // compute effective dipoles at receiver and transmitter // Ref Kouba(2009) Using IGS Products; note sign diff. <=> East(ref) West(here) // NB. switching second sign between the two eqns <=> overall sign windup DR = XR - TR * TR.dot(XR) + Position(TR.cross(YR)); DT = XT - TR * TR.dot(XT) - Position(TR.cross(YT)); // normalize d = 1.0/DR.mag(); DR = d * DR; d = 1.0/DT.mag(); DT = d * DT; windup = ::acos(DT.dot(DR)) / TWO_PI; if(TR.dot(DR.cross(DT)) < 0.) windup *= -1.0; // adjust by 2pi if necessary d = windup-prev; windup -= int(d + (d < 0.0 ? -0.5 : 0.5)); return windup; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } } // end namespace gpstk //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] 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 error_info_defs.H /// @brief Defines to support the Error Information class /// #ifndef FAPI2_ERRORINFO_DEFS_H_ #define FAPI2_ERRORINFO_DEFS_H_ #include <stdint.h> #include <target.H> #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) #include <variable_buffer.H> #include <utility> #endif namespace fapi2 { /// /// @brief Type to hold the ffdc data to be sent to hostboot /// /// Note: Typical data sent seems to be register/addresss info /// rather than use extra space converting stuff just /// send a uint64 always /// struct sbeFfdc_t { uint32_t size; uint64_t data; }; // 10 entries limits the size of SbeFfdcData_t to 128 bytes enum { MAX_SBE_FFDC_ENTRIES = 10 }; // Data type for SBE ffdc buffer sent through fifo typedef struct { uint32_t fapiRc; // Return code from failure uint32_t ffdcLength; // length of Fapi FFDC data (in bytes) struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data } SbeFfdcData_t; // 128 bytes /// /// @brief Type to hold the ffdc element in the ffdc class /// Needed so that the size can be squirled away before the /// macro is called. /// struct ffdc_struct { const void* ptr; size_t size; }; class ffdc_t { public: ffdc_t(void) {} void operator=(const ffdc_t& i ) { iv_value.ptr = i.ptr(); iv_value.size = i.size(); } operator const void* () const { return iv_value.ptr; } operator uint8_t() const { return *(reinterpret_cast<const uint8_t*>(iv_value.ptr)); } size_t size(void) const { return iv_value.size; } size_t& size(void) { return iv_value.size; } const void* ptr(void) const { return iv_value.ptr; } const void*& ptr(void) { return iv_value.ptr; } private: struct ffdc_struct iv_value = {}; //init to zero }; /// /// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a /// special type that cannot simply be memcopied enum ErrorInfoFfdcSize { EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T> EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb }; /// /// @brief Enumeration of error log severity. /// enum errlSeverity_t { FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general }; /// /// @brief Enumeration of ErrorInfo types /// enum ErrorInfoType { EI_TYPE_FFDC = 0, EI_TYPE_HW_CALLOUT = 1, EI_TYPE_PROCEDURE_CALLOUT = 2, EI_TYPE_BUS_CALLOUT = 3, EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD EI_TYPE_COLLECT_TRACE = 6, EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1, }; #ifndef MINIMUM_FFDC /// /// @enum HwCallout /// /// This enumeration defines the possible Hardware Callouts that are not /// represented by fapi2::Targets /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace HwCallouts { enum HwCallout { // Where indicated, a HW Callout in FAPI Error XML must include a // reference target that is used to identify the HW. e.g. for // TOD_CLOCK, the proc chip that the clock is attached to must be // specified TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet) MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet) PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet) PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet) FLASH_CONTROLLER_PART = 4, PNOR_PART = 5, SBE_SEEPROM_PART = 6, VPD_PART = 7, LPC_SLAVE_PART = 8, GPIO_EXPANDER_PART = 9, SPIVID_SLAVE_PART = 10, }; } /// /// @enum ProcedureCallout /// /// This enumeration defines the possible Procedure Callouts /// These instruct the customer/customer-engineer what to do /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace ProcedureCallouts { enum ProcedureCallout { CODE = 0, // Code problem LVL_SUPPORT = 1, // Call next level of support MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error BUS_CALLOUT = 3, // Bus Called Out }; } /// /// @enum CalloutPriority /// /// This enumeration defines the possible Procedure and Target callout priorities /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform priority value /// so do not reorder without consulting all platforms /// namespace CalloutPriorities { enum CalloutPriority { LOW = 0, MEDIUM = 1, HIGH = 2, }; } /// /// @enum CollectTrace /// /// This enumeration defines the possible firmware traces to collect /// namespace CollectTraces { const uint32_t TRACE_SIZE = 256; // limit collected trace size enum CollectTrace { FSI = 1, SCOM = 2, SCAN = 3, MBOX = 4, }; } // NOTE - this assumes no buffer_t or variable_buffers are passed // data is converted to a uint64_t when placed into the sbe ffdc // buffer inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc ) { fapi2::ffdc_t temp; temp.size() = static_cast<size_t>(i_sbeFfdc.size); if(temp.size() == EI_FFDC_SIZE_TARGET) { #ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET uint64_t targetData = i_sbeFfdc.data; fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32); uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF); // call hostboot to get the fapi2 target reference temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance)); #endif } else { // adjust the pointer based on the data size. temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) + (sizeof(uint64_t) - i_sbeFfdc.size)); } return temp; } #endif /// /// @brief Get FFDC Size /// /// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of /// FFDC data. If the data is of a special type that is handled differently /// than types that are simply memcopied then it is handled by a template /// specialization. /// If this function template is instantiated with a pointer, the compile /// will fail. /// /// @return uint16_t. Size of the FFDC data /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T&) { static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE, "FFDC too large to capture"); return sizeof(T); } #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) /// /// @brief Compile error if caller tries to get the FFDC size of a pointer /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T*) { static_assert(std::is_pointer<T>::value, "pointer passed to getErrorInfoFfdcSize"); return 0; } #endif /// /// @brief Get FFDC Size specialization for fapi2::Target /// template<fapi2::TargetType T, typename V> inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&) { return EI_FFDC_SIZE_TARGET; } #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) /// /// @brief Get FFDC Size specialization for variable buffers /// template<> inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing) { // Limit a variable buffer to 4kb bytes, and we can memcpy the storage. return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE), i_thing.getLength<uint8_t>()); } #endif }; #endif // FAPI2_ERRORINFO_DEFS_H_ <commit_msg>pack the sbeFfdc_t structure so that SbeFfdcData_t will be correct<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] 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 error_info_defs.H /// @brief Defines to support the Error Information class /// #ifndef FAPI2_ERRORINFO_DEFS_H_ #define FAPI2_ERRORINFO_DEFS_H_ #include <stdint.h> #include <target.H> #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) #include <variable_buffer.H> #include <utility> #endif namespace fapi2 { /// /// @brief Type to hold the ffdc data to be sent to hostboot /// /// Note: Typical data sent seems to be register/addresss info /// rather than use extra space converting stuff just /// send a uint64 always /// struct sbeFfdc_t { uint32_t size; uint64_t data; } __attribute__((packed)); // 10 entries limits the size of SbeFfdcData_t to 128 bytes enum { MAX_SBE_FFDC_ENTRIES = 10 }; // Data type for SBE ffdc buffer sent through fifo typedef struct { uint32_t fapiRc; // Return code from failure uint32_t ffdcLength; // length of Fapi FFDC data (in bytes) struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data } SbeFfdcData_t; // 128 bytes /// /// @brief Type to hold the ffdc element in the ffdc class /// Needed so that the size can be squirled away before the /// macro is called. /// struct ffdc_struct { const void* ptr; size_t size; }; class ffdc_t { public: ffdc_t(void) {} void operator=(const ffdc_t& i ) { iv_value.ptr = i.ptr(); iv_value.size = i.size(); } operator const void* () const { return iv_value.ptr; } operator uint8_t() const { return *(reinterpret_cast<const uint8_t*>(iv_value.ptr)); } size_t size(void) const { return iv_value.size; } size_t& size(void) { return iv_value.size; } const void* ptr(void) const { return iv_value.ptr; } const void*& ptr(void) { return iv_value.ptr; } private: struct ffdc_struct iv_value = {}; //init to zero }; /// /// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a /// special type that cannot simply be memcopied enum ErrorInfoFfdcSize { EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T> EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb }; /// /// @brief Enumeration of error log severity. /// enum errlSeverity_t { FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general }; /// /// @brief Enumeration of ErrorInfo types /// enum ErrorInfoType { EI_TYPE_FFDC = 0, EI_TYPE_HW_CALLOUT = 1, EI_TYPE_PROCEDURE_CALLOUT = 2, EI_TYPE_BUS_CALLOUT = 3, EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD EI_TYPE_COLLECT_TRACE = 6, EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1, }; #ifndef MINIMUM_FFDC /// /// @enum HwCallout /// /// This enumeration defines the possible Hardware Callouts that are not /// represented by fapi2::Targets /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace HwCallouts { enum HwCallout { // Where indicated, a HW Callout in FAPI Error XML must include a // reference target that is used to identify the HW. e.g. for // TOD_CLOCK, the proc chip that the clock is attached to must be // specified TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet) MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet) PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet) PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet) FLASH_CONTROLLER_PART = 4, PNOR_PART = 5, SBE_SEEPROM_PART = 6, VPD_PART = 7, LPC_SLAVE_PART = 8, GPIO_EXPANDER_PART = 9, SPIVID_SLAVE_PART = 10, }; } /// /// @enum ProcedureCallout /// /// This enumeration defines the possible Procedure Callouts /// These instruct the customer/customer-engineer what to do /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace ProcedureCallouts { enum ProcedureCallout { CODE = 0, // Code problem LVL_SUPPORT = 1, // Call next level of support MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error BUS_CALLOUT = 3, // Bus Called Out }; } /// /// @enum CalloutPriority /// /// This enumeration defines the possible Procedure and Target callout priorities /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform priority value /// so do not reorder without consulting all platforms /// namespace CalloutPriorities { enum CalloutPriority { LOW = 0, MEDIUM = 1, HIGH = 2, }; } /// /// @enum CollectTrace /// /// This enumeration defines the possible firmware traces to collect /// namespace CollectTraces { const uint32_t TRACE_SIZE = 256; // limit collected trace size enum CollectTrace { FSI = 1, SCOM = 2, SCAN = 3, MBOX = 4, }; } // NOTE - this assumes no buffer_t or variable_buffers are passed // data is converted to a uint64_t when placed into the sbe ffdc // buffer inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc ) { fapi2::ffdc_t temp; temp.size() = static_cast<size_t>(i_sbeFfdc.size); if(temp.size() == EI_FFDC_SIZE_TARGET) { #ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET uint64_t targetData = i_sbeFfdc.data; fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32); uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF); // call hostboot to get the fapi2 target reference temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance)); #endif } else { // adjust the pointer based on the data size. temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) + (sizeof(uint64_t) - i_sbeFfdc.size)); } return temp; } #endif /// /// @brief Get FFDC Size /// /// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of /// FFDC data. If the data is of a special type that is handled differently /// than types that are simply memcopied then it is handled by a template /// specialization. /// If this function template is instantiated with a pointer, the compile /// will fail. /// /// @return uint16_t. Size of the FFDC data /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T&) { static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE, "FFDC too large to capture"); return sizeof(T); } #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) /// /// @brief Compile error if caller tries to get the FFDC size of a pointer /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T*) { static_assert(std::is_pointer<T>::value, "pointer passed to getErrorInfoFfdcSize"); return 0; } #endif /// /// @brief Get FFDC Size specialization for fapi2::Target /// template<fapi2::TargetType T, typename V> inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&) { return EI_FFDC_SIZE_TARGET; } #if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC) /// /// @brief Get FFDC Size specialization for variable buffers /// template<> inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing) { // Limit a variable buffer to 4kb bytes, and we can memcpy the storage. return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE), i_thing.getLength<uint8_t>()); } #endif }; #endif // FAPI2_ERRORINFO_DEFS_H_ <|endoftext|>
<commit_before>/* kopeteemoticons.cpp - Kopete Preferences Container-Class Copyright (c) 2002 by Stefan Gehn <metz AT gehn.net> Copyright (c) 2002 by Olivier Goffart <ogoffart@tiscalinet.be> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteemoticons.h" #include "kopeteprefs.h" #include <qdom.h> #include <qfile.h> #include <qregexp.h> #include <qstylesheet.h> #include <qimage.h> #include <kapplication.h> #include <kdebug.h> #include <kstandarddirs.h> KopeteEmoticons *KopeteEmoticons::s_instance = 0L; KopeteEmoticons *KopeteEmoticons::emoticons() { if( !s_instance ) s_instance = new KopeteEmoticons; return s_instance; } KopeteEmoticons::KopeteEmoticons( const QString &theme ) : QObject( kapp, "KopeteEmoticons" ) { // kdDebug(14010) << "KopeteEmoticons::KopeteEmoticons" << endl; if(theme.isNull()) { initEmoticons(); connect( KopetePrefs::prefs(), SIGNAL(saved()), this, SLOT(initEmoticons()) ); } else { initEmoticons( theme ); } } void KopeteEmoticons::addIfPossible( const QString& filenameNoExt, QStringList emoticons ) { KStandardDirs *dir = KGlobal::dirs(); QString pic; //maybe an extension was given, so try to find the exact file pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt ); if( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".mng" ) ); if ( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".png" ) ); if ( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".gif" ) ); if( !pic.isNull() ) // only add if we found one file { // kdDebug(14010) << "KopeteEmoticons::addIfPossible : found pixmap for emoticons" <<endl; map[pic] = emoticons; } } void KopeteEmoticons::initEmoticons( const QString &theme ) { if(theme.isNull()) { if ( m_theme == KopetePrefs::prefs()->iconTheme() ) return; m_theme = KopetePrefs::prefs()->iconTheme(); } else m_theme = theme; // kdDebug(14010) << k_funcinfo << "Called" << endl; map.clear(); // empty the mapping QDomDocument emoticonMap( QString::fromLatin1( "messaging-emoticon-map" ) ); QString filename = KGlobal::dirs()->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/emoticons.xml" ) ); if( filename.isEmpty() ) { kdDebug(14010) << "KopeteEmoticons::initEmoticons : WARNING: emoticon-map not found" <<endl; return ; } QFile mapFile( filename ); mapFile.open( IO_ReadOnly ); emoticonMap.setContent( &mapFile ); QDomElement list = emoticonMap.documentElement(); QDomNode node = list.firstChild(); while( !node.isNull() ) { QDomElement element = node.toElement(); if( !element.isNull() ) { if( element.tagName() == QString::fromLatin1( "emoticon" ) ) { QString emoticon_file = element.attribute( QString::fromLatin1( "file" ), QString::null ); QStringList items; QDomNode emoticonNode = node.firstChild(); while( !emoticonNode.isNull() ) { QDomElement emoticonElement = emoticonNode.toElement(); if( !emoticonElement.isNull() ) { if( emoticonElement.tagName() == QString::fromLatin1( "string" ) ) { items << emoticonElement.text(); } else { kdDebug(14010) << k_funcinfo << "Warning: Unknown element '" << element.tagName() << "' in emoticon data" << endl; } } emoticonNode = emoticonNode.nextSibling(); } addIfPossible ( emoticon_file, items ); } else { kdDebug(14010) << k_funcinfo << "Warning: Unknown element '" << element.tagName() << "' in map file" << endl; } } node = node.nextSibling(); } mapFile.close(); } QString KopeteEmoticons::emoticonToPicPath ( const QString& em ) { EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) { // search in QStringList data for emoticon if ( it.data().findIndex(em) != -1 ) return it.key(); // if found return path for corresponding animation or pixmap } return QString(); } QStringList KopeteEmoticons::picPathToEmoticon ( const QString& path ) { EmoticonMap::Iterator it = map.find( path ); if ( it != map.end() ) return it.data(); return QStringList(); } QStringList KopeteEmoticons::emoticonList() { QStringList retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal += it.data(); return retVal; } QStringList KopeteEmoticons::picList() { QStringList retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal += it.key(); return retVal; } QMap<QString, QString> KopeteEmoticons::emoticonAndPicList() { QMap<QString, QString> retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal[it.data().first()] = it.key(); return retVal; } QString KopeteEmoticons::parseEmoticons( QString message ) { // if emoticons are disabled, we do nothing if ( !KopetePrefs::prefs()->useEmoticons() ) return message; QStringList emoticons = KopeteEmoticons::emoticons()->emoticonList(); /* * FIXME: do proper emoticon support * Testcase: * * All emoticons: * :-):-(:-):-):-) :-) * * MSN Messenger & gaim see the :p emoticon, we should see it too * msn:possible * * Display the emoticon without breaking the link * http://blah.com/something:-) * * Show the trailing emoticon * funny:-) * */ for ( QStringList::Iterator it = emoticons.begin(); it != emoticons.end(); ++it ) { QString es=QStyleSheet::escape(*it); if(message.contains(es)) { QString em = QRegExp::escape( es ); QString imgPath = KopeteEmoticons::emoticons()->emoticonToPicPath( *it ); QImage iconImage(imgPath); message.replace( QRegExp(QString::fromLatin1( "(^|[\\W\\s]|%1)(%2)(?!\\w)" ).arg(em).arg(em)), QString::fromLatin1("\\1<img align=\"center\" width=\"") + QString::number(iconImage.width()) + QString::fromLatin1("\" height=\"") + QString::number(iconImage.height()) + QString::fromLatin1("\" src=\"") + imgPath + QString::fromLatin1("\" title=\"") + es + QString::fromLatin1( "\"/>" ) ); } } return message; } //%1%1%1%1 #include "kopeteemoticons.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>more comments<commit_after>/* kopeteemoticons.cpp - Kopete Preferences Container-Class Copyright (c) 2002 by Stefan Gehn <metz AT gehn.net> Copyright (c) 2002 by Olivier Goffart <ogoffart@tiscalinet.be> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteemoticons.h" #include "kopeteprefs.h" #include <qdom.h> #include <qfile.h> #include <qregexp.h> #include <qstylesheet.h> #include <qimage.h> #include <kapplication.h> #include <kdebug.h> #include <kstandarddirs.h> KopeteEmoticons *KopeteEmoticons::s_instance = 0L; KopeteEmoticons *KopeteEmoticons::emoticons() { if( !s_instance ) s_instance = new KopeteEmoticons; return s_instance; } KopeteEmoticons::KopeteEmoticons( const QString &theme ) : QObject( kapp, "KopeteEmoticons" ) { // kdDebug(14010) << "KopeteEmoticons::KopeteEmoticons" << endl; if(theme.isNull()) { initEmoticons(); connect( KopetePrefs::prefs(), SIGNAL(saved()), this, SLOT(initEmoticons()) ); } else { initEmoticons( theme ); } } void KopeteEmoticons::addIfPossible( const QString& filenameNoExt, QStringList emoticons ) { KStandardDirs *dir = KGlobal::dirs(); QString pic; //maybe an extension was given, so try to find the exact file pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt ); if( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".mng" ) ); if ( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".png" ) ); if ( pic.isNull() ) pic = dir->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/" ) + filenameNoExt + QString::fromLatin1( ".gif" ) ); if( !pic.isNull() ) // only add if we found one file { // kdDebug(14010) << "KopeteEmoticons::addIfPossible : found pixmap for emoticons" <<endl; map[pic] = emoticons; } } void KopeteEmoticons::initEmoticons( const QString &theme ) { if(theme.isNull()) { if ( m_theme == KopetePrefs::prefs()->iconTheme() ) return; m_theme = KopetePrefs::prefs()->iconTheme(); } else m_theme = theme; // kdDebug(14010) << k_funcinfo << "Called" << endl; map.clear(); // empty the mapping QDomDocument emoticonMap( QString::fromLatin1( "messaging-emoticon-map" ) ); QString filename = KGlobal::dirs()->findResource( "data", QString::fromLatin1( "kopete/pics/emoticons/" ) + m_theme + QString::fromLatin1( "/emoticons.xml" ) ); if( filename.isEmpty() ) { kdDebug(14010) << "KopeteEmoticons::initEmoticons : WARNING: emoticon-map not found" <<endl; return ; } QFile mapFile( filename ); mapFile.open( IO_ReadOnly ); emoticonMap.setContent( &mapFile ); QDomElement list = emoticonMap.documentElement(); QDomNode node = list.firstChild(); while( !node.isNull() ) { QDomElement element = node.toElement(); if( !element.isNull() ) { if( element.tagName() == QString::fromLatin1( "emoticon" ) ) { QString emoticon_file = element.attribute( QString::fromLatin1( "file" ), QString::null ); QStringList items; QDomNode emoticonNode = node.firstChild(); while( !emoticonNode.isNull() ) { QDomElement emoticonElement = emoticonNode.toElement(); if( !emoticonElement.isNull() ) { if( emoticonElement.tagName() == QString::fromLatin1( "string" ) ) { items << emoticonElement.text(); } else { kdDebug(14010) << k_funcinfo << "Warning: Unknown element '" << element.tagName() << "' in emoticon data" << endl; } } emoticonNode = emoticonNode.nextSibling(); } addIfPossible ( emoticon_file, items ); } else { kdDebug(14010) << k_funcinfo << "Warning: Unknown element '" << element.tagName() << "' in map file" << endl; } } node = node.nextSibling(); } mapFile.close(); } QString KopeteEmoticons::emoticonToPicPath ( const QString& em ) { EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) { // search in QStringList data for emoticon if ( it.data().findIndex(em) != -1 ) return it.key(); // if found return path for corresponding animation or pixmap } return QString(); } QStringList KopeteEmoticons::picPathToEmoticon ( const QString& path ) { EmoticonMap::Iterator it = map.find( path ); if ( it != map.end() ) return it.data(); return QStringList(); } QStringList KopeteEmoticons::emoticonList() { QStringList retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal += it.data(); return retVal; } QStringList KopeteEmoticons::picList() { QStringList retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal += it.key(); return retVal; } QMap<QString, QString> KopeteEmoticons::emoticonAndPicList() { QMap<QString, QString> retVal; EmoticonMap::Iterator it; for ( it = map.begin(); it != map.end(); ++it ) retVal[it.data().first()] = it.key(); return retVal; } QString KopeteEmoticons::parseEmoticons( QString message ) { // if emoticons are disabled, we do nothing if ( !KopetePrefs::prefs()->useEmoticons() ) return message; QStringList emoticons = KopeteEmoticons::emoticons()->emoticonList(); /* * FIXME: do proper emoticon support * Testcase: * * All emoticons: * :-):-(:-):-):-) :-) * * MSN Messenger & gaim see the :p emoticon, we should see it too * msn:possible * * Display the emoticon without breaking the link * http://blah.com/something:-) * * Show the trailing emoticon * funny:-) * * Does not include some html escaped code in the emoticon * >) &) ) ( &nbsp;) ) * * Parse bigger emoticons first * >:-) * * Do not parse emiticons if they are in a html tag: * <img src="..." title=">:-)" /> */ for ( QStringList::Iterator it = emoticons.begin(); it != emoticons.end(); ++it ) { QString es=QStyleSheet::escape(*it); if(message.contains(es)) { QString em = QRegExp::escape( es ); QString imgPath = KopeteEmoticons::emoticons()->emoticonToPicPath( *it ); QImage iconImage(imgPath); message.replace( QRegExp(QString::fromLatin1( "(^|[\\W\\s]|%1)(%2)(?!\\w)" ).arg(em).arg(em)), QString::fromLatin1("\\1<img align=\"center\" width=\"") + QString::number(iconImage.width()) + QString::fromLatin1("\" height=\"") + QString::number(iconImage.height()) + QString::fromLatin1("\" src=\"") + imgPath + QString::fromLatin1("\" title=\"") + es + QString::fromLatin1( "\"/>" ) ); } } return message; } //%1%1%1%1 #include "kopeteemoticons.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#pragma once /* * Author(s): * - Cedric Gestes <gestes@aldebaran-robotics.com> * - Chris Kilner <ckilner@aldebaran-robotics.com> * * Copyright (C) 2010 Aldebaran Robotics */ #ifndef _QIMESSAGING_MASTER_HPP_ #define _QIMESSAGING_MASTER_HPP_ #include <string> #include <boost/scoped_ptr.hpp> #include <qimessaging/context.hpp> #include <qimessaging/api.hpp> namespace qi { namespace detail { class MasterImpl; } /// <summary> A central directory that allows Services and Topics to /// be discovered. /// </summary> /// \ingroup Messaging class QIMESSAGING_API Master { public: /// <summary> Constructor. </summary> /// <param name="masterAddress"> /// The master address. /// e.g. 127.0.0.1:5555 /// </param> /// <seealso cref="qi::Server"/> /// <seealso cref="qi::Client"/> /// <seealso cref="qi::Publisher"/> /// <seealso cref="qi::Subscriber"/> Master(const std::string& masterAddress = "127.0.0.1:5555", qi::Context *ctx = NULL); /// <summary>Destructor. </summary> virtual ~Master(); /// <summary>Runs the master. </summary> void run(); bool isInitialized() const; private: /// <summary> The private implementation </summary> boost::scoped_ptr<detail::MasterImpl> _impl; }; } #endif // _QIMESSAGING_MASTER_HPP_ <commit_msg>remove old file<commit_after><|endoftext|>
<commit_before>// XAST Packer by yosh778 #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <cinttypes> #include <boost/filesystem.hpp> #define ALIGN_16(n) ((n / 0x10 + (n % 0x10 ? 1 : 0)) * 0x10) #define RBUF_SIZE 0x1000000 using namespace boost::filesystem; void write32(std::fstream& output, uint32_t data) { output.write((char*)&data, (int)sizeof(data)); } uint64_t write64(std::fstream& output, uint64_t data) { output.write((char*)&data, (int)sizeof(data)); } uint32_t read32(std::ifstream& input) { uint32_t data; input.read((char*)&data, (int)sizeof(data)); return data; } uint64_t read64(std::ifstream& input) { uint64_t data; input.read((char*)&data, (int)sizeof(data)); return data; } // Checksum reverse by weaknespase uint32_t checksum(const char* in, const size_t length, int last = 0){ const char* end = in + length; int acc = last; while (in < end) acc = (acc * 33) ^ (unsigned char) *in++; return acc; } typedef struct FileData_ { std::string fullpath; std::string filename; uint32_t pathCheck; uint32_t contentCheck; uint64_t size; } FileData; bool alphaSorter(const FileData& a, const FileData& b) { return a.filename < b.filename; } int main(int argc, char *argv[]) { if ( argc < 3 ) { std::cout << "Usage : " << argv[0] << " <dataPath> <output>" << std::endl; return -1; } std::string inPath = argv[1]; std::string output = argv[2]; // Check input path existence if ( !exists( inPath ) ) { std::cout << "ERROR : Input directory " << inPath << " does not exist" << std::endl; return EXIT_FAILURE; } std::vector<FileData> files; recursive_directory_iterator it( inPath ), end; FileData fileData; uint32_t pathsCount = 0; // Compress input directory recursively for ( ; it != end; ++it ) { bool is_dir = is_directory( *it ); std::string fullpath = it->path().string(); std::string filename = fullpath.substr( inPath.size() ); if ( filename.front() == '/' ) { filename.erase(0, 1); } // Skip any non-existing file if ( !exists( fullpath ) ) continue; if ( !is_dir ) { pathsCount += filename.size() + 1; fileData.filename = filename; fileData.fullpath = fullpath; fileData.pathCheck = checksum( filename.c_str(), filename.size() ); // std::cout << "Checksum for " << filename << " : " << std::hex << fileData.pathCheck << std::dec << std::endl; fileData.size = file_size( fullpath ); files.push_back( fileData ); } } std::sort (files.begin(), files.end(), alphaSorter); uint32_t nbEntries = files.size(); std::fstream oFile( output.c_str(), std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios_base::binary ); if ( !oFile.is_open() ) { std::cout << "Failed to open output file '" << output << "'" << std::endl; return -2; } uint32_t nbUnused = 0; uint32_t maxEntries = nbEntries + nbUnused; uint32_t alignedPathsCount = ALIGN_16(pathsCount); uint32_t data; uint64_t pathsOffset = 0x30 * (1 + maxEntries); uint32_t dataOffset = pathsOffset + alignedPathsCount; // XAST header write32(oFile, 0x54534158); write32(oFile, 0x01010000); // Version : 1.01 write32(oFile, nbEntries); write32(oFile, maxEntries); write32(oFile, pathsCount); write32(oFile, dataOffset); uint32_t unk0 = 0xA02A4B6A; // File checksum ? write32(oFile, unk0); uint32_t headersCount = pathsOffset - 0x30; write32(oFile, headersCount); uint64_t fileSize = -1; write64(oFile, fileSize); write64(oFile, 0); uint64_t nextPathOffset = pathsOffset; uint64_t nextFileOffset = dataOffset; uint32_t unk1 = 0x8113D6D3; uint32_t tmpChecksum = 0xC75EB5E1; uint32_t i = 0; for ( FileData& file : files ) { // std::cout << "opening " << "xai_sums/" << file.filename << std::endl; // std::ifstream iSums( ("xai_sums/" + file.filename).c_str(), std::ios_base::binary ); // if ( iSums.is_open() ) { // // Filepath hash // unk1 = read32(iSums); // checksum = read32(iSums); // } // else{ printf("FATAL ERROR\n"); return -11;} // iSums.close(); std::cout << "Checksum for " << file.filename << " : " << std::hex << file.pathCheck << std::dec << std::endl; // Filepath checksum write32(oFile, file.pathCheck); write32(oFile, nextPathOffset); nextPathOffset += file.filename.size() + 1; write32(oFile, tmpChecksum); // File checksum bool isXast = extension(file.filename) == ".xai"; // std::cout << extension(file.filename) << " : " << isXast << std::endl; write32(oFile, isXast); // boolean : is it another XAST .xai file ? write64(oFile, file.size); write64(oFile, 0); // Padding uint64_t aSize = ALIGN_16(file.size); // if ( ++i >= files.size() ) // aSize = file.size; write64(oFile, nextFileOffset); write64(oFile, aSize); // Aligned file size nextFileOffset += aSize; } // Write unused entry slots for ( uint32_t i = 0; i < nbUnused; i++ ) { write32(oFile, -1); write32(oFile, 0); write32(oFile, -1); write32(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); } for ( FileData file : files ) { oFile.write( file.filename.c_str(), file.filename.size() + 1 ); } uint8_t *buf = new uint8_t[RBUF_SIZE]; if ( oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } if ( oFile.tellp() != dataOffset ) { std::cout << "Error while writing header" << std::endl; return -2; } uint32_t n = 0; for ( FileData& file : files ) { std::ifstream input( file.fullpath.c_str(), std::ios_base::binary ); if ( !input.is_open() ) continue; std::cout << "Writing " << file.filename << std::endl; uint32_t last = 0; uint64_t read = 0; uint64_t totalRead = 0; while ( input && oFile ) { input.read( (char*)buf, RBUF_SIZE ); if ( input ) read = RBUF_SIZE; else read = input.gcount(); last = checksum( (const char*)buf, read, last ); oFile.write( (const char*)buf, read ); totalRead += read; } input.close(); if ( totalRead != file.size ) { std::cout << "Bad file size" << std::endl; return -3; } file.contentCheck = last; // Align for next file data if needed if ( ++n < files.size() && oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } } fileSize = oFile.tellp(); oFile.seekp(0x20); write64(oFile, fileSize); i = 0; for ( FileData& file : files ) { oFile.seekp((0x30 * ++i) + 8); // write32(oFile, file.pathCheck); // write32(oFile, file.pathOffset); write32(oFile, file.contentCheck); // File checksum } oFile.seekp(0x30); uint32_t headerSize = 0x30 * maxEntries; if ( RBUF_SIZE < headerSize ) { delete buf; buf = new uint8_t[ headerSize ]; } oFile.read( (char*)buf, headerSize ); uint32_t headerCheck = checksum( (const char*)buf, headerSize); oFile.seekp(0x18); write32(oFile, headerCheck); oFile.close(); std::cout << std::endl << n << " files were included" << std::endl; std::cout << "XAST archive successfully created" << std::endl; return 0; } <commit_msg>Added header order mimic option<commit_after>// XAST Packer by yosh778 #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <unordered_map> #include <cinttypes> #include <boost/filesystem.hpp> #define ALIGN_16(n) ((n / 0x10 + (n % 0x10 ? 1 : 0)) * 0x10) #define RBUF_SIZE 0x1000000 using namespace boost::filesystem; void write32(std::fstream& output, uint32_t data) { output.write((char*)&data, (int)sizeof(data)); } uint64_t write64(std::fstream& output, uint64_t data) { output.write((char*)&data, (int)sizeof(data)); } uint32_t read32(std::ifstream& input) { uint32_t data; input.read((char*)&data, (int)sizeof(data)); return data; } uint64_t read64(std::ifstream& input) { uint64_t data; input.read((char*)&data, (int)sizeof(data)); return data; } // Checksum reverse by weaknespase uint32_t checksum(const char* in, const size_t length, int last = 0){ const char* end = in + length; int acc = last; while (in < end) acc = (acc * 33) ^ (unsigned char) *in++; return acc; } typedef struct FileData_ { std::string fullpath; std::string filename; uint32_t pathOffset; uint32_t pathCheck; uint32_t contentCheck; uint64_t offset; uint64_t size; } FileData; std::vector<char*> headerOrder; bool alphaSorter(const FileData& a, const FileData& b) { return a.filename < b.filename; } uint32_t getHeaderOrder(std::vector<char*>& order, std::string input); int main(int argc, char *argv[]) { if ( argc < 3 ) { std::cout << "Usage : " << argv[0] << " <dataPath> <output>" << std::endl; return -1; } std::string inPath = argv[1]; std::string output = argv[2]; uint32_t mimicUnused = 0; // Check input path existence if ( !exists( inPath ) ) { std::cout << "ERROR : Input directory " << inPath << " does not exist" << std::endl; return EXIT_FAILURE; } if ( argc > 3 ) { mimicUnused = getHeaderOrder( headerOrder, argv[3] ); } std::vector<FileData> files; recursive_directory_iterator it( inPath ), end; FileData fileData; uint32_t pathsCount = 0; std::unordered_map<std::string, int> headerMap; uint32_t i = 0; // Compress input directory recursively for ( ; it != end; ++it ) { bool is_dir = is_directory( *it ); std::string fullpath = it->path().string(); std::string filename = fullpath.substr( inPath.size() ); if ( filename.front() == '/' ) { filename.erase(0, 1); } // Skip any non-existing file if ( !exists( fullpath ) ) continue; if ( !is_dir ) { pathsCount += filename.size() + 1; fileData.filename = filename; fileData.fullpath = fullpath; fileData.pathCheck = checksum( filename.c_str(), filename.size() ); // std::cout << "Checksum for " << filename << " : " << std::hex << fileData.pathCheck << std::dec << std::endl; fileData.size = file_size( fullpath ); files.push_back( fileData ); } } std::sort (files.begin(), files.end(), alphaSorter); uint32_t nbEntries = files.size(); std::fstream oFile( output.c_str(), std::ios_base::trunc | std::ios_base::in | std::ios_base::out | std::ios_base::binary ); if ( !oFile.is_open() ) { std::cout << "Failed to open output file '" << output << "'" << std::endl; return -2; } uint32_t nbUnused = 0; uint32_t maxEntries = nbEntries + nbUnused + mimicUnused; uint32_t alignedPathsCount = ALIGN_16(pathsCount); uint32_t data; uint64_t pathsOffset = 0x30 * (1 + maxEntries); uint32_t dataOffset = pathsOffset + alignedPathsCount; // XAST header write32(oFile, 0x54534158); write32(oFile, 0x01010000); // Version : 1.01 write32(oFile, nbEntries); write32(oFile, maxEntries); write32(oFile, pathsCount); write32(oFile, dataOffset); uint32_t unk0 = 0xA02A4B6A; // File checksum ? write32(oFile, unk0); uint32_t headersCount = pathsOffset - 0x30; write32(oFile, headersCount); uint64_t fileSize = -1; write64(oFile, fileSize); write64(oFile, 0); uint64_t nextPathOffset = pathsOffset; uint64_t nextFileOffset = dataOffset; uint32_t unk1 = 0x8113D6D3; uint32_t tmpChecksum = 0xC75EB5E1; i = 0; if ( argc == 3 ) for ( FileData& file : files ) { std::cout << "Checksum for " << file.filename << " : " << std::hex << file.pathCheck << std::dec << std::endl; // Filepath checksum write32(oFile, file.pathCheck); write32(oFile, nextPathOffset); nextPathOffset += file.filename.size() + 1; write32(oFile, tmpChecksum); // File checksum bool isXast = extension(file.filename) == ".xai"; // std::cout << extension(file.filename) << " : " << isXast << std::endl; write32(oFile, isXast); // boolean : is it another XAST .xai file ? write64(oFile, file.size); write64(oFile, 0); // Padding uint64_t aSize = ALIGN_16(file.size); // if ( ++i >= files.size() ) // aSize = file.size; write64(oFile, nextFileOffset); write64(oFile, aSize); // Aligned file size nextFileOffset += aSize; } else for ( char *filePath : headerOrder ) { write32(oFile, -1); write32(oFile, 0); write32(oFile, -1); write32(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); } // Write additional unused entry slots for ( uint32_t i = 0; i < nbUnused; i++ ) { write32(oFile, -1); write32(oFile, 0); write32(oFile, -1); write32(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); write64(oFile, 0); } for ( FileData file : files ) { oFile.write( file.filename.c_str(), file.filename.size() + 1 ); } uint8_t *buf = new uint8_t[RBUF_SIZE]; if ( oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } if ( oFile.tellp() != dataOffset ) { std::cout << "Error while writing header : " << std::hex << oFile.tellp() << " != " << dataOffset << std::dec << std::endl; return -2; } uint32_t n = 0; i = 0; for ( FileData& file : files ) { std::ifstream input( file.fullpath.c_str(), std::ios_base::binary ); if ( !input.is_open() ) continue; file.pathOffset = nextPathOffset; nextPathOffset += file.filename.size() + 1; headerMap[ file.filename ] = i++; uint64_t aSize = ALIGN_16(file.size); file.offset = nextFileOffset; nextFileOffset += aSize; std::cout << "Writing " << file.filename << std::endl; uint32_t last = 0; uint64_t read = 0; uint64_t totalRead = 0; while ( input && oFile ) { input.read( (char*)buf, RBUF_SIZE ); if ( input ) read = RBUF_SIZE; else read = input.gcount(); last = checksum( (const char*)buf, read, last ); oFile.write( (const char*)buf, read ); totalRead += read; } input.close(); if ( totalRead != file.size ) { std::cout << "Bad file size" << std::endl; return -3; } file.contentCheck = last; // Align for next file data if needed if ( ++n < files.size() && oFile.tellp() % 0x10 ) { memset( buf, 0, 0x10 ); oFile.write( (char*)buf, 0x10 - (oFile.tellp() % 0x10) ); } } fileSize = oFile.tellp(); oFile.seekp(0x20); write64(oFile, fileSize); i = 0; uint32_t j = 0; if ( argc == 3 ) for ( FileData& file : files ) { oFile.seekp((0x30 * ++i) + 8); // write32(oFile, file.pathCheck); // write32(oFile, file.pathOffset); write32(oFile, file.contentCheck); // File checksum } else for ( char *filePath : headerOrder ) { std::string hpath; oFile.seekp(0x30 * (i+1)); if ( filePath && filePath != (char*)-1 ) { hpath = std::string(filePath); FileData& file = files[ headerMap[ hpath ] ]; std::cout << "Writing checksum for " << file.filename << std::endl; write32(oFile, file.pathCheck); write32(oFile, file.pathOffset); write32(oFile, file.contentCheck); // File checksum bool isXast = extension(file.filename) == ".xai"; // std::cout << extension(file.filename) << " : " << isXast << std::endl; write32(oFile, isXast); // boolean : is it another XAST .xai file ? write64(oFile, file.size); write64(oFile, 0); // Padding write64(oFile, file.offset); uint32_t aSize = ALIGN_16(file.size); if ( (file.offset + file.size) >= fileSize ) { aSize = file.size; } write64(oFile, aSize); // Aligned file size j++; // if ( j > pFiles.size() ) // return -1; } i++; } oFile.seekp(0x30); uint32_t headerSize = 0x30 * maxEntries; if ( RBUF_SIZE < headerSize ) { delete buf; buf = new uint8_t[ headerSize ]; } oFile.read( (char*)buf, headerSize ); uint32_t headerCheck = checksum( (const char*)buf, headerSize); oFile.seekp(0x18); write32(oFile, headerCheck); oFile.close(); std::cout << std::endl << n << " files were included" << std::endl; std::cout << "XAST archive successfully created" << std::endl; return 0; } uint32_t getHeaderOrder(std::vector<char*>& order, std::string input) { std::ifstream file( input.c_str(), std::ios_base::binary ); if ( !file.is_open() ) return -2; uint32_t data; // XAST header uint32_t magic = read32(file); // Version : 1.01 uint32_t version = read32(file); uint32_t nbEntries = read32(file); // nbEntries uint32_t maxEntries = read32(file); // maxEntries uint32_t pathsCount = read32(file); uint32_t dataOffset = read32(file); uint32_t unk0 = read32(file); uint32_t headersCount = read32(file); uint32_t fileSize = read32(file); uint32_t pathsOffset = 0x30 + headersCount; uint64_t *fileSizes = new uint64_t[maxEntries]; uint64_t *fileOffsets = new uint64_t[maxEntries]; uint32_t *pathOffsets = new uint32_t[maxEntries]; uint32_t *unk1 = new uint32_t[maxEntries]; uint32_t *fileChecksums = new uint32_t[maxEntries]; uint32_t nbActualEntries = 0; uint32_t i = 0; file.seekg(pathsOffset); char *pathsData = new char[pathsCount]; file.read(pathsData, pathsCount); file.seekg(0x30); uint32_t nbUnused = 0; for (i = 0; i < maxEntries; i++) { unk1[i] = read32(file); pathOffsets[i] = read32(file); fileChecksums[i] = read32(file); uint32_t isXai = read32(file); if ( pathOffsets[i] && pathOffsets[i] != -1 ) { order.push_back( pathsData + (pathOffsets[i] - pathsOffset) ); // std::cout << "Detected " << ( pathsData + (pathOffsets[i] - pathsOffset) ) << file.filename << std::endl; } else { order.push_back( (char*)-1 ); nbUnused++; } fileSizes[i] = read64(file); uint64_t padding = read64(file); fileOffsets[i] = read64(file); uint64_t aSize = read64(file); if ( file.tellg() >= pathsOffset ) { // std::cout << "break!" << std::endl; // std::cout << std::hex << file.tellg() << std::endl; break; } } delete fileSizes; delete fileOffsets; delete pathOffsets; delete unk1; delete fileChecksums; return nbUnused; } <|endoftext|>
<commit_before>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphOutlet.h" #include "TTCallback.h" #include "TTGraphDestination.h" #include "TTGraphObject.h" // C Callback from any Graph Destination objects we are observing void TTGraphDestinationObserverCallback(TTGraphDestinationPtr self, TTValue& arg) { // at the moment we only receive one callback, which is for the object being deleted self->mDestinationObject = NULL; self->mInletNumber = 0; self->mOwner->drop(*self); } // Implementation for Graph Destination class TTGraphDestination::TTGraphDestination() : mDestinationObject(NULL), mInletNumber(0), mCallbackHandler(NULL), mOwner(NULL) { create(); } TTGraphDestination::~TTGraphDestination() { if (mDestinationObject) mDestinationObject->unregisterObserverForNotifications(*mCallbackHandler); TTObjectRelease(&mCallbackHandler); mDestinationObject = NULL; mInletNumber = 0; mCallbackHandler = NULL; } void TTGraphDestination::create() { TTObjectInstantiate(TT("callback"), &mCallbackHandler, kTTValNONE); mCallbackHandler->setAttributeValue(TT("function"), TTPtr(&TTGraphDestinationObserverCallback)); mCallbackHandler->setAttributeValue(TT("baton"), TTPtr(this)); } void TTGraphDestination::connect(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber) { mDestinationObject = anObject; mInletNumber = fromOutletNumber; // dynamically add a message to the callback object so that it can handle the 'objectFreeing' notification mCallbackHandler->registerMessage(TT("objectFreeing"), (TTMethod)&TTCallback::notify, kTTMessagePassValue); // tell the source that is passed in that we want to watch it mDestinationObject->registerObserverForNotifications(*mCallbackHandler); } /*************************************************************/ TTErr TTGraphDestination::push(const TTDictionary& aDictionary) { // TODO: We need to append the inlet number into the dictionary before sending it return mDestinationObject->push(aDictionary); } <commit_msg>TTGraphDestination: adding owner to callback handler to help with debugging<commit_after>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphOutlet.h" #include "TTCallback.h" #include "TTGraphDestination.h" #include "TTGraphObject.h" // C Callback from any Graph Destination objects we are observing void TTGraphDestinationObserverCallback(TTGraphDestinationPtr self, TTValue& arg) { // at the moment we only receive one callback, which is for the object being deleted self->mDestinationObject = NULL; self->mInletNumber = 0; self->mOwner->drop(*self); } // Implementation for Graph Destination class TTGraphDestination::TTGraphDestination() : mDestinationObject(NULL), mInletNumber(0), mCallbackHandler(NULL), mOwner(NULL) { create(); } TTGraphDestination::~TTGraphDestination() { if (mDestinationObject) mDestinationObject->unregisterObserverForNotifications(*mCallbackHandler); TTObjectRelease(&mCallbackHandler); mDestinationObject = NULL; mInletNumber = 0; mCallbackHandler = NULL; } void TTGraphDestination::create() { TTObjectInstantiate(TT("callback"), &mCallbackHandler, kTTValNONE); mCallbackHandler->setAttributeValue(TT("owner"), TT("TTGraphDestination")); mCallbackHandler->setAttributeValue(TT("function"), TTPtr(&TTGraphDestinationObserverCallback)); mCallbackHandler->setAttributeValue(TT("baton"), TTPtr(this)); } void TTGraphDestination::connect(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber) { mDestinationObject = anObject; mInletNumber = fromOutletNumber; // dynamically add a message to the callback object so that it can handle the 'objectFreeing' notification mCallbackHandler->registerMessage(TT("objectFreeing"), (TTMethod)&TTCallback::notify, kTTMessagePassValue); // tell the source that is passed in that we want to watch it mDestinationObject->registerObserverForNotifications(*mCallbackHandler); } /*************************************************************/ TTErr TTGraphDestination::push(const TTDictionary& aDictionary) { // TODO: We need to append the inlet number into the dictionary before sending it return mDestinationObject->push(aDictionary); } <|endoftext|>
<commit_before> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/memory_stream.hpp> #include <quanta/core/object/object.hpp> #include <togo/support/test.hpp> #include <cmath> using namespace quanta; #define TSN(d) {true, d, {}}, #define TSE(d, e) {true, d, e}, #define TF(d) {false, d, {}}, struct Test { bool success; StringRef data; StringRef expected_output; } const tests[]{ // whitespace TSN("") TSN(" ") TSN("\n") TSN(" \t\n") // comments TF("/") TF("/*") TSN("//") TSN("/**/") TSN("/*\nblah\n*/") // constants TSE("null", "null") TSE("false", "false") TSE("true", "true") // identifiers TSE("a", "a") TSE("á", "á") TSE(".á", ".á") TSE("_", "_") TSE("a\nb", "a\nb") // markers TSE("~", "~") TSE("~x", "~x") TSE("~~x", "~~x") TSE("~~~x", "~~~x") TSE("^", "^") TSE("^x", "^x") TSE("^^x", "^^x") TSE("^^^x", "^^^x") TSE("G~~x", "G~~x") TSE(" G~x", "G~x") TSE("G~^x", "G~^x") TSE("?", "?") TSE("?~x", "?~x") TSE(" ?x", "?x") TSE("?^x", "?^x") // source TSE("x$0", "x") TSE("x$0$0", "x") TSE("x$0$1", "x") TSE("x$0$?", "x") TSE("x$1", "x$1") TSE("x$1$0", "x$1") TSE("x$1$?", "x$1$?") TSE("x$1$2", "x$1$2") TSE("x$?1", "x$?1") TSE("x$?1$0", "x$?1") TSE("x$?1$?", "x$?1$?") TSE("x$?1$2", "x$?1$2") TSE("x$?$?", "x$?$?") // numerics TSE(" 1", "1") TSE("+1", "1") TSE("-1", "-1") // . is actually a valid identifier lead here, so this is not true // TSE(" .1", "0.1") TSE("+.1", "0.1") TSE("-.1", "-0.1") TSE(" 1.1", "1.1") TSE("+1.1", "1.1") TSE("-1.1", "-1.1") TSE(" 1.1e1", "11") TSE("+1.1e1", "11") TSE("-1.1e1", "-11") TSE(" 1.1e+1", "11") TSE("+1.1e+1", "11") TSE("-1.1e+1", "-11") TSE(" 1.1e-1", "0.11") TSE("+1.1e-1", "0.11") TSE("-1.1e-1", "-0.11") // units TSE("1a", "1a") TSE("1µg", "1µg") // strings TSE("\"\"", "\"\"") TSE("\"a\"", "a") TSE("``````", "\"\"") TSE("```a```", "a") TSE("\"\\t\"", "\"\t\"") TSE("\"\\n\"", "```\n```") // names TF("=") TF("a=") TF("=,") TF("=;") TF("=\n") TSE("a=1", "a = 1") TSE("a=b", "a = b") TSE("a = 1", "a = 1") TSE("a = b", "a = b") TSE("a=\"\"", "a = \"\"") TSE("a=\"ab\"", "a = ab") TSE("a=\"a b\"", "a = \"a b\"") TF("a=\"\n") TSE("a=```ab```", "a = ab") TSE("a=```a b```", "a = \"a b\"") TSE("a=```a\nb```", "a = ```a\nb```") // tags TF(":") TF("::") TF(":,") TF(":;") TF(":\n") TF(":\"a\"") TF(":```a```") TF(":1") TF(":x=") TF("x=:") TF(":x:") TSE(":x", ":x") TSE("x:y", "x:y") TSE(":x:y", ":x:y") TSE(":?x", ":?x") TSE(":G~x", ":G~x") TSE(":~x", ":~x") TSE(":~~x", ":~~x") TSE(":~~~x", ":~~~x") TSE(":^x", ":^x") TSE(":^^x", ":^^x") TSE(":^^^x", ":^^^x") TSE(":?~x", ":?~x") TSE(":?~~x", ":?~~x") TSE(":?~~~x", ":?~~~x") TSE(":?^x", ":?^x") TSE(":?^^x", ":?^^x") TSE(":?^^^x", ":?^^^x") TSE(":G~~x", ":G~~x") TSE(":G~~~x", ":G~~~x") TSE(":G~~~~x", ":G~~~~x") TSE(":G~^x", ":G~^x") TSE(":G~^^x", ":G~^^x") TSE(":G~^^^x", ":G~^^^x") TF(":x(") TSE(":x()", ":x") TSE(":x( )", ":x") TSE(":x(\t)", ":x") TSE(":x(\n)", ":x") TSE(":x(1)", ":x(1)") TSE(":x(y)", ":x(y)") TSE(":x(y,z)", ":x(y, z)") TSE(":x(y;z)", ":x(y, z)") TSE(":x(y\nz)", ":x(y, z)") // scopes TF("{") TF("(") TF("[") TSE("{}", "null") TSE("{{}}", "{\n\tnull\n}") TSE("x{}", "x") TSE("x[]", "x") TSE("x[1]", "x[1]") TSE("x[y]", "x[y]") }; void check(Test const& test) { TOGO_LOGF( "reading (%3u): <%.*s>\n", test.data.size, test.data.size, test.data.data ); Object root; MemoryReader in_stream{test.data}; ObjectParserInfo pinfo; if (object::read_text(root, in_stream, pinfo)) { MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1}; TOGO_ASSERTE(object::write_text(root, out_stream)); StringRef output{ reinterpret_cast<char*>(array::begin(out_stream.data())), static_cast<unsigned>(out_stream.size()) }; // Remove trailing newline if (output.size > 0) { --output.size; } TOGO_LOGF( "rewritten (%3u): <%.*s>\n", output.size, output.size, output.data ); TOGO_ASSERT(test.success, "read succeeded when it should have failed"); TOGO_ASSERT( string::compare_equal(test.expected_output, output), "output does not match" ); } else { TOGO_LOGF( "failed to read%s: [%2u,%2u]: %s\n", test.success ? " (UNEXPECTED)" : "", pinfo.line, pinfo.column, pinfo.message ); TOGO_ASSERT(!test.success, "read failed when it should have succeeded"); } TOGO_LOG("\n"); } signed main() { memory_init(); for (auto& test : tests) { check(test); } return 0; } <commit_msg>lib/core/test/object/io_text: tidy.<commit_after> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/memory_stream.hpp> #include <quanta/core/object/object.hpp> #include <togo/support/test.hpp> #include <cmath> using namespace quanta; #define TSN(d) {true, d, {}}, #define TSE(d, e) {true, d, e}, #define TF(d) {false, d, {}}, struct Test { bool success; StringRef data; StringRef expected_output; } const tests[]{ // whitespace TSN("") TSN(" ") TSN("\n") TSN(" \t\n") // comments TF("/") TF("/*") TSN("//") TSN("/**/") TSN("/*\nblah\n*/") // constants TSE("null", "null") TSE("false", "false") TSE("true", "true") // identifiers TSE("a", "a") TSE("á", "á") TSE(".á", ".á") TSE("_", "_") TSE("a\nb", "a\nb") // markers TSE("~", "~") TSE("~x", "~x") TSE("~~x", "~~x") TSE("~~~x", "~~~x") TSE("^", "^") TSE("^x", "^x") TSE("^^x", "^^x") TSE("^^^x", "^^^x") TSE("G~~x", "G~~x") TSE(" G~x", "G~x") TSE("G~^x", "G~^x") TSE("?", "?") TSE("?~x", "?~x") TSE(" ?x", "?x") TSE("?^x", "?^x") // source TSE("x$0", "x") TSE("x$0$0", "x") TSE("x$0$1", "x") TSE("x$0$?", "x") TSE("x$1", "x$1") TSE("x$1$0", "x$1") TSE("x$1$?", "x$1$?") TSE("x$1$2", "x$1$2") TSE("x$?1", "x$?1") TSE("x$?1$0", "x$?1") TSE("x$?1$?", "x$?1$?") TSE("x$?1$2", "x$?1$2") TSE("x$?$?", "x$?$?") // numerics TSE(" 1", "1") TSE("+1", "1") TSE("-1", "-1") // . is actually a valid identifier lead here, so this is not true // TSE(" .1", "0.1") TSE("+.1", "0.1") TSE("-.1", "-0.1") TSE(" 1.1", "1.1") TSE("+1.1", "1.1") TSE("-1.1", "-1.1") TSE(" 1.1e1", "11") TSE("+1.1e1", "11") TSE("-1.1e1", "-11") TSE(" 1.1e+1", "11") TSE("+1.1e+1", "11") TSE("-1.1e+1", "-11") TSE(" 1.1e-1", "0.11") TSE("+1.1e-1", "0.11") TSE("-1.1e-1", "-0.11") // units TSE("1a", "1a") TSE("1µg", "1µg") // strings TSE("\"\"", "\"\"") TSE("\"a\"", "a") TSE("``````", "\"\"") TSE("```a```", "a") TSE("\"\\t\"", "\"\t\"") TSE("\"\\n\"", "```\n```") // names TF("=") TF("a=") TF("=,") TF("=;") TF("=\n") TSE("a=1", "a = 1") TSE("a=b", "a = b") TSE("a = 1", "a = 1") TSE("a = b", "a = b") TSE("a=\"\"", "a = \"\"") TSE("a=\"ab\"", "a = ab") TSE("a=\"a b\"", "a = \"a b\"") TF("a=\"\n") TSE("a=```ab```", "a = ab") TSE("a=```a b```", "a = \"a b\"") TSE("a=```a\nb```", "a = ```a\nb```") // tags TF(":") TF("::") TF(":,") TF(":;") TF(":\n") TF(":\"a\"") TF(":```a```") TF(":1") TSE(":x", ":x") TF(":x:") TF(":x=") TF("x=:") TSE("x:y", "x:y") TSE(":x:y", ":x:y") TSE(":?x", ":?x") TSE(":G~x", ":G~x") TSE(":~x", ":~x") TSE(":~~x", ":~~x") TSE(":~~~x", ":~~~x") TSE(":^x", ":^x") TSE(":^^x", ":^^x") TSE(":^^^x", ":^^^x") TSE(":?~x", ":?~x") TSE(":?~~x", ":?~~x") TSE(":?~~~x", ":?~~~x") TSE(":?^x", ":?^x") TSE(":?^^x", ":?^^x") TSE(":?^^^x", ":?^^^x") TSE(":G~~x", ":G~~x") TSE(":G~~~x", ":G~~~x") TSE(":G~~~~x", ":G~~~~x") TSE(":G~^x", ":G~^x") TSE(":G~^^x", ":G~^^x") TSE(":G~^^^x", ":G~^^^x") TF(":x(") TSE(":x()", ":x") TSE(":x( )", ":x") TSE(":x(\t)", ":x") TSE(":x(\n)", ":x") TSE(":x(1)", ":x(1)") TSE(":x(y)", ":x(y)") TSE(":x(y,z)", ":x(y, z)") TSE(":x(y;z)", ":x(y, z)") TSE(":x(y\nz)", ":x(y, z)") // scopes TF("{") TF("(") TF("[") TSE("{}", "null") TSE("{{}}", "{\n\tnull\n}") TSE("x{}", "x") TSE("x[]", "x") TSE("x[1]", "x[1]") TSE("x[y]", "x[y]") }; void check(Test const& test) { TOGO_LOGF( "reading (%3u): <%.*s>\n", test.data.size, test.data.size, test.data.data ); Object root; MemoryReader in_stream{test.data}; ObjectParserInfo pinfo; if (object::read_text(root, in_stream, pinfo)) { MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1}; TOGO_ASSERTE(object::write_text(root, out_stream)); StringRef output{ reinterpret_cast<char*>(array::begin(out_stream.data())), static_cast<unsigned>(out_stream.size()) }; // Remove trailing newline if (output.size > 0) { --output.size; } TOGO_LOGF( "rewritten (%3u): <%.*s>\n", output.size, output.size, output.data ); TOGO_ASSERT(test.success, "read succeeded when it should have failed"); TOGO_ASSERT( string::compare_equal(test.expected_output, output), "output does not match" ); } else { TOGO_LOGF( "failed to read%s: [%2u,%2u]: %s\n", test.success ? " (UNEXPECTED)" : "", pinfo.line, pinfo.column, pinfo.message ); TOGO_ASSERT(!test.success, "read failed when it should have succeeded"); } TOGO_LOG("\n"); } signed main() { memory_init(); for (auto& test : tests) { check(test); } return 0; } <|endoftext|>
<commit_before>/* Copyright 2015 Stanford University, NVIDIA Corporation * * 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. */ // clocks, timers for Realm // nop, but helps IDEs #include "timers.h" #include "logging.h" #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #else #include <time.h> #endif namespace Realm { //////////////////////////////////////////////////////////////////////// // // class Clock inline /*static*/ double Clock::current_time(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif double t = ts.tv_sec + (1e-9 * ts.tv_nsec); if(!absolute) t -= 1e-9 * zero_time; return t; } inline /*static*/ long long Clock::current_time_in_microseconds(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif long long t = (1000000LL * ts.tv_sec) + (ts.tv_nsec / 1000); if(!absolute) t -= zero_time / 1000; return t; } inline /*static*/ long long Clock::current_time_in_nanoseconds(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif long long t = (1000000000LL * ts.tv_sec) + ts.tv_nsec; if(!absolute) t -= zero_time; return t; } inline /*static*/ long long Clock::get_zero_time(void) { return zero_time; } inline /*static*/ void Clock::set_zero_time(void) { // this looks weird, but we can't use the absolute time because it uses // a different system clock in POSIX-land, so we ask for the current // relative time (based on whatever zero_time currently is) and add // that in zero_time += current_time_in_nanoseconds(false); } //////////////////////////////////////////////////////////////////////// // // class Clock inline TimeStamp::TimeStamp(const char *_message, bool _difference, Logger *_logger /*= 0*/) : message(_message), difference(_difference), logger(_logger) { start_time = Clock::current_time(); if(!difference) { if(logger) logger->info("%s %7.6f", message, start_time); else printf("%s %7.6f\n", message, start_time); } } inline TimeStamp::~TimeStamp(void) { if(difference) { double interval = Clock::current_time() - start_time; if(logger) logger->info("%s %7.6f", message, interval); else printf("%s %7.6f\n", message, interval); } } }; // namespace Realm <commit_msg>timers: change logger-based timestamps to print instead of info<commit_after>/* Copyright 2015 Stanford University, NVIDIA Corporation * * 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. */ // clocks, timers for Realm // nop, but helps IDEs #include "timers.h" #include "logging.h" #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #else #include <time.h> #endif namespace Realm { //////////////////////////////////////////////////////////////////////// // // class Clock inline /*static*/ double Clock::current_time(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif double t = ts.tv_sec + (1e-9 * ts.tv_nsec); if(!absolute) t -= 1e-9 * zero_time; return t; } inline /*static*/ long long Clock::current_time_in_microseconds(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif long long t = (1000000LL * ts.tv_sec) + (ts.tv_nsec / 1000); if(!absolute) t -= zero_time / 1000; return t; } inline /*static*/ long long Clock::current_time_in_nanoseconds(bool absolute /*= false*/) { #ifdef __MACH__ mach_timespec_t ts; clock_serv_t cclock; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); #else struct timespec ts; clock_gettime(absolute ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts); #endif long long t = (1000000000LL * ts.tv_sec) + ts.tv_nsec; if(!absolute) t -= zero_time; return t; } inline /*static*/ long long Clock::get_zero_time(void) { return zero_time; } inline /*static*/ void Clock::set_zero_time(void) { // this looks weird, but we can't use the absolute time because it uses // a different system clock in POSIX-land, so we ask for the current // relative time (based on whatever zero_time currently is) and add // that in zero_time += current_time_in_nanoseconds(false); } //////////////////////////////////////////////////////////////////////// // // class Clock inline TimeStamp::TimeStamp(const char *_message, bool _difference, Logger *_logger /*= 0*/) : message(_message), difference(_difference), logger(_logger) { start_time = Clock::current_time(); if(!difference) { if(logger) logger->print("%s %7.6f", message, start_time); else printf("%s %7.6f\n", message, start_time); } } inline TimeStamp::~TimeStamp(void) { if(difference) { double interval = Clock::current_time() - start_time; if(logger) logger->print("%s %7.6f", message, interval); else printf("%s %7.6f\n", message, interval); } } }; // namespace Realm <|endoftext|>