void AsyncCopy::Run(void* data) { START_KROLL_THREAD; Logger* logger = Logger::Get("Filesystem.AsyncCopy"); AsyncCopy* ac = static_cast<AsyncCopy*>(data); std::vector<std::string>::iterator iter = ac->files.begin(); Poco::Path to(ac->destination); Poco::File tof(to.toString()); logger->Debug("Job started: dest=%s, count=%i", ac->destination.c_str(), ac->files.size()); if (!tof.exists()) { tof.createDirectory(); } int c = 0; while (!ac->stopped && iter!=ac->files.end()) { bool err_copy = false; std::string file = (*iter++); c++; logger->Debug("File: path=%s, count=%i\n", file.c_str(), c); try { Poco::Path from(file); Poco::File f(file); if (f.isDirectory()) { ac->Copy(from,to); } else { Poco::Path dest(to,from.getFileName()); ac->Copy(from,dest); } logger->Debug("File copied"); KValueRef value = Value::NewString(file); ValueList args; args.push_back(value); args.push_back(Value::NewInt(c)); args.push_back(Value::NewInt(ac->files.size())); args.push_back(Value::NewBool(true)); RunOnMainThread(ac->callback, args, false); logger->Debug("Callback executed"); } catch (ValueException &ex) { err_copy = true; SharedString ss = ex.DisplayString(); logger->Error(std::string("Error: ") + *ss + " for file: " + file); } catch (Poco::Exception &ex) { err_copy = true; logger->Error(std::string("Error: ") + ex.displayText() + " for file: " + file); } catch (std::exception &ex) { err_copy = true; logger->Error(std::string("Error: ") + ex.what() + " for file: " + file); } catch (...) { err_copy = true; logger->Error(std::string("Unknown error during copy: ") + file); } try { if(err_copy) { KValueRef value = Value::NewString(file); ValueList args; args.push_back(value); args.push_back(Value::NewInt(c)); args.push_back(Value::NewInt(ac->files.size())); args.push_back(Value::NewBool(false)); RunOnMainThread(ac->callback, args, false); } } catch(...) { err_copy = true; logger->Error(std::string("Unknown error during copy: ") + file); } } ac->Set("running",Value::NewBool(false)); ac->stopped = true; logger->Debug(std::string("Job finished")); END_KROLL_THREAD; }
void set_log_level(int level){ logger.setLevel(level); }
int get_log_level(const char * levelname){ return logger.getLevel(levelname); }
int main(int argc, const char* argv[]) { const string error_abort_str("\nProgram aborted.\n\n"); const string parse_error_str("PARSE ERROR:\n"); const string processnetwork_error_str("INVALID MODEL ERROR:\n"); const string io_error_str("I/O ERROR:\n"); const string critical_error_str("CRITICAL PROGRAM ERROR:\n"); string header = string() + "f2cc - A CUDA C synthesizer for ForSyDe models\n\n"; cout << header; // Get configuration Config config; try { config.setFromCommandLine(argc, argv); } catch (InvalidFormatException& ex) { cout << ex.getMessage() << endl; return 0; } catch (Exception& ex) { cout << ex.toString() << endl; cout << error_abort_str << endl; return 0; } if (config.doPrintHelpMenu()) { cout << config.getHelpMenu() << endl; return 0; } if (config.doPrintVersion()) { cout << "Version: " << config.getVersion() << endl << "SVN revision: " << config.getSvnRevision() << endl; return 0; } // Prepare logger Logger logger; logger.setLogLevel(config.getLogLevel()); try { logger.open(config.getLogFile()); } catch (Exception& ex) { cout << ex.toString() << endl; cout << error_abort_str << endl; } logger.logDebugMessage("Logger open"); // Execute try { try { Frontend* parser; switch (config.getInputFormat()) { case Config::XML: { logger.logInfoMessage(string("New XML format assumed.") + " The execution will follow the path from v0.2..."); parser = new (std::nothrow) XmlParser(logger); break; } case Config::CUDA: { logger.logInfoMessage(string("Old GraphML format assumed.") + " The execution will follow the path from v0.1..."); parser = new (std::nothrow) GraphmlParser(logger); break; } } if (!parser) THROW_EXCEPTION(OutOfMemoryException); logger.logInfoMessage(string("MODEL INPUT FILE: ") + config.getInputFile()); logger.logInfoMessage("Parsing input file..."); ProcessNetwork* processnetwork = parser->parse(config.getInputFile()); delete parser; string processnetwork_info_message("MODEL INFO:\n"); processnetwork_info_message += getProcessNetworkInfo(processnetwork); logger.logInfoMessage(processnetwork_info_message); string target_platform_message("TARGET PLATFORM: "); switch (config.getTargetPlatform()) { case Config::C: { target_platform_message += "C"; break; } case Config::CUDA: { target_platform_message += "CUDA"; break; } } logger.logInfoMessage(target_platform_message); // Make processnetwork modifications, if necessary ModelModifier modifier(processnetwork, logger); logger.logInfoMessage("Removing redundant leafs..."); modifier.removeRedundantLeafs(); logger.logInfoMessage("Converting Comb leafs " "with one in port to Comb leafs..."); modifier.convertZipWith1ToMap(); if (config.getTargetPlatform() == Config::CUDA) { string leaf_coalescing_message("DATA PARALLEL PROCESS " "COALESCING: "); if (config.doDataParallelLeafCoalesing()) { leaf_coalescing_message += "YES"; } else { leaf_coalescing_message += "NO"; } logger.logInfoMessage(leaf_coalescing_message); if (config.doDataParallelLeafCoalesing()) { logger.logInfoMessage("" "Performing data parallel Comb leaf " "coalescing..."); modifier.coalesceDataParallelLeafs(); } logger.logInfoMessage( "Splitting data parallel segments..."); modifier.splitDataParallelSegments(); logger.logMessage(Logger::INFO, "Fusing chains of Unzipx-map-Zipx " "leafs..."); modifier.fuseUnzipMapZipLeafs(); if (config.doDataParallelLeafCoalesing()) { logger.logInfoMessage("" "Performing ParallelMap leaf " "coalescing..."); modifier.coalesceParallelMapSyLeafs(); } } processnetwork_info_message = "NEW MODEL INFO:\n"; processnetwork_info_message += getProcessNetworkInfo(processnetwork); logger.logInfoMessage(processnetwork_info_message); // Generate code and write to file Synthesizer synthesizer(processnetwork, logger, config); Synthesizer::CodeSet code; switch (config.getTargetPlatform()) { case Config::C: { code = synthesizer.generateCCode(); break; } case Config::CUDA: { code = synthesizer.generateCudaCCode(); break; } } logger.logInfoMessage("Writing code to output files..."); tools::writeFile(config.getHeaderOutputFile(), code.header); tools::writeFile(config.getImplementationOutputFile(), code.implementation); logger.logInfoMessage("MODEL SYNTHESIS COMPLETE"); // Clean up delete processnetwork; logger.logDebugMessage("Closing logger..."); logger.close(); } catch (FileNotFoundException& ex) { logger.logErrorMessage(ex.getMessage()); } catch (ParseException& ex) { logger.logErrorMessage(parse_error_str + ex.getMessage()); } catch (InvalidModelException& ex) { logger.logErrorMessage(processnetwork_error_str + ex.getMessage()); } catch (IOException& ex) { logger.logErrorMessage(io_error_str + ex.getMessage()); } catch (Exception& ex) { logger.logCriticalMessage(critical_error_str + ex.toString() + error_abort_str); } } catch (Exception&) { // Ignore } return 0; }
int main (int argc, char *argv[]) { BasicConfigurator config; config.configure(); int loglevel = 0; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "show help message") ("version,V", "show version (and exit)") ("daemon,d", "daemon mode, run in background") ("list,l", "list available CEC adapters and devices") ("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)") ("quiet,q", "quiet output (print almost nothing)") ("donotactivate,a", "do not activate device on startup") ("onstandby", value<string>()->value_name("<path>"), "command to run on standby") ("onactivate", value<string>()->value_name("<path>"), "command to run on activation") ("ondeactivate", value<string>()->value_name("<path>"), "command to run on deactivation") ("port,p", value<HDMI::address>()->value_name("<a[.b.c.d]>"), "HDMI port A or address A.B.C.D (overrides autodetected value)") ("usb", value<string>()->value_name("<path>"), "USB adapter path (as shown by --list)") ; po::positional_options_description p; p.add("usb", 1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); } catch( po::error &e ) { cerr << argv[0] << ": " << e.what() << endl; cerr << "Type \"" << argv[0] << " --help\" for more information." << endl; return 1; } po::notify(vm); if (vm.count("help")) { cout << "Usage: " << argv[0] << " [options] [usb]" << endl << endl; cout << desc << endl; return 0; } if (vm.count("version")) { cout << PACKAGE_STRING << endl; return 0; } if(vm.count("quiet")) { loglevel = -1; } else { loglevel = min(loglevel, 2); } Logger root = Logger::getRoot(); switch (loglevel) { case 2: root.setLogLevel(TRACE_LOG_LEVEL); break; case 1: root.setLogLevel(DEBUG_LOG_LEVEL); break; default: root.setLogLevel(INFO_LOG_LEVEL); break; case -1: root.setLogLevel(FATAL_LOG_LEVEL); break; } try { // Create the main Main & main = Main::instance(); string device = ""; if (vm.count("list")) { main.listDevices(); return 0; } if (vm.count("donotactivate")) { main.setMakeActive(false); } if (vm.count("usb")) { device = vm["usb"].as< string >(); } if (vm.count("onstandby")) { main.setOnStandbyCommand(vm["onstandby"].as< string >()); } if (vm.count("onactivate")) { main.setOnActivateCommand(vm["onactivate"].as< string >()); } if (vm.count("ondeactivate")) { main.setOnDeactivateCommand(vm["ondeactivate"].as< string >()); } if (vm.count("port")) { main.setTargetAddress(vm["port"].as< HDMI::address >()); } if (vm.count("daemon")) { if( daemon(0, 0) ) return -1; } main.loop(device); } catch (std::exception & e) { cerr << e.what() << endl; return -1; } return 0; }
bool UploadDump(const char* file, const char* user, int build, int branch, DelegateI<Prog_s>* progress) { Logger log; log.write("---------------------------------------\r\n"); time_t ltime; /* calendar time */ ltime=time(NULL); /* get current cal time */ #ifdef WIN32 char buff[255] = {0}; struct tm t; localtime_s(&t, <ime); asctime_s(buff, 255, &t); #else struct tm *t = localtime(<ime); char* buff = asctime(t); #endif log.write("%s\r\n", buff); log.write("---------------------------------------\r\n"); log.write("Uploaded crash dump: [%s]\r\n", file); gcString dump(file); if (PrepDumpForUpload(dump) == false) { log.write("Failed to prepare crash dump.\r\n"); return false; } else { log.write("Prepared crash dump to: [%s]\r\n", dump.c_str()); } std::string os = UTIL::OS::getOSString(); HttpHandle hh(DUMP_UPLOAD_URL); if (progress) hh->getProgressEvent() += progress; hh->setUserAgent(DUMP_UPLOAD_AGENT); hh->cleanUp(); hh->addPostText("os", os.c_str()); hh->addPostText("build", build); hh->addPostText("appid", branch); if (user) hh->addPostText("user", user); hh->addPostFile("crashfile", dump.c_str()); try { hh->postWeb(); } catch (gcException &except) { log.write("Failed to upload crash: %s [%d.%d].\r\n", except.getErrMsg(), except.getErrId(), except.getSecErrId()); return false; } TiXmlDocument doc; doc.LoadBuffer(const_cast<char*>(hh->getData()), hh->getDataSize()); try { XML::processStatus(doc, "crashupload"); log.write("Uploaded dump\r\n"); UTIL::FS::delFile(UTIL::FS::Path(dump, "", true)); } catch (gcException &) { log.write("Bad status returned from upload crash dump.\r\n"); gcString res; res.assign(hh->getData(), hh->getDataSize()); log.write("Result: \r\n\r\n%s\r\n\r\n", res.c_str()); return false; } return true; }
void XCSoarInterface::Shutdown(void) { CreateProgressDialog(gettext(TEXT("Shutdown, please wait..."))); StartHourglassCursor(); StartupStore(TEXT("Entering shutdown...\n")); StartupLogFreeRamAndStorage(); // turn off all displays globalRunningEvent.reset(); StartupStore(TEXT("dlgAirspaceWarningDeInit\n")); dlgAirspaceWarningDeInit(); CreateProgressDialog(gettext(TEXT("Shutdown, saving logs..."))); // stop logger logger.guiStopLogger(Basic(),true); CreateProgressDialog(gettext(TEXT("Shutdown, saving profile..."))); // Save settings Profile::StoreRegistry(); // Stop sound StartupStore(TEXT("SaveSoundSettings\n")); Profile::SaveSoundSettings(); #ifndef DISABLEAUDIOVARIO // VarioSound_EnableSound(false); // VarioSound_Close(); #endif // Stop drawing CreateProgressDialog(gettext(TEXT("Shutdown, please wait..."))); StartupStore(TEXT("CloseDrawingThread\n")); closeTriggerEvent.trigger(); calculation_thread->join(); StartupStore(TEXT("- calculation thread returned\n")); instrument_thread->join(); StartupStore(TEXT("- instrument thread returned\n")); draw_thread->join(); StartupStore(TEXT("- draw thread returned\n")); delete draw_thread; // Clear data CreateProgressDialog(gettext(TEXT("Shutdown, saving task..."))); StartupStore(TEXT("Resume abort task\n")); task.ResumeAbortTask(SettingsComputer(), -1); // turn off abort if it was on. StartupStore(TEXT("Save default task\n")); task.SaveDefaultTask(); StartupStore(TEXT("Clear task data\n")); task.ClearTask(); StartupStore(TEXT("Close airspace\n")); CloseAirspace(); StartupStore(TEXT("Close waypoints\n")); way_points.clear(); CreateProgressDialog(gettext(TEXT("Shutdown, please wait..."))); StartupStore(TEXT("CloseTerrainTopology\n")); RASP.Close(); terrain.CloseTerrain(); delete topology; delete marks; devShutdown(); SaveCalculationsPersist(Basic(),Calculated()); #if (EXPERIMENTAL > 0) // CalibrationSave(); #endif #if defined(GNAV) && !defined(PCGNAV) StartupStore(TEXT("Altair shutdown\n")); Sleep(2500); StopHourglassCursor(); InputEvents::eventDLLExecute(TEXT("altairplatform.dll SetShutdown 1")); while(1) { Sleep(100); // free time up for processor to perform shutdown } #endif CloseFLARMDetails(); // Kill windows StartupStore(TEXT("Destroy Info Boxes\n")); InfoBoxManager::Destroy(); StartupStore(TEXT("Destroy Button Labels\n")); ButtonLabel::Destroy(); StartupStore(TEXT("Delete Objects\n")); // Kill graphics objects DeleteFonts(); DeleteAirspace(); StartupStore(TEXT("Close Progress Dialog\n")); CloseProgressDialog(); CloseGeoid(); StartupStore(TEXT("Close Windows - main \n")); main_window.reset(); StartupStore(TEXT("Close Graphics\n")); MapGfx.Destroy(); #ifdef DEBUG_TRANSLATIONS StartupStore(TEXT("Writing missing translations\n")); WriteMissingTranslations(); #endif StartupLogFreeRamAndStorage(); StartupStore(TEXT("Finished shutdown\n")); StopHourglassCursor(); }
int log_level() { Logger* logger = get_or_create_global_logger(); return logger->get_level(); }
void set_log_level(int level) { Logger* logger = get_or_create_global_logger(); logger->set_level(level); }
int log_open(FILE *fp, int level) { Logger* logger = get_or_create_global_logger(); return logger->open(fp, level); }
int log_open(const char *filename, int level, uint64_t rotate_size) { Logger* logger = get_or_create_global_logger(); return logger->open(filename, level, rotate_size); }
INT_32 FN_CoNaN::Usage(Logger &logger) { logger.Emerg("Usage: CoNaN(N, LIST(\"язык\", \"языка\", \"языков\"), [concat_num = true]) or CoNaN(N, \"язык\", \"языка\", \"языков\", [concat_num = true])"); return -1; }
/** Implementation of M2 scenario */ int main(int argc, char *argv[]) { if (argc>=2) { // INI file is given as command line parameter configfilename = argv[1]; } // Setup config management configManager.init(configfilename); // Setup statistics output file Logger *logger = new FileLogger(configManager.logFileName.c_str()); logger->SetLogLevel(Logger::LOGLEVEL_INFO); Logger::getInstance()->Log(Logger::LOGLEVEL_VERBOSE,"M2Host","M2Host started\n"); cout << "Log is written to: " << configManager.logFileName << endl; // Write current time and date to log time_t t = time(0); // get time now struct tm * now = localtime( & t ); Logger::getInstance()->Log(Logger::LOGLEVEL_VERBOSE,"M2Host","Current time: %d-%d-%d, %d:%d:%d\n", (now->tm_year + 1900),(now->tm_mon + 1),now->tm_mday,now->tm_hour,now->tm_min,now->tm_sec ); Logger::getInstance()->Log(Logger::LOGLEVEL_VERBOSE,"M2Host","Configuration: %s\n",configfilename); Logger::getInstance()->Log(Logger::LOGLEVEL_VERBOSE,"M2Host","Local measurement log: %s\nRemote measurement log: %s\n", configManager.localMLogFilename.c_str(), configManager.remoteMLogFilename.c_str()); // Setup time management // Waiting a little to allow other processes to init... // Useful if started together with CamClient which needs to start its server. cout << "Waiting 3s..." << endl; #ifdef WIN32 Sleep(3000); #else #error TODO: Sleep not implemented for non-Win32. #endif const bool useLocalCamera=true; CameraProxy *camProxy = NULL; CameraRemoteProxy *camRemoteProxy = NULL; CameraLocalProxy *camLocalProxy = NULL; if (useLocalCamera) { camProxy = camLocalProxy = new CameraLocalProxy(VIDEOINPUTTYPE_PS3EYE,0); } else { camProxy = camRemoteProxy = new CameraRemoteProxy(); } // Prepare camera and detector objects //ChessboardDetector detector(Size(9,6),36.1); // Chessboard cell size is 36x36mm, using CameraProxy default camProxy->camera->cameraID=0; camProxy->camera->isStationary=false; camProxy->camera->loadCalibrationData(configManager.camIntrinsicParamsFileName.data()); if (camRemoteProxy) { cout << "Connecting..." << endl; camRemoteProxy->Connect(configManager.phoneIpAddress.c_str(),configManager.phonePort); } // --------------------------- Execute main task cout << "Main task started" << endl; // ---Currently, multiple possible measurements are supported. // - Original "capture 100 frames and report capture times" measurement //camRemoteProxy->PerformCaptureSpeedMeasurement_A(100,configManager.MLogFilename.c_str()); // - Reading TimeSyncBeacon measurement M2_TimeSyncTest(camProxy,10); cout << "Main task finished" << endl; // --------------------------- Closing... if (camRemoteProxy) { cout << "Disconnecting..." << endl; camRemoteProxy->Disconnect(); } delete camProxy; cout << "Done." << endl; }
bool Atlas::clearTexture( Logger & _logger, const MAGIC_CHANGE_ATLAS & c ) { uint32_t index = s_imageIndex( c ); TMapImages::iterator it_found = m_images.find( index ); if( it_found == m_images.end() ) { _logger.message("Atlas::clearTexture not found!" ); return false; } ImageDesc & desc = it_found->second; desc.texture->Release(); m_images.erase( it_found ); IDirect3DSurface9 * back = NULL; DXCALL m_pDevice->GetRenderTarget( 0, &back ); if( back == NULL ) { return false; } IDirect3DSurface9 * dest = NULL; m_pTexture->GetSurfaceLevel( 0, &dest ); if( dest == NULL ) { return false; } DXCALL m_pDevice->SetRenderTarget( 0, dest ); D3DSURFACE_DESC texDesc; DXCALL m_pTexture->GetLevelDesc( 0, &texDesc ); float cw = (float)c.width; float ch = (float)c.height; float tw = (float)texDesc.Width; float th = (float)texDesc.Height; float scale_x = tw / cw; float scale_y = th / ch; D3DRECT rect[1]; rect[0].x1 = (LONG)( (c.x * scale_x) + 0.5f ); rect[0].y1 = (LONG)((c.y * scale_y) + 0.5f); rect[0].x2 = (LONG)((c.x + c.width) * scale_x + 0.5f); rect[0].y2 = (LONG)((c.y + c.height) * scale_y + 0.5f); m_pDevice->Clear( 1, rect, D3DCLEAR_TARGET, 0x0, 0.f, 0 ); dest->Release(); m_pDevice->SetRenderTarget( 0, back ); back->Release(); return true; }
/** * Parses argument options and sets variables appropriately. * @param ac number of arguments. * @param pointer to array of arguments as character arrays. * @return True iff there was an error. */ bool parse_options(int ac, char ** av) { size_t additional_online = 0; size_t additional_batch = 0; po::options_description standard("Standard Options"); standard.add_options() ("help,h", "produce help message") ("output-dir,o", po::value<string>(&output_dir)->default_value(output_dir), "write all output files to this directory") #ifdef PROTO ("preprocess,D", "run preprocess script for eXpressD") #endif ("frag-len-mean,m", po::value<size_t>(&def_fl_mean)->default_value(def_fl_mean), "prior estimate for average fragment length") ("frag-len-stddev,s", po::value<size_t>(&def_fl_stddev)->default_value(def_fl_stddev), "prior estimate for fragment length std deviation") ("haplotype-file,H", po::value<string>(&haplotype_file_name)->default_value(haplotype_file_name), "path to a file containing haplotype pairs") ("additional-batch,B", po::value<size_t>(&additional_batch)->default_value(additional_batch), "number of additional batch EM rounds after initial online round") ("additional-online,O", po::value<size_t>(&additional_online)->default_value(additional_online), "number of additional online EM rounds after initial online round") ("max-read-len,L", po::value<size_t>(&max_read_len)->default_value(max_read_len), "maximum allowed length of a read") ("output-align-prob", "output alignments (sam/bam) with probabilistic assignments") ("output-align-samp", "output alignments (sam/bam) with sampled assignments") ("fr-stranded", "accept only forward->reverse alignments (second-stranded protocols)") ("rf-stranded", "accept only reverse->forward alignments (first-stranded protocols)") ("f-stranded", "accept only forward single-end alignments (second-stranded protocols)") ("r-stranded", "accept only reverse single-end alignments (first-stranded protocols)") ("no-update-check", "disables automatic check for update via web") ("logtostderr", "prints all logging messages to stderr") ; po::options_description advanced("Advanced Options"); advanced.add_options() ("forget-param,f", po::value<double>(&ff_param)->default_value(ff_param), "sets the 'forgetting factor' parameter (0.5 < c <= 1)") ("library-size", po::value<size_t>(&library_size), "specifies library size for FPKM instead of calculating from alignments") ("max-indel-size", po::value<size_t>(&max_indel_size)->default_value(max_indel_size), "sets the maximum allowed indel size, affecting geometric indel prior") ("calc-covar", "calculate and output covariance matrix") ("expr-alpha", po::value<double>(&expr_alpha)->default_value(expr_alpha), "sets the strength of the prior, per bp") ("stop-at", po::value<size_t>(&stop_at)->default_value(stop_at), "sets the number of fragments to process, disabled with 0") ("burn-out", po::value<size_t>(&burn_out)->default_value(burn_out), "sets number of fragments after which to stop updating auxiliary parameters") ("no-bias-correct", "disables bias correction") ("no-error-model", "disables error modelling") ("aux-param-file", po::value<string>(¶m_file_name)->default_value(param_file_name), "path to file containing auxiliary parameters to use instead of learning") ; string prior_file = ""; po::options_description hidden("Experimental/Debug Options"); hidden.add_options() ("num-threads,p", po::value<size_t>(&num_threads)->default_value(num_threads), "number of threads (>= 2)") ("edit-detect","") ("single-round", "") ("output-running-rounds", "") ("output-running-reads", "") ("batch-mode","") ("both","") ("prior-params", po::value<string>(&prior_file)->default_value(""), "") ("sam-file", po::value<string>(&in_map_file_names)->default_value(""), "") ("fasta-file", po::value<string>(&fasta_file_name)->default_value(""), "") ("num-neighbors", po::value<size_t>(&num_neighbors)->default_value(0), "") ("bias-model-order", po::value<size_t>(&bias_model_order)->default_value(bias_model_order), "sets the order of the Markov chain used to model sequence bias") ; po::positional_options_description positional; positional.add("fasta-file",1).add("sam-file",1); po::options_description cmdline_options; cmdline_options.add(standard).add(advanced).add(hidden); bool error = false; po::variables_map vm; try { po::store(po::command_line_parser(ac, av).options(cmdline_options) .positional(positional).run(), vm); } catch (po::error& e) { logger.info("Command-Line Argument Error: %s.", e.what()); error = true; } po::notify(vm); if (ff_param > 1.0 || ff_param < 0.5) { logger.info("Command-Line Argument Error: forget-param/f option must be " "between 0.5 and 1.0."); error= true; } if (fasta_file_name == "") { logger.info("Command-Line Argument Error: target sequence fasta file " "required."); error = true; } if (error || vm.count("help")) { cerr << "express v" << PACKAGE_VERSION << endl << "-----------------------------\n" << "File Usage: express [options] <target_seqs.fa> <hits.(sam/bam)>\n" << "Piped Usage: bowtie [options] -S <index> <reads.fq> | express " << "[options] <target_seqs.fa>\n\n" << "Required arguments:\n" << " <target_seqs.fa> target sequence file in fasta format\n" << " <hits.(sam/bam)> read alignment file in SAM or BAM format\n\n" << standard << advanced; return 1; } if (param_file_name.size()) { burn_in = 0; burn_out = 0; burned_out = true; } size_t stranded_count = 0; if (vm.count("fr-stranded")) { direction = FR; stranded_count++; } if (vm.count("rf-stranded")) { direction = RF; stranded_count++; } if (vm.count("f-stranded")) { direction = F; stranded_count++; } if (vm.count("r-stranded")) { direction = R; stranded_count++; } if (stranded_count > 1) { logger.severe("Multiple strandedness flags cannot be specified in the same " "run."); } if (vm.count("logtostderr")) { logger.info_out(&cerr); } edit_detect = vm.count("edit-detect"); calc_covar = vm.count("calc-covar"); bias_correct = !(vm.count("no-bias-correct")); error_model = !(vm.count("no-error-model")); output_align_prob = vm.count("output-align-prob"); output_align_samp = vm.count("output-align-samp"); output_running_rounds = vm.count("output-running-rounds"); output_running_reads = vm.count("output-running-reads"); batch_mode = vm.count("batch-mode"); both = vm.count("both"); remaining_rounds = max(additional_online, additional_batch); spark_pre = vm.count("preprocess"); if (batch_mode) { ff_param = 1; } if (additional_online > 0 && additional_batch > 0) { logger.severe("Cannot add both online and batch rounds."); } else if (additional_online > 0) { online_additional = true; } if (output_align_prob && output_align_samp) { logger.severe("Cannot output both alignment probabilties and sampled " "alignments."); } if ((output_align_prob || output_align_samp) && remaining_rounds == 0) { logger.warn("It is recommended that at least one additional round " "be used when outputting alignment probabilities or sampled " "alignments. Use the '-B' or '-O' option to enable."); } // We have 1 processing thread and 1 parsing thread always, so we should not // count these as additional threads. if (num_threads < 2) { num_threads = 0; } num_threads -= 2; if (num_threads > 0) { num_threads -= edit_detect; } if (remaining_rounds && in_map_file_names == "") { logger.severe("Cannot process multiple rounds from streaming input."); } if (remaining_rounds) { last_round = false; } if (prior_file != "") { expr_alpha_map = parse_priors(prior_file); } #ifndef WIN32 if (!vm.count("no-update-check")) { check_version(PACKAGE_VERSION); } #endif return 0; }
void Sink::run(void) { int32 ret = 0, is_msg = 0, handler_ret = 0; int32 data_ready = 0; Logger* sl = getBlockManager()->getLogger(); cmessage cm; while (!_quit) { //if (_started) { // // get a message from control pin non blocking // ret = getControlPin()->tryRecvMessage(&cm); // if (ret == SUCCESS) is_msg = 1; //} else { // get a message from control pin blocking ret = getControlPin()->recvMessage(&cm); if (ret == SUCCESS) is_msg = 1; //} if (is_msg) { // detect terminate event if (cm.code == Block::EVENT_TERMINATE) { _started = false; _quit = true; sl->log(Logger::LEVEL_NOTICE, "%s: terminate request received", getName()); // set status setStatus(STATUS_TERMINATING); // jump to while() //continue; } else { // check message codes and set status switch (cm.code) { case EVENT_PAUSE: setStatus(STATUS_PAUSED); _started = false; sl->log(Logger::LEVEL_NOTICE, "%s: pause request received", getName()); break; case EVENT_RESET: setStatus(STATUS_RESETTING); _started = false; sl->log(Logger::LEVEL_NOTICE, "%s: reset request received", getName()); break; case EVENT_START: setStatus(STATUS_STARTED); _started = true; sl->log(Logger::LEVEL_NOTICE, "%s: start request received", getName()); break; case EVENT_STOP: setStatus(STATUS_STOPPED); _started = false; sl->log(Logger::LEVEL_NOTICE, "%s: stop request received", getName()); break; case EVENT_BUFFERIZE: setStatus(STATUS_BUFFERIZING); _started = true; sl->log(Logger::LEVEL_NOTICE, "%s: bufferize request received", getName()); break; case EVENT_SEEK: setStatus(STATUS_SEEKING); setSeekInfo(&cm.seek); sl->log(Logger::LEVEL_NOTICE, "%s: seek request received (strange)", getName()); break; case EVENT_TELL: setStatus(STATUS_TELLING); sl->log(Logger::LEVEL_NOTICE, "%s: tell request received (strange)", getName()); break; case EVENT_SKIP: setStatus(STATUS_SKIPPING); _started = true; setSeekInfo(&cm.seek); sl->log(Logger::LEVEL_NOTICE, "%s: skip request received", getName()); break; case EVENT_QUIT: setStatus(STATUS_QUITTING); _started = false; _quit = true; sl->log(Logger::LEVEL_NOTICE, "%s: quit request received", getName()); break; case EVENT_TIMEOUT: sl->log(Logger::LEVEL_NOTICE, "%s: timeout request received", getName()); break; case EVENT_DATA_READY: setStatus(STATUS_STARTED); _started = true; data_ready = 1; sl->log(Logger::LEVEL_NOTICE, "%s: data_ready request received", getName()); break; case EVENT_COMMAND: sl->log(Logger::LEVEL_NOTICE, "%s: command request received", getName()); break; default: if (cm.code >= EVENT_MAX_ID) sl->log(Logger::LEVEL_CRIT, "%s: invalid message code (%d)", getName(), cm.code); else sl->log(Logger::LEVEL_CRIT, "%s: user message %d received", getName(), cm.code); } // execute event handler for this message code handler_ret = executeEventHandler(cm.code); if (handler_ret == Block::HANDLER_UNDEFINED) { sl->log(Logger::LEVEL_NOTICE, "%s: undefined handler %d", getName(), cm.code); } else if (handler_ret == BlockHandler::HFAILURE) { _started = false; setStatus(STATUS_READY); sl->log(Logger::LEVEL_ERROR, "%s: handler %d failed", getName(), cm.code); } /* * This block checks for StatusListeners availability. If * any status listener has been registered, this block sends * status messages to it. */ if (cm.status_listener) { // DEBUG //UOSUTIL_DOUT((stderr, "Untested code: status listener\n")); smessage sm; memset(&sm, 0, sizeof(smessage)); sm.code = cm.code; sm.serial = cm.serial; sm.status = getStatus(); sm.eh_return = handler_ret; snprintf(sm.error, SM_MESSAGE_SZ, "%s", getErrorString()); ret = cm.status_listener->notifyStatusMessage(&sm); if (ret == FAILURE) { sl->log(Logger::LEVEL_WARN, "%s: cannot notify status to registered listener", getName()); } // DEBUG //UOSUTIL_DOUT((stderr, "Untested code: status listener end\n")); } // set status to ready if compatible if (cm.code != EVENT_START && cm.code != EVENT_STOP && cm.code != EVENT_PAUSE && cm.code != EVENT_DATA_READY && cm.code != EVENT_COMMAND) setStatus(STATUS_READY); // wait for next message is_msg = 0; } } if (_started && data_ready) { // do sink main action: consume data if ready handler_ret = executeActionHandler(ACTION_DATA_CONSUME); if (handler_ret == Block::HANDLER_UNDEFINED) { _started = false; setStatus(STATUS_READY); sl->log(Logger::LEVEL_CRIT, "%s: undefined action handler", getName()); } else if (handler_ret == BlockHandler::HSUCCESS) { // DO NOTHING HERE (useless log) } else if (handler_ret == BlockHandler::HFAILURE) { _started = false; setStatus(STATUS_READY); sl->log(Logger::LEVEL_ERROR, "%s: action handler returned FAILURE", getName()); } else if (handler_ret == BlockHandler::HCRITICAL) { _started = false; setStatus(STATUS_READY); sl->log(Logger::LEVEL_EMERG, "%s: action handler returned CRITICAL FAILURE", getName()); } else { sl->log(Logger::LEVEL_CRIT, "%s: action handler returned undefined value", getName()); } // reset data_ready flag data_ready = 0; } } // release the quit semaphore sl-> log(Logger::LEVEL_CRIT, "%s: Releasing QUIT SEMAPHORE (so quitting)", getName()); _quitSem. post(); // log termination before block destruction sl-> log(Logger::LEVEL_CRIT, "%s: Asking BlockManager for termination", getName()); /* * Notify the block manager that this block is quitting. * Messages must be sent with normal priority since the * block manager have to complete all pending activities. */ cmessage bmm; memset(&bmm, 0, sizeof(bmm)); bmm. code = BlockManager::BM_MESSAGE_BLOCKQUIT; bmm. from = this; getControlPin()-> sendMessage(&bmm); }
// // Get configuration from variant data type // ServiceConfig::State ServiceConfig::GetConfig(const VariantNC & oData, ServiceConfig & oServiceConfig, Logger & oLogger) { // Allow connection from specified IP's or subnets if (ParseNetworks(oData, "AllowConnect", oServiceConfig, oServiceConfig.ipv4_allowed_networks, oLogger) != OK) { return CONFIG_ERROR; } // Deny connection from specified IP's or subnets if (ParseNetworks(oData, "DenyConnect", oServiceConfig, oServiceConfig.ipv4_denied_networks, oLogger) != OK) { return CONFIG_ERROR; } // Order of networks check oServiceConfig.allow_deny_order = ALLOW_DENY; const STLW::vector<STLW::string> vDenyAllow = oData["AllowDenyOrder"]; if (!vDenyAllow.empty() && vDenyAllow[0] != "") { if (vDenyAllow.size() != 2) { oLogger.Emerg("Invalid format of parameter `Service/%s/AllowDenyOrder`: need `allow deny` or `deny allow`", oServiceConfig.name.c_str()); return CONFIG_ERROR; } if (Unicode::CompareIgnoreCase(vDenyAllow[0].data(), vDenyAllow[0].size(), "deny", sizeof("deny") - 1) == 0) { oServiceConfig.allow_deny_order = DENY_ALLOW; } } // Listen to inteface STLW::vector<STLW::string> vListen; ConfigHelper::GetList(oData["Listen"], vListen); STLW::vector<STLW::string>::const_iterator itvListen = vListen.begin(); while(itvListen != vListen.end()) { ListenInterface oInterface; ConfigHelper::State oRC = ConfigHelper::ParseAddress(*itvListen, oInterface.af, oInterface.address, oInterface.port); if (oRC != ConfigHelper::OK) { oLogger.Emerg("Invalid address: `%s`", itvListen -> c_str()); return CONFIG_ERROR; } oServiceConfig.listen.push_back(oInterface); ++itvListen; } // Socket listen queue oServiceConfig.listen_queue = oData["MaxQueueLength"]; if (oServiceConfig.listen_queue == 0) { oLogger.Emerg("Invalid format of parameter `Service/%s/MaxQueueLength` not set", oServiceConfig.name.c_str()); return CONFIG_ERROR; } // Read buffer size oServiceConfig.recv_buffer_size = ConfigHelper::ParseSize(oData["RecvBufferSize"]); if (oServiceConfig.recv_buffer_size == 0 || oServiceConfig.recv_buffer_size == UINT_32(-1)) { oLogger.Emerg("Invalid format of parameter `Service/%s/RecvBufferSize` not set", oServiceConfig.name.c_str()); return CONFIG_ERROR; } // Maximum number of connections for this service oServiceConfig.max_clients = oData["MaxClients"]; if (oServiceConfig.max_clients == 0) { oLogger.Warn("Parameter `Service/%s/MaxClients`: not set", oServiceConfig.name.c_str()); } // Number of active clients oServiceConfig.active_clients = 0; // Read/Write timeout oServiceConfig.io_timeout = ConfigHelper::ParseTimeout(oData["IOTimeout"]) / 1000.0; if (oServiceConfig.io_timeout == 0) { oLogger.Emerg("Parameter `Service/%s/IOTimeout`: need to set positive value", oServiceConfig.name.c_str()); return CONFIG_ERROR; } #ifdef IRIS_TLS_SUPPORT // TLS parameters oServiceConfig.enable_ssl_tls = ConfigHelper::ParseBool(oData["EnableTLSSSL"]); if (oServiceConfig.enable_ssl_tls) { // File with the RSA certificate in PEM format. oServiceConfig.tls_cert_file = oData["TLSCertFile"]; // File with the RSA private key in PEM format oServiceConfig.tls_key_file = oData["TLSKeyFile"]; // File with the DH data oServiceConfig.dh_file.assign(oData["DHFile"]); // SSL Ciphers oServiceConfig.ciphers.assign(oData["SSLCiphers"]); if (oServiceConfig.tls_cert_file.size() != oServiceConfig.tls_key_file.size()) { oLogger.Emerg("Number of files `Service/%s/TLSCertFile` and Service/%s/TLSKeyFile` must be equal", oServiceConfig.name.c_str()); return CONFIG_ERROR; } // Use Transport Level Security at connection time oServiceConfig.use_tls = ConfigHelper::ParseBool(oData["UseTLS"]); // Allow upgrade an existing insecure connection to a secure connection using SSL/TLS oServiceConfig.start_tls = ConfigHelper::ParseBool(oData["StartTLS"]); // Prefer to user server ciphers oServiceConfig.prefer_server_ciphers = ConfigHelper::ParseBool(oData["PreferServerCiphers"], true); } #endif // IRIS_TLS_SUPPORT // Handler name oServiceConfig.handler_name.assign(oData["Handler"]); // Handler object oServiceConfig.handler = NULL; return OK; }
AndroidSystemLogOutput() { g_logger.addOutput(this); }
/** * "Boots" up XCSoar * @param hInstance Instance handle * @param lpCmdLine Command line string * @return True if bootup successful, False otherwise */ bool XCSoarInterface::Startup(HINSTANCE hInstance, LPTSTR lpCmdLine) { // The title bar text TCHAR szTitle[MAX_LOADSTRING]; // Store instance handle in our global variable hInst = hInstance; // IDS_APP_TITLE = XCSoar (see XCSoar.rc) LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); //If it is already running, then focus on the window if (MainWindow::find(szTitle)) return false; // Send the SettingsMap to the DeviceBlackboard SendSettingsMap(); // Register window classes PaintWindow::register_class(hInst); MainWindow::register_class(hInst); MapWindow::register_class(hInst); // Fill the fast(co)sine table InitSineTable(); PreloadInitialisation(true); // Send the SettingsMap to the DeviceBlackboard SendSettingsMap(); // Creates the main window StartupStore(TEXT("Create main window\n")); RECT WindowSize = SystemWindowSize(); main_window.set(szTitle, WindowSize.left, WindowSize.top, WindowSize.right, WindowSize.bottom); if (!main_window.defined()) { return false; } main_window.install_timer(); // Initialize DeviceBlackboard device_blackboard.Initialise(); // Initialize Marks marks = new Marks("xcsoar-marks"); topology = new TopologyStore(marks->GetTopology()); // Show the main and map windows StartupStore(TEXT("Create map window\n")); main_window.show(); main_window.map.show(); #ifdef HAVE_ACTIVATE_INFO SHSetAppKeyWndAssoc(VK_APP1, main_window); SHSetAppKeyWndAssoc(VK_APP2, main_window); SHSetAppKeyWndAssoc(VK_APP3, main_window); SHSetAppKeyWndAssoc(VK_APP4, main_window); // Typical Record Button // Why you can't always get this to work // http://forums.devbuzz.com/m_1185/mpage_1/key_/tm.htm // To do with the fact it is a global hotkey, but you can with code above // Also APPA is record key on some systems SHSetAppKeyWndAssoc(VK_APP5, main_window); SHSetAppKeyWndAssoc(VK_APP6, main_window); #endif // Initialize main blackboard data task.ClearTask(); glide_computer.Initialise(); logger.LinkGRecordDLL(); // try to link DLL if it exists // Load the EGM96 geoid data OpenGeoid(); PreloadInitialisation(false); Profile::LoadWindFromRegistry(); // TODO TB: seems to be out of date?! CalculateNewPolarCoef(); // Calculate polar-related data and saves it to the cache StartupStore(TEXT("GlidePolar::UpdatePolar\n")); GlidePolar::UpdatePolar(false, SettingsComputer()); // Show startup info depending on device StartupInfo(); // Read the topology file(s) topology->Open(); // Read the terrain file terrain.OpenTerrain(); // Read the waypoint files ReadWayPoints(way_points, terrain); // Read and parse the airfield info file ReadAirfieldFile(); // Set the home waypoint SetHome(way_points, terrain, SetSettingsComputer(), false, true); // ReSynchronise the blackboards here since SetHome touches them ReadBlackboardBasic(device_blackboard.Basic()); terrain.ServiceFullReload(Basic().Location); // Scan for weather forecast CreateProgressDialog(gettext(TEXT("Scanning weather forecast"))); StartupStore(TEXT("RASP load\n")); RASP.ScanAll(Basic().Location); // Reads the airspace files ReadAirspace(); // Sorts the airspaces by priority SortAirspace(); // Read the FLARM details file OpenFLARMDetails(); #ifndef DISABLEAUDIOVARIO /* VarioSound_Init(); VarioSound_EnableSound(EnableSoundVario); VarioSound_SetVdead(SoundDeadband); VarioSound_SetV(0); VarioSound_SetSoundVolume(SoundVolume); */ #endif // Start the device thread(s) CreateProgressDialog(gettext(TEXT("Starting devices"))); devStartup(lpCmdLine); // Reset polar in case devices need the data StartupStore(TEXT("GlidePolar::UpdatePolar\n")); GlidePolar::UpdatePolar(true, SettingsComputer()); CreateProgressDialog(gettext(TEXT("Initialising display"))); // Finally ready to go.. all structures must be present before this. // Create the drawing thread StartupStore(TEXT("CreateDrawingThread\n")); draw_thread = new DrawThread(main_window.map, main_window.flarm); draw_thread->start(); // Show the infoboxes StartupStore(TEXT("ShowInfoBoxes\n")); InfoBoxManager::Show(); // Create the calculation thread StartupStore(TEXT("CreateCalculationThread\n")); CreateCalculationThread(); #ifdef NEWTASK { // NEWTASK PeriodClock t; t.reset(); t.update(); CreateProgressDialog(gettext(TEXT("Running test 0"))); test_newtask(0); StartupStore(TEXT("test 0 %d\n"),t.elapsed()); /* t.update(); CreateProgressDialog(gettext(TEXT("Running test 1"))); test_newtask(1); StartupStore(TEXT("test 1 %d\n"),t.elapsed()); t.update(); CreateProgressDialog(gettext(TEXT("Running test 2"))); test_newtask(2); StartupStore(TEXT("test 2 %d\n"),t.elapsed()); t.update(); CreateProgressDialog(gettext(TEXT("Running test 3"))); test_newtask(3); StartupStore(TEXT("test 3 %d\n"),t.elapsed()); t.update(); CreateProgressDialog(gettext(TEXT("Running test 4"))); test_newtask(4); StartupStore(TEXT("test 4 %d\n"),t.elapsed()); */ CreateProgressDialog(gettext(TEXT("test complete"))); } #endif // Initialise the airspace warning dialog StartupStore(TEXT("dlgAirspaceWarningInit\n")); dlgAirspaceWarningInit(); // Find unique ID of this PDA ReadAssetNumber(); StartupStore(TEXT("ProgramStarted\n")); // Give focus to the map main_window.map.set_focus(); // Start calculation thread calculation_thread->start(); // Start instrument thread instrument_thread->start(); globalRunningEvent.trigger(); return true; }
~AndroidSystemLogOutput() { g_logger.removeOutput(this); }
/*! This is the main function and creates and links all the different classes. First it reads in all the parameters from the command prompt (<program name> -help)and uses these values to create the classes. After all the classes are linked, the mainLoop in the Player class is called. */ int main( int argc, char * argv[] ) { #ifdef WIN32 HANDLE listen, sense; #else pthread_t listen, sense; #endif ServerSettings ss; PlayerSettings cs; // define variables for command options and initialize with default values char strTeamName[MAX_TEAM_NAME_LENGTH] = "UvA_Trilearn"; int iPort = 6002; int iMinLogLevel = 0 ; int iMaxLogLevel = 0; char strHost[128] = "localhost"; double dVersion = 14; int iMode = 0; char strFormations[128] = "formations.conf"; int iNr = 0; int iReconnect = -1; bool bInfo = false; bool bSuppliedLogFile = false; ofstream os; // read in all the command options and change the associated variables // assume every two values supplied at prompt, form a duo char * str; for( int i = 1 ; i < argc ; i = i + 2 ) { // help is only option that does not have to have an argument if( i + 1 >= argc && strncmp( argv[i], "-help", 3 ) != 0 ) { cout << "Need argument for option: " << argv[i] << endl; exit( 0 ); } // read a command option if( argv[i][0] == '-' && strlen( argv[i] ) > 1) { switch( argv[i][1] ) { case 'h': // host server or help if( strlen( argv [i]) > 2 && argv[i][2] == 'e' ) { printOptions( ); exit(0); } else strcpy( strHost, argv[i+1] ); break; case 'f': // formations file strcpy( strFormations, argv[i+1] ); break; case 'c': // clientconf file if( cs.readValues( argv[i+1], ":" ) == false ) cerr << "Error in reading client file: " << argv[i+1] << endl; break; case 'i': // info 1 0 str = &argv[i+1][0]; bInfo = (Parse::parseFirstInt( &str ) == 1 ) ? true : false ; break; case 'l': // loglevel int[..int] str = &argv[i+1][0]; iMinLogLevel = Parse::parseFirstInt( &str ); while( iMinLogLevel != 0 ) { if( *str == '.' ) // '.' indicates range of levels { iMaxLogLevel = Parse::parseFirstInt( &str ); if( iMaxLogLevel == 0 ) iMaxLogLevel = iMinLogLevel; Log.addLogRange( iMinLogLevel, iMaxLogLevel ); } else Log.addLogLevel( iMinLogLevel ); iMinLogLevel = Parse::parseFirstInt( &str ); } break; case 'm': // mode int str = &argv[i+1][0]; iMode = Parse::parseFirstInt( &str ); break; case 'o': // output file log info os.open( argv[i+1] ); bSuppliedLogFile = true; break; case 'p': // port str = &argv[i+1][0]; iPort = Parse::parseFirstInt( &str ); break; case 's': // serverconf file if( ss.readValues( argv[i+1], ":" ) == false ) cerr << "Error in reading server file: " << argv[i+1] << endl; break; case 't': // teamname name strcpy( strTeamName, argv[i+1] ); break; case 'v': // version version str = &argv[i+1][0]; dVersion = Parse::parseFirstDouble( &str ); break; default: cerr << "(main) Unknown command option: " << argv[i] << endl; } } } if( bInfo == true ) cout << "team : " << strTeamName << endl << "port : " << iPort << endl << "host : " << strHost << endl << "version : " << dVersion << endl << "min loglevel : " << iMinLogLevel << endl << "max loglevel : " << iMaxLogLevel << endl << "mode : " << iMode << endl << "playernr : " << iNr << endl << "reconnect : " << iReconnect << endl ; if( bSuppliedLogFile == true ) Log.setOutputStream( os ); // initialize logger else Log.setOutputStream( cout ); Log.restartTimer( ); Formations fs( strFormations, (FormationT)cs.getInitialFormation(), iNr ); // read formations file WorldModel wm( &ss, &cs, &fs ); // create worldmodel Connection c( strHost, iPort, MAX_MSG ); // make connection with server ActHandler a( &c, &wm, &ss ); // link actHandler and WM SenseHandler s( &c, &wm, &ss, &cs ); // link senseHandler with wm bool isTrainer = (iPort == ss.getCoachPort()) ? true : false; BasicCoach bp( &a, &wm, &ss, strTeamName, dVersion, isTrainer ); // link acthandler and WM #ifdef WIN32 DWORD id1; sense = CreateThread(NULL, 0, &sense_callback, &s, 0, &id1); if (sense == NULL) { cerr << "create thread error" << endl; return false; } #else pthread_create( &sense, NULL, sense_callback , &s); // start listening #endif if( iMode > 0 && iMode < 9 ) // only listen to sdtdin when not playing #ifdef WIN32 { DWORD id2; listen = CreateThread(NULL, 0, &stdin_callback, &bp, 0, &id2); if ( listen == NULL) { cerr << "create thread error" << endl; return false; } } #else pthread_create( &listen, NULL, stdin_callback, &bp); #endif if( iMode == 0 ) bp.mainLoopNormal(); c.disconnect(); os.close(); }
void RawLogBuffer::flush(const std::string &buffer) { g_logger.logRaw(LL_NONE, buffer); }
int main() { // Set up logging BasicConfigurator config; config.configure(); logger.setLogLevel(TRACE_LOG_LEVEL); int r; UsbContext usb; UsbDevice dev (jambox_open(usb)); if (!dev) { //LOG4CPLUS_TRACE_STR(logger, "Main::Main()"); LOG4CPLUS_ERROR(logger, "Failed to find a jambox"); return NULL; } /* unsigned char data[] = {0x00, 0xFC, 0x23, 0xC2, 0x00, 0x00, 0x11, 0x00, 0x3B, 0x71,/ 0x03, 0x70, 0x00, 0x00, 0x08, 0x01, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; int len = sizeof(data) / sizeof(*data); */ jambox_req req; int actual = 0; //used to find out how many bytes were written create_name_request(&req); unsigned char * data = (unsigned char *)&req; int len = 0x26; print_bytes(data, len); cout<<"Writing Data"<<endl; r = libusb_control_transfer(dev, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, data, len, USB_TIMEOUT); if(r == len) { cout<<"Writing Successful!"<<endl; } else { cout<<"Write Error "<< r << " " << actual << "/" << len << endl; } //r = libusb_interrupt_transfer(dev, 0x81, in, sizeof(in), &actual, USB_TIMEOUT); r = libusb_interrupt_transfer(dev, 0x81, &req.data[1], sizeof(req) - 1, &actual, USB_TIMEOUT); printf("interrupt read returned %d, %d bytes: ", r, actual); print_bytes((unsigned char *)&req, actual + 1); //printf("\n"); printf("device name: %s\n", &req.data[20]); create_pair_request(&req); len = 0x6a; print_bytes((unsigned char *)&req, req.header.len + 3); r = libusb_control_transfer(dev, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, data, len, USB_TIMEOUT); if(r == len) { cout<<"Writing Successful!"<<endl; } else { cout<<"Write Error "<< r << " " << actual << "/" << len << endl; } //r = libusb_interrupt_transfer(dev, 0x81, in, sizeof(in), &actual, USB_TIMEOUT); r = libusb_interrupt_transfer(dev, 0x81, &req.data[1], sizeof(req) - 1, &actual, USB_TIMEOUT); printf("interrupt read returned %d, %d bytes: ", r, actual); print_bytes((unsigned char *)&req, actual + 1); //printf("\n"); printf("device name: %s\n", &req.data[20]); return 0; }
void nvlog_flush() { nvlogger.Flush(); }
int main(int argc, char *argv[]) { #ifdef WIN32 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // dump leaks at return //_CrtSetBreakAlloc(287); #endif string verboseLevelConsole; string verboseLevelImages; vector<path> inputPaths; path inputFilelist; path inputDirectory; vector<path> inputFilenames; path configFilename; shared_ptr<ImageSource> imageSource; path outputPicsDir; try { po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("verbose,v", po::value<string>(&verboseLevelConsole)->implicit_value("DEBUG")->default_value("INFO","show messages with INFO loglevel or below."), "specify the verbosity of the console output: PANIC, ERROR, WARN, INFO, DEBUG or TRACE") ("verbose-images,w", po::value<string>(&verboseLevelImages)->implicit_value("INTERMEDIATE")->default_value("FINAL","write images with FINAL loglevel or below."), "specify the verbosity of the image output: FINAL, INTERMEDIATE, INFO, DEBUG or TRACE") ("config,c", po::value<path>()->required(), "path to a config (.cfg) file") ("input,i", po::value<vector<path>>()->required(), "input from one or more files, a directory, or a .lst-file containing a list of images") ("output-dir,o", po::value<path>()->default_value("."), "output directory for the result images") ; po::positional_options_description p; p.add("input", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << "Usage: mergePlaygroundApp [options]\n"; cout << desc; return EXIT_SUCCESS; } if (vm.count("verbose")) { verboseLevelConsole = vm["verbose"].as<string>(); } if (vm.count("verbose-images")) { verboseLevelImages = vm["verbose-images"].as<string>(); } if (vm.count("input")) { inputPaths = vm["input"].as<vector<path>>(); } if (vm.count("config")) { configFilename = vm["config"].as<path>(); } if (vm.count("output-dir")) { outputPicsDir = vm["output-dir"].as<path>(); } } catch(std::exception& e) { cout << e.what() << endl; return EXIT_FAILURE; } loglevel logLevel; if(boost::iequals(verboseLevelConsole, "PANIC")) logLevel = loglevel::PANIC; else if(boost::iequals(verboseLevelConsole, "ERROR")) logLevel = loglevel::ERROR; else if(boost::iequals(verboseLevelConsole, "WARN")) logLevel = loglevel::WARN; else if(boost::iequals(verboseLevelConsole, "INFO")) logLevel = loglevel::INFO; else if(boost::iequals(verboseLevelConsole, "DEBUG")) logLevel = loglevel::DEBUG; else if(boost::iequals(verboseLevelConsole, "TRACE")) logLevel = loglevel::TRACE; else { cout << "Error: Invalid loglevel." << endl; return EXIT_FAILURE; } imagelogging::loglevel imageLogLevel; if(boost::iequals(verboseLevelImages, "FINAL")) imageLogLevel = imagelogging::loglevel::FINAL; else if(boost::iequals(verboseLevelImages, "INTERMEDIATE")) imageLogLevel = imagelogging::loglevel::INTERMEDIATE; else if(boost::iequals(verboseLevelImages, "INFO")) imageLogLevel = imagelogging::loglevel::INFO; else if(boost::iequals(verboseLevelImages, "DEBUG")) imageLogLevel = imagelogging::loglevel::DEBUG; else if(boost::iequals(verboseLevelImages, "TRACE")) imageLogLevel = imagelogging::loglevel::TRACE; else { cout << "Error: Invalid image loglevel." << endl; return EXIT_FAILURE; } Loggers->getLogger("classification").addAppender(make_shared<logging::ConsoleAppender>(logLevel)); Loggers->getLogger("imageio").addAppender(make_shared<logging::ConsoleAppender>(logLevel)); Loggers->getLogger("imageprocessing").addAppender(make_shared<logging::ConsoleAppender>(logLevel)); Loggers->getLogger("detection").addAppender(make_shared<logging::ConsoleAppender>(logLevel)); Loggers->getLogger("ffpDetectApp").addAppender(make_shared<logging::ConsoleAppender>(logLevel)); Logger appLogger = Loggers->getLogger("ffpDetectApp"); appLogger.debug("Verbose level for console output: " + logging::loglevelToString(logLevel)); appLogger.debug("Verbose level for image output: " + imagelogging::loglevelToString(imageLogLevel)); appLogger.debug("Using config: " + configFilename.string()); appLogger.debug("Using output directory: " + outputPicsDir.string()); if(outputPicsDir.empty()) { appLogger.info("Output directory not set. Writing images into current directory."); } ImageLoggers->getLogger("detection").addAppender(make_shared<imagelogging::ImageFileWriter>(imageLogLevel, outputPicsDir)); ImageLoggers->getLogger("mergePlaygroundApp").addAppender(make_shared<imagelogging::ImageFileWriter>(imageLogLevel, outputPicsDir)); // TEMP: Read a txt patchset from Cog, do WHI, and write a new .txt. // ================================================================= vector<cv::Mat> positives; std::ifstream file("E:/training/ffd_training_regrPaperX200/data/posPatches.txt"); if (!file.is_open()) { std::cout << "Invalid patches file" << std::endl; return 0; } while (file.good()) { string line; if (!std::getline(file, line)) break; int width = 31; int height = 31; int dimensions = width * height; Mat patch(width, height, CV_8U); std::istringstream lineStream(line); if (!lineStream.good() || lineStream.fail()) { std::cout << "Invalid patches file l2" << std::endl; return 0; } uchar* values = patch.ptr<uchar>(0); float val; for (int j = 0; j < dimensions; ++j) { lineStream >> val; values[j] = static_cast<uchar>(val*255.0f); } positives.push_back(patch); } file.close(); vector<cv::Mat> negatives; file.open("E:/training/ffd_training_regrPaperX200/data/negPatches.txt"); if (!file.is_open()) { std::cout << "Invalid patches file" << std::endl; return 0; } while (file.good()) { string line; if (!std::getline(file, line)) break; int width = 31; int height = 31; int dimensions = width * height; Mat patch(width, height, CV_8U); std::istringstream lineStream(line); if (!lineStream.good() || lineStream.fail()) { std::cout << "Invalid patches file l4" << std::endl; return 0; } uchar* values = patch.ptr<uchar>(0); float val; for (int j = 0; j < dimensions; ++j) { lineStream >> val; values[j] = static_cast<uchar>(val*255.0f); } negatives.push_back(patch); } file.close(); shared_ptr<WhiteningFilter> fw = make_shared<WhiteningFilter>(); shared_ptr<HistogramEqualizationFilter> fh = make_shared<HistogramEqualizationFilter>(); shared_ptr<ConversionFilter> fc = make_shared<ConversionFilter>(CV_32F, 1.0/127.5, -1.0); shared_ptr<UnitNormFilter> fi = make_shared<UnitNormFilter>(cv::NORM_L2); shared_ptr<ReshapingFilter> fr = make_shared<ReshapingFilter>(1); for (auto& p : positives) { //p.convertTo(p, CV_32F); fw->applyInPlace(p); // min/max, stretch to [0, 255] 8U fh->applyInPlace(p); // need to go back to [-1, 1] before UnitNormFilter: fc->applyInPlace(p); fi->applyInPlace(p); fr->applyInPlace(p); } for (auto& p : negatives) { fw->applyInPlace(p); fh->applyInPlace(p); fc->applyInPlace(p); fi->applyInPlace(p); fr->applyInPlace(p); } std::ofstream ofile("E:/training/ffd_training_regrPaperX200/data/posPatchesWhi.txt"); if (!ofile.is_open()) { std::cout << "Invalid patches file" << std::endl; return 0; } for (auto& p : positives) { int width = 31; int height = 31; int dimensions = width * height; float* values = p.ptr<float>(0); float val; for (int j = 0; j < dimensions; ++j) { ofile << values[j] << " "; } ofile << "\n"; } ofile.close(); ofile.open("E:/training/ffd_training_regrPaperX200/data/negPatchesWhi.txt"); if (!ofile.is_open()) { std::cout << "Invalid patches file" << std::endl; return 0; } for (auto& p : negatives) { int width = 31; int height = 31; int dimensions = width * height; float* values = p.ptr<float>(0); float val; for (int j = 0; j < dimensions; ++j) { ofile << values[j] << " "; } ofile << "\n"; } ofile.close(); // END TEMP std::chrono::time_point<std::chrono::system_clock> start, end; Mat img; while(imageSource->next()) { img = imageSource->getImage(); start = std::chrono::system_clock::now(); // do something end = std::chrono::system_clock::now(); int elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(end-start).count(); int elapsed_mseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); std::time_t end_time = std::chrono::system_clock::to_time_t(end); stringstream ss; ss << std::ctime(&end_time); appLogger.info("finished computation at " + ss.str() + "elapsed time: " + lexical_cast<string>(elapsed_seconds) + "s or exactly " + lexical_cast<string>(elapsed_mseconds) + "ms.\n"); } return 0; }
char* BSONObj::toChar() { // if the toChar was already calculated before use it if (_cBSON != NULL) { return strcpy(_cBSON); } Logger* log = getLogger(NULL); char* result = (char*)malloc(MAX_BSONOBJ_BUFFER); memset(result, 0, MAX_BSONOBJ_BUFFER); __int32 pos = 0; result[0] = '{'; pos += 1; bool first = true; for (std::map<std::string, BSONContent* >::const_iterator i = _elements.begin(); i != _elements.end(); i++) { if (!first) { result[pos] = ','; pos++; } first = false; BSONContent* content = i->second; std::string key = i->first; sprintf(result + pos, " \"%s\" : ", key.c_str()); pos += key.length() + 6; //ss << "\"" << key << "\" :"; char* chr; const char* cstr; switch (content->type()) { case BSON_TYPE: { BSONContentBSON* bbson = (BSONContentBSON*)content; BSONObj* bson = (BSONObj*)*bbson; char* chrbson = bson->toChar(); sprintf(result + pos, "%s", chrbson); free(chrbson); break; } case BSONARRAY_TYPE: { BSONContentBSONArray* bbsonarray = (BSONContentBSONArray*)content; BSONArrayObj* bsonarray = (BSONArrayObj*)*bbsonarray; char* chrbsonarray = bsonarray->toChar(); sprintf(result + pos, "%s", chrbsonarray); free(chrbsonarray); break; } case BOOL_TYPE: { BSONContentBoolean* bb = (BSONContentBoolean*)content; sprintf(result + pos, "%s", ((bool)*bb?"true": "false")); break; } case INT_TYPE: { BSONContentInt* bint = (BSONContentInt*)content; sprintf(result + pos, "%d", (__int32)*bint); break; } case LONG_TYPE: { BSONContentLong* blong = (BSONContentLong*)content; sprintf(result + pos, "%ld", (__int64)*blong); break; } case DOUBLE_TYPE: { BSONContentDouble* bdouble = (BSONContentDouble*)content; sprintf(result + pos, "%f", (double)*bdouble); break; } case STRING_TYPE: case PTRCHAR_TYPE: { BSONContentString* bstring = (BSONContentString*)content; djondb::string s = *bstring; sprintf(result + pos, "\"%.*s\"", s.length(), s.c_str()); break; } } pos = strlen(result); assert(pos < MAX_BSONOBJ_BUFFER); } result[pos] = '}'; result[pos+1] = 0; pos++; __int32 len = strlen(result); // Saves the value to cache the calculated value _cBSON = result; char* cresult = strcpy(result); if (log->isDebug()) log->debug("toChar result: %s", cresult); return cresult; }
void log_open(const char *filename){ return logger.open(filename); }
// // Handler // INT_32 FnMBTruncate::Handler(CDT * aArguments, const UINT_32 iArgNum, CDT & oCDTRetVal, Logger & oLogger) { if (iArgNum == 2) { const UINT_32 iMaxLen = UINT_32(aArguments[0].GetInt()); const STLW::string sData = aArguments[1].GetString(); CCHAR_P szStart = sData.data(); CCHAR_P szEnd = sData.data() + sData.size(); INT_32 iPos = 0; UINT_32 iCharPos = 0; for(;;) { INT_32 iCharLen = utf_charlen(szStart + iPos, szEnd); if (iCharLen == -3) { break; } // Check character length if (iCharLen < 0) { iCharLen = 1; } // Skip errors else { ++iCharPos; } iPos += iCharLen; if (iCharPos >= iMaxLen) { break; } } if (iCharPos == iMaxLen) { oCDTRetVal = STLW::string(sData, 0, iPos); } else { oCDTRetVal = sData; } return 0; } else if (iArgNum == 3) { const UINT_32 iMaxLen = UINT_32(aArguments[1].GetInt()); STLW::string sData = aArguments[2].GetString(); CCHAR_P szStart = sData.data(); CCHAR_P szEnd = sData.data() + sData.size(); INT_32 iPos = 0; UINT_32 iCharPos = 0; for(;;) { INT_32 iCharLen = utf_charlen(szStart + iPos, szEnd); if (iCharLen == -3) { break; } // Check character length if (iCharLen < 0) { iCharLen = 1; } // Skip errors else { ++iCharPos; } iPos += iCharLen; if (iCharPos >= iMaxLen) { break; } } if (iCharPos >= iMaxLen) { sData = STLW::string(sData, 0, iPos); sData.append(aArguments[0].GetString()); } oCDTRetVal = sData; return 0; } oLogger.Emerg("Usage: MB_TRUNCATE(data, offset) or MB_TRUNCATE(data, offset, add_on)"); return -1; }
/// /// Create the menubar /// void MainForm::createMenuBar() { // menubar QMenuBar *m_pMenubar = new QMenuBar( this ); setMenuBar( m_pMenubar ); // FILE menu QMenu *m_pFileMenu = m_pMenubar->addMenu( trUtf8( "&Project" ) ); m_pFileMenu->addAction( trUtf8( "&New" ), this, SLOT( action_file_new() ), QKeySequence( "Ctrl+N" ) ); m_pFileMenu->addAction( trUtf8( "Show &info" ), this, SLOT( action_file_songProperties() ), QKeySequence( "" ) ); m_pFileMenu->addSeparator(); // ----- m_pFileMenu->addAction( trUtf8( "&Open" ), this, SLOT( action_file_open() ), QKeySequence( "Ctrl+O" ) ); m_pFileMenu->addAction( trUtf8( "Open &Demo" ), this, SLOT( action_file_openDemo() ), QKeySequence( "Ctrl+D" ) ); m_pRecentFilesMenu = m_pFileMenu->addMenu( trUtf8( "Open &recent" ) ); m_pFileMenu->addSeparator(); // ----- m_pFileMenu->addAction( trUtf8( "&Save" ), this, SLOT( action_file_save() ), QKeySequence( "Ctrl+S" ) ); m_pFileMenu->addAction( trUtf8( "Save &as..." ), this, SLOT( action_file_save_as() ), QKeySequence( "Ctrl+Shift+S" ) ); m_pFileMenu->addSeparator(); // ----- m_pFileMenu->addAction ( trUtf8 ( "Open &Pattern" ), this, SLOT ( action_file_openPattern() ), QKeySequence ( "" ) ); m_pFileMenu->addAction( trUtf8( "Expor&t pattern as..." ), this, SLOT( action_file_export_pattern_as() ), QKeySequence( "Ctrl+P" ) ); m_pFileMenu->addSeparator(); // ----- m_pFileMenu->addAction( trUtf8( "Export &MIDI file" ), this, SLOT( action_file_export_midi() ), QKeySequence( "Ctrl+M" ) ); m_pFileMenu->addAction( trUtf8( "&Export song" ), this, SLOT( action_file_export() ), QKeySequence( "Ctrl+E" ) ); m_pFileMenu->addAction( trUtf8( "Export &LilyPond file" ), this, SLOT( action_file_export_lilypond() ), QKeySequence( "Ctrl+L" ) ); #ifndef Q_OS_MACX m_pFileMenu->addSeparator(); // ----- m_pFileMenu->addAction( trUtf8("&Quit"), this, SLOT( action_file_exit() ), QKeySequence( "Ctrl+Q" ) ); #endif updateRecentUsedSongList(); connect( m_pRecentFilesMenu, SIGNAL( triggered(QAction*) ), this, SLOT( action_file_open_recent(QAction*) ) ); //~ FILE menu // Undo menu QMenu *m_pUndoMenu = m_pMenubar->addMenu( trUtf8( "&Undo" ) ); m_pUndoMenu->addAction( trUtf8( "Undo" ), this, SLOT( action_undo() ), QKeySequence( "Ctrl+Z" ) ); m_pUndoMenu->addAction( trUtf8( "Redo" ), this, SLOT( action_redo() ), QKeySequence( "Shift+Ctrl+Z" ) ); m_pUndoMenu->addAction( trUtf8( "Undo history" ), this, SLOT( openUndoStack() ), QKeySequence( "" ) ); // INSTRUMENTS MENU QMenu *m_pInstrumentsMenu = m_pMenubar->addMenu( trUtf8( "I&nstruments" ) ); m_pInstrumentsMenu->addAction( trUtf8( "&Add instrument" ), this, SLOT( action_instruments_addInstrument() ), QKeySequence( "" ) ); m_pInstrumentsMenu->addAction( trUtf8( "&Clear all" ), this, SLOT( action_instruments_clearAll() ), QKeySequence( "" ) ); m_pInstrumentsMenu->addAction( trUtf8( "&Save library" ), this, SLOT( action_instruments_saveLibrary() ), QKeySequence( "" ) ); m_pInstrumentsMenu->addAction( trUtf8( "&Export library" ), this, SLOT( action_instruments_exportLibrary() ), QKeySequence( "" ) ); m_pInstrumentsMenu->addAction( trUtf8( "&Import library" ), this, SLOT( action_instruments_importLibrary() ), QKeySequence( "" ) ); // Tools menu QMenu *m_pToolsMenu = m_pMenubar->addMenu( trUtf8( "&Tools" )); m_pToolsMenu->addAction( trUtf8("Playlist &editor"), this, SLOT( action_window_showPlaylistDialog() ), QKeySequence( "" ) ); m_pToolsMenu->addAction( trUtf8("Director"), this, SLOT( action_window_show_DirectorWidget() ), QKeySequence( "Alt+D" ) ); m_pToolsMenu->addAction( trUtf8("&Mixer"), this, SLOT( action_window_showMixer() ), QKeySequence( "Alt+M" ) ); m_pToolsMenu->addAction( trUtf8("&Instrument Rack"), this, SLOT( action_window_showDrumkitManagerPanel() ), QKeySequence( "Alt+I" ) ); m_pInputModeMenu = m_pToolsMenu->addMenu( trUtf8( "Input mode" ) ); m_pInstrumentAction = m_pInputModeMenu->addAction( trUtf8( "Instrument" ), this, SLOT( action_toggle_input_mode()), QKeySequence( "Ctrl+Alt+I" ) ); m_pInstrumentAction->setCheckable( true ); m_pDrumkitAction = m_pInputModeMenu->addAction( trUtf8( "Drumkit" ), this, SLOT( action_toggle_input_mode()), QKeySequence( "Ctrl+Alt+D" ) ); m_pDrumkitAction->setCheckable( true ); if( Preferences::get_instance()->__playselectedinstrument ) { m_pInstrumentAction->setChecked( true ); m_pDrumkitAction->setChecked (false ); } else { m_pInstrumentAction->setChecked( false ); m_pDrumkitAction->setChecked (true ); } m_pToolsMenu->addAction( trUtf8("&Preferences"), this, SLOT( showPreferencesDialog() ), QKeySequence( "Alt+P" ) ); //~ Tools menu Logger *pLogger = Logger::get_instance(); if ( pLogger->bit_mask() >= 1 ) { // DEBUG menu QMenu *m_pDebugMenu = m_pMenubar->addMenu( trUtf8("De&bug") ); m_pDebugMenu->addAction( trUtf8( "Show &audio engine info" ), this, SLOT( action_debug_showAudioEngineInfo() ) ); if(pLogger->bit_mask() == 8) // hydrogen -V8 list object map in console m_pDebugMenu->addAction( trUtf8( "Print Objects" ), this, SLOT( action_debug_printObjects() ) ); //~ DEBUG menu } // INFO menu QMenu *m_pInfoMenu = m_pMenubar->addMenu( trUtf8( "&Info" ) ); m_pInfoMenu->addAction( trUtf8("&User manual"), this, SLOT( showUserManual() ), QKeySequence( "Ctrl+?" ) ); m_pInfoMenu->addSeparator(); m_pInfoMenu->addAction( trUtf8("&About"), this, SLOT( action_help_about() ), QKeySequence( trUtf8("", "Info|About") ) ); m_pInfoMenu->addAction( trUtf8("Report bug"), this, SLOT( action_report_bug() )); //m_pInfoMenu->addAction( trUtf8("Donate"), this, SLOT( action_donate() )); //~ INFO menu }
int main(int argc, char* argv[]) { // Initialize logger logFile.open("engine_test.log"); logFilePath = std::experimental::filesystem::current_path(); logFilePath /= "engine_test.log"; cout << "Log files can be found at:\n "; cout << " " << logFilePath << endl; if (logFile.is_open()) { logger.OpenStream(&logFile); } else { logger.OpenStream(&std::cout); } // Set exception terminate handler std::set_terminate(OnTerminate); // Create the window itself Window window; window.SetTitle("QC Simulator"); window.SetSize({ 960, 640 }); // Create GraphicsEngine systemLogStream.Event("Initializing Graphics Engine..."); std::unique_ptr<IGxapiManager> gxapiMgr; std::unique_ptr<IGraphicsApi, ReportDeleter> gxapi; std::unique_ptr<GraphicsEngine> engine; std::unique_ptr<QCWorld> qcWorld; std::unique_ptr<InputHandler> inputHandler; std::unique_ptr<Input> joyInput; std::unique_ptr<Input> keyboardInput; try { // Create manager systemLogStream.Event("Creating GxApi Manager..."); gxapiMgr.reset(new GxapiManager()); auto adapters = gxapiMgr->EnumerateAdapters(); std::string cardList; for (auto adapter : adapters) { cardList += "\n"; cardList += adapter.name; } systemLogStream.Event("Available graphics cards:" + cardList); // Create graphics api int device = 0; if (argc == 3 && argv[1] == std::string("--device") && isdigit(argv[2][0])) { device = argv[2][0] - '0'; // works for single digits, good enough, lol } systemLogStream.Event("Creating GraphicsApi..."); gxapi.reset(gxapiMgr->CreateGraphicsApi(adapters[device].adapterId)); std::stringstream ss; ss << "Using graphics card: " << adapters[device].name; systemLogStream.Event(ss.str()); // Create graphics engine systemLogStream.Event("Creating Graphics Engine..."); GraphicsEngineDesc desc; desc.fullScreen = false; desc.graphicsApi = gxapi.get(); desc.gxapiManager = gxapiMgr.get(); desc.width = window.GetClientSize().x; desc.height = window.GetClientSize().y; desc.targetWindow = window.GetNativeHandle(); desc.logger = &logger; engine.reset(new GraphicsEngine(desc)); // Load graphics pipeline std::string pipelineFileName = SelectPipeline(gxapi.get()); std::string exeDir = System::GetExecutableDir(); std::ifstream pipelineFile(INL_PIPELINE_DIRECTORY "\\" + pipelineFileName); if (!pipelineFile.is_open()) { throw FileNotFoundException("Failed to open pipeline JSON."); } std::string pipelineDesc((std::istreambuf_iterator<char>(pipelineFile)), std::istreambuf_iterator<char>()); engine->LoadPipeline(pipelineDesc); // Create mini world qcWorld.reset(new QCWorld(engine.get())); // Create input handling inputHandler = std::make_unique<InputHandler>(qcWorld.get()); window.OnResize += Delegate<void(ResizeEvent)>{ &InputHandler::OnResize, inputHandler.get() }; auto joysticks = Input::GetDeviceList(eInputSourceType::JOYSTICK); if (!joysticks.empty()) { joyInput = std::make_unique<Input>(joysticks.front().id); joyInput->SetQueueMode(eInputQueueMode::QUEUED); joyInput->OnJoystickMove += Delegate<void(JoystickMoveEvent)>{ &InputHandler::OnJoystickMove, inputHandler.get() }; } auto keyboards = Input::GetDeviceList(eInputSourceType::KEYBOARD); if (!keyboards.empty()) { keyboardInput = std::make_unique<Input>(keyboards.front().id); keyboardInput->SetQueueMode(eInputQueueMode::QUEUED); keyboardInput->OnKeyboard += Delegate<void(KeyboardEvent)>{ &InputHandler::OnKey, inputHandler.get() }; } window.OnResize += [&engine, &qcWorld](ResizeEvent evt) { engine->SetScreenSize(evt.clientSize.x, evt.clientSize.y); qcWorld->ScreenSizeChanged(evt.clientSize.x, evt.clientSize.y); }; logger.Flush(); } catch (Exception& ex) { errorMessage = std::string("Error creating GraphicsEngine: ") + ex.what() + "\n" + ex.StackTraceStr(); systemLogStream.Event(errorMessage); logger.Flush(); } catch (std::exception& ex) { errorMessage = std::string("Error creating GraphicsEngine: ") + ex.what(); systemLogStream.Event(errorMessage); logger.Flush(); } if (!qcWorld) { return 0; } // Main rendering loop Timer timer; timer.Start(); double frameTime = 0.05, frameRateUpdate = 0; std::vector<double> frameTimeHistory; float avgFps = 0; auto CaptionHandler = [&window](Vec2i cursorPos) { Vec2i size = window.GetSize(); RectI rc; rc.top = 5; rc.bottom = 50; rc.right = size.x - 5; rc.left = size.x - 50; if (rc.IsPointInside(cursorPos)) return eWindowCaptionButton::CLOSE; rc.Move({ -50, 0 }); if (rc.IsPointInside(cursorPos)) return eWindowCaptionButton::MAXIMIZE; rc.Move({ -50, 0 }); if (rc.IsPointInside(cursorPos)) return eWindowCaptionButton::MINIMIZE; if (cursorPos.y < 55) { return eWindowCaptionButton::BAR; } return eWindowCaptionButton::NONE; }; //window.SetBorderless(true); //window.SetCaptionButtonHandler(CaptionHandler); while (!window.IsClosed()) { inputHandler->SetFocused(window.IsFocused()); window.CallEvents(); if (joyInput) { joyInput->CallEvents(); } if (keyboardInput) { keyboardInput->CallEvents(); } try { // Update world qcWorld->UpdateWorld(frameTime); qcWorld->RenderWorld(frameTime); // Calculate elapsed time for frame. frameTime = timer.Elapsed(); timer.Reset(); // Calculate average framerate frameRateUpdate += frameTime; if (frameRateUpdate > 0.5) { frameRateUpdate = 0; double avgFrameTime = 0.0; for (auto v : frameTimeHistory) { avgFrameTime += v; } avgFrameTime /= frameTimeHistory.size(); avgFps = 1 / avgFrameTime; frameTimeHistory.clear(); } frameTimeHistory.push_back(frameTime); // Set info text as window title unsigned width, height; engine->GetScreenSize(width, height); std::string title = "Graphics Engine Test | " + std::to_string(width) + "x" + std::to_string(height) + " | FPS=" + std::to_string((int)avgFps); window.SetTitle(title); } catch (Exception& ex) { std::stringstream trace; trace << "Graphics engine error:" << ex.what() << "\n"; ex.PrintStackTrace(trace); systemLogStream.Event(trace.str()); PostQuitMessage(0); } catch (std::exception& ex) { systemLogStream.Event(std::string("Graphics engine error: ") + ex.what()); logger.Flush(); PostQuitMessage(0); } } cout << "Shutting down." << endl; return 0; }