void PostRouteFileHandler::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) { if (header.has("Content-Type")) { std::string contentType = header["Content-Type"]; if (!_route.settings().getValidContentTypes().empty() && !isContentTypeValid(contentType)) { ofLogError("PostRouteFileHandler::handlePart") << "Invalid content type: " << contentType; return; // reject } } else { ofLogError("PostRouteFileHandler::handlePart") << "No Content-Type header."; return; } // Is this an uploaded file and are we allowing files to be uploaded? if (header.has("Content-Disposition") && _route.settings().getMaximumFileUploadSize() > 0) { std::string contentDisposition = header["Content-Disposition"]; Poco::Net::NameValueCollection parameters; Poco::Net::MessageHeader::splitParameters(contentDisposition.begin(), contentDisposition.end(), parameters); std::string formFileName = parameters.get("filename", ""); std::string formFieldName = parameters.get("name", ""); if (!formFileName.empty()) { try { // std::stringstream ss; std::filesystem::path uploadFolder = _route.settings().getUploadFolder(); std::filesystem::path uniqueFilename = Poco::UUIDGenerator::defaultGenerator().createOne().toString(); std::filesystem::path originalFilename = formFileName; //std::filesystem::extension(originalFilename) std::filesystem::path p = uploadFolder; p /= uniqueFilename; p += std::filesystem::extension(originalFilename); // ss << _route.settings().getUploadFolder(); // ss << "/"; // ss << Poco::UUIDGenerator::defaultGenerator().createOne().toString(); // ss << "."; // ss << Poco::Path(formFileName).getExtension(); std::string newFilename = ofToDataPath(p, true); ofFile file(newFilename, ofFile::WriteOnly, true); Poco::Net::MediaType contentType(header["Content-Type"]); PostUploadEventArgs args(_evt, _postId, formFieldName, formFileName, newFilename, contentType, 0, PostUploadEventArgs::UPLOAD_STARTING); ofNotifyEvent(_route.events.onHTTPUploadEvent, args, &_route); ofLogVerbose("PostRouteFileHandler::handlePart") << "Writing file to absolute path : " << file.getAbsolutePath(); // The section below is from StreamCopier::copyStream, // and might be used for upload progress feedback Poco::Buffer<char> buffer(_route.settings().getWriteBufferSize()); stream.read(buffer.begin(), _route.settings().getWriteBufferSize()); unsigned long long sz = 0; unsigned long long n = stream.gcount(); while (n > 0) { if (sz > _route.settings().getMaximumFileUploadSize()) { ofLogError("PostRouteFileHandler::handlePart") << "File upload size exceeded. Removing file."; file.close(); ofFile::removeFile(newFilename, false); return; } sz += n; file.write(buffer.begin(), n); if (stream && file) { stream.read(buffer.begin(), _route.settings().getWriteBufferSize()); n = stream.gcount(); } else { n = 0; } PostUploadEventArgs uploadArgs(_evt, _postId, formFieldName, formFileName, newFilename, contentType, sz, PostUploadEventArgs::UPLOAD_PROGRESS); ofNotifyEvent(_route.events.onHTTPUploadEvent, uploadArgs, &_route); } file.close(); PostUploadEventArgs finishedArgs(_evt, _postId, formFieldName, formFileName, newFilename, contentType, sz, PostUploadEventArgs::UPLOAD_FINISHED); ofNotifyEvent(_route.events.onHTTPUploadEvent, finishedArgs, &_route); } catch (const Poco::Exception& exc) { ofLogError("PostRouteFileHandler::handlePart") << exc.displayText(); } catch (const std::exception& exc) { ofLogError("PostRouteFileHandler::handlePart") << exc.what(); } catch ( ... ) { ofLogError("PostRouteFileHandler::handlePart") << "Uncaught thread exception: Unknown exception."; } } else { ofLogError("PostRouteFileHandler::handlePart") << "No filename in header."; } } }
void Editbox::onCharacter(TextEventArgs& e) { // NB: We are not calling the base class handler here because it propagates // inputs back up the window hierarchy, whereas, as a consumer of input // events, we want such propagation to cease with us regardless of whether // we actually handle the event. // fire event. fireEvent(EventCharacterKey, e, Window::EventNamespace); // only need to take notice if we have focus if (e.handled == 0 && hasInputFocus() && !isReadOnly() && getFont()->isCodepointAvailable(e.d_character)) { // backup current text String tmp(getText()); UndoHandler::UndoAction undoSelection; undoSelection.d_type = UndoHandler::UAT_DELETE; undoSelection.d_startIdx = getSelectionStart(); undoSelection.d_text = tmp.substr(getSelectionStart(), getSelectionLength()); tmp.erase(getSelectionStart(), getSelectionLength()); // if there is room if (tmp.length() < d_maxTextLen) { UndoHandler::UndoAction undo; undo.d_type = UndoHandler::UAT_INSERT; undo.d_startIdx = getSelectionStart(); undo.d_text = e.d_character; tmp.insert(getSelectionStart(), 1, e.d_character); if (handleValidityChangeForString(tmp)) { // erase selection using mode that does not modify getText() // (we just want to update state) eraseSelectedText(false); // advance caret (done first so we can "do stuff" in event // handlers!) d_caretPos++; // set text to the newly modified string setText(tmp); // char was accepted into the Editbox - mark event as handled. ++e.handled; d_undoHandler->addUndoHistory(undo); if (getSelectionLength() > 0) d_undoHandler->addUndoHistory(undoSelection); } } else { // Trigger text box full event WindowEventArgs args(this); onEditboxFullEvent(args); } } // event was (possibly) not handled }
NSCAPI::nagiosReturn CheckWMI::commandLineExec(const int target_mode, const std::string &command, const std::list<std::string> &arguments, std::string &result) { try { if (command == "wmi" || command == "help" || command.empty()) { namespace po = boost::program_options; std::string query, ns, user, password, list_cls, list_inst; std::string computer; bool simple; int limit = -1; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Show help screen") ("select,s", po::value<std::string>(&query), "Execute a query") ("simple", "Use simple format") ("list-classes", po::value<std::string>(&list_cls)->implicit_value(""), "list all classes of a given type") ("list-instances", po::value<std::string>(&list_inst), "list all instances of a given type") ("list-ns", "list all name spaces") ("list-all-ns", "list all name spaces recursively") ("limit,l", po::value<int>(&limit), "Limit number of rows") ("namespace,n", po::value<std::string>(&ns)->default_value("root\\cimv2"), "Namespace") ("computer,c", po::value<std::string>(&computer), "A remote computer to connect to ") ("user,u", po::value<std::string>(&user), "The user for the remote computer") ("password,p", po::value<std::string>(&password), "The password for the remote computer") ; boost::program_options::variables_map vm; if (command == "help") { std::stringstream ss; ss << "wmi Command line syntax:" << std::endl; ss << desc; result = ss.str(); return NSCAPI::exec_return_codes::returnOK; } std::vector<std::string> args(arguments.begin(), arguments.end()); po::parsed_options parsed = po::basic_command_line_parser<char>(args).options(desc).run(); po::store(parsed, vm); po::notify(vm); if (vm.count("help") || (vm.count("select") == 0 && vm.count("list-classes") == 0 && vm.count("list-instances") == 0 && vm.count("list-ns") == 0 && vm.count("list-all-ns") == 0)) { std::stringstream ss; ss << "CheckWMI Command line syntax:" << std::endl; ss << desc; result = ss.str(); return NSCAPI::exec_return_codes::returnOK; } simple = vm.count("simple") > 0; ns = build_namespace(ns, computer); if (vm.count("select")) { row_type headers; std::vector<std::size_t> widths; std::size_t count = 0; try { wmi_impl::query wmiQuery(query, ns, user, password); std::list<std::string> cols = wmiQuery.get_columns(); count = cols.size(); BOOST_FOREACH(const std::string &col, cols) { headers.push_back(col); widths.push_back(col.size()); } result = render(headers, widths, wmiQuery.execute()); return NSCAPI::exec_return_codes::returnOK; } catch (const wmi_impl::wmi_exception &e) { result += "ERROR: " + e.reason(); return NSCAPI::exec_return_codes::returnERROR; } } else if (vm.count("list-classes")) {
bool StressTest::OpenFile(const WCHAR *fileName) { wprintf(L"%s\n", fileName); fflush(stdout); LoadArgs args(fileName); args.forceReuse = rand() % 3 != 1; WindowInfo *w = LoadDocument(args); if (!w) return false; if (w == win) { // WindowInfo reused if (!win->IsDocLoaded()) return false; } else if (!w->IsDocLoaded()) { // new WindowInfo CloseWindow(w, false); return false; } // transfer ownership of stressTest object to a new window and close the // current one assert(this == win->stressTest); if (w != win) { if (win->IsDocLoaded()) { // try to provoke a crash in RenderCache cleanup code ClientRect rect(win->hwndFrame); rect.Inflate(rand() % 10, rand() % 10); SendMessage(win->hwndFrame, WM_SIZE, 0, MAKELONG(rect.dx, rect.dy)); if (win->AsFixed()) win->cbHandler->RequestRendering(1); win->RepaintAsync(); } WindowInfo *toClose = win; w->stressTest = win->stressTest; win->stressTest = nullptr; win = w; CloseWindow(toClose, false); } if (!win->IsDocLoaded()) return false; win->ctrl->SetDisplayMode(DM_CONTINUOUS); win->ctrl->SetZoomVirtual(ZOOM_FIT_PAGE); win->ctrl->GoToFirstPage(); if (win->tocVisible || gGlobalPrefs->showFavorites) SetSidebarVisibility(win, win->tocVisible, gGlobalPrefs->showFavorites); currPage = pageRanges.At(0).start; win->ctrl->GoToPage(currPage, false); currPageRenderTime.Start(); ++filesCount; pageForSearchStart = (rand() % win->ctrl->PageCount()) + 1; // search immediately in single page documents if (1 == pageForSearchStart) { // use text that is unlikely to be found, so that we search all pages win::SetText(win->hwndFindBox, L"!z_yt"); FindTextOnThread(win, FIND_FORWARD, true); } int secs = SecsSinceSystemTime(stressStartTime); ScopedMem<WCHAR> tm(FormatTime(secs)); ScopedMem<WCHAR> s(str::Format(L"File %d: %s, time: %s", filesCount, fileName, tm)); win->ShowNotification(s, NOS_PERSIST, NG_STRESS_TEST_SUMMARY); return true; }
static EncodedJSValue JSC_HOST_CALL constructWithDateConstructor(ExecState* exec) { ArgList args(exec); return JSValue::encode(constructDate(exec, asInternalFunction(exec->callee())->globalObject(), args)); }
/*///////////////////////////////////////////////////////////////*/ int cmdline_args (KConfig K, int argc, char *argv[]) { const char* thisfunction = "cmdline_args"; int i; if (K->genotypes != 1) { not_implemented(thisfunction, "genotypes != 1"); } enum { o_help, o_progress, o_generation_cutoff, o_nested, o_unnested, o_U_mutation, o_s_selection, o_h_dominance, o_S_selfing_rate, o_A_apomixis_rate, o_truncate, o_no_lethal, o_table_heading_only, o_table, o_load_savefile, o_load_savefile_name, o_save_savefile, o_save_savefile_name, }; CSimpleOpt::SOption K_options[] = { { o_help, "-?", SO_NONE }, { o_help, "--help", SO_NONE }, { o_progress, "--progress", SO_REQ_SEP }, { o_generation_cutoff, "--generation-cutoff", SO_REQ_SEP }, { o_nested, "--nested", SO_NONE }, { o_unnested, "--unnested", SO_NONE }, { o_U_mutation, "-U", SO_REQ_SEP }, { o_s_selection, "-s", SO_REQ_SEP }, { o_h_dominance, "-h", SO_REQ_SEP }, { o_S_selfing_rate, "-S", SO_REQ_SEP }, { o_A_apomixis_rate, "-A", SO_REQ_SEP }, { o_truncate, "--truncate", SO_NONE }, { o_no_lethal, "--no-lethal-shortcut", SO_NONE }, { o_table_heading_only, "--table-heading-only", SO_NONE }, { o_table, "--table", SO_NONE }, { o_load_savefile, "--load-savefile", SO_NONE }, { o_load_savefile_name, "--load-savefile-name", SO_REQ_SEP }, { o_save_savefile, "--save-savefile", SO_NONE }, { o_save_savefile_name, "--save-savefile-name", SO_REQ_SEP }, SO_END_OF_OPTIONS }; CSimpleOpt args(argc, argv, K_options); while (args.Next()) { if (args.LastError() != SO_SUCCESS) { cerr << "invalid argument '" << args.OptionText() << "'" << endl; cmdline_usage(K); exit(0); } switch (args.OptionId()) { case o_help: cmdline_usage(K); exit(0); break; case o_progress: K->progress = atol(args.OptionArg()); break; case o_generation_cutoff: GENERATION_CUTOFF = atoi(args.OptionArg()); break; case o_nested: cerr << "Unnested simulation, option invalid '" << args.OptionText() << "'" << endl; break; exit(1); case o_unnested: /* ignored here */ break; case o_U_mutation: K->U = atof(args.OptionArg()); break; case o_s_selection: K->fit_s = atof(args.OptionArg()); break; case o_h_dominance: K->fit_h = atof(args.OptionArg()); break; case o_S_selfing_rate: K->S[0] = atof(args.OptionArg()); break; case o_A_apomixis_rate: K->A[0] = atof(args.OptionArg()); break; case o_truncate: K->option_truncate = 1; break; case o_no_lethal: K->option_nolethal = 1; break; case o_table_heading_only: stats_print_table_heading(K); exit(0); break; case o_table: K->option_table = 1; break; case o_load_savefile: K->load_savefile = 1; break; case o_load_savefile_name: K->load_savefile_name = args.OptionArg(); break; case o_save_savefile: K->save_savefile = 1; break; case o_save_savefile_name: K->save_savefile_name = args.OptionArg(); break; default: cerr << "Invalid option '" << args.OptionText() << "'" << endl; exit(1); break; /* } else if (!strcmp( argv[i], "-inita1" )) { // initial frequency of allele 1 INITIAL_A1 = (double)atof( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-n" )) { N = atol( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-fecm" )) { FECM = atol( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-fecf" )) { FECF = atol( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-gens" )) { GENS = atol( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-selmod" )) { selection_model = atoi( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-popmod" )) { selection_model = atoi( argv[i+1] ); i += 2; } else if (!strcmp( argv[i], "-selfsurv" )) { self_survival = (double)atof( argv[i+1] ); i += 2; */ } } return 0; }
int main(int argc, char *argv[]) { #ifdef _WIN32 AllocConsole(); #endif vector<string> args(argv,argv+argc); // initialize Zoidcom scoped_ptr<ZoidCom> zcom(new ZoidCom(zoidcom_logger)); if (!zcom || !zcom->Init()) { throw std::runtime_error("Unable to initialize ZoidCom!"); } zcom->setLogLevel(0); intrusive_ptr<IrrlichtDevice> device; if(args.size() > 1 && args[1] == "server") { // Skip graphical interface // Dedicated server uses 'null' graphics device.. device = intrusive_ptr<IrrlichtDevice>( createDevice(video::EDT_NULL, core::dimension2d<u32>(640,480), 16, false, true, true), false /* don't addref */ ); device->getLogger()->setLogLevel(ELL_INFORMATION); addHeightMapLoader(get_pointer(device)); // Start server, run game instances in loop while(true) { std::cout << "Loading server instance..."; scoped_ptr<Sarona::PhysWorld> serverworld( new Sarona::PhysWorld(get_pointer(device)) ); serverworld->SetLevel("testlevel/"); serverworld->Bind(9192, false); serverworld->Start(); serverworld->Wait(); } } else { // Display main menu, graphical interface needed device = intrusive_ptr<IrrlichtDevice>( createDevice(video::EDT_OPENGL, core::dimension2d<u32>(800,600), 16, false, true, true), false /* don't addref */ ); device->getLogger()->setLogLevel(ELL_WARNING); addHeightMapLoader(get_pointer(device)); Sarona::GameMenu menu(get_pointer(device)); bool local_game = true; bool server = true; if(args.size()>1) local_game = server = args[1]!="client"; // Run the main menu, let user decide what to do //menu.Run(local_game, server); scoped_ptr<Sarona::NetWorld> clientworld; scoped_ptr<Sarona::PhysWorld> serverworld; if(server) { serverworld.reset(new Sarona::PhysWorld(get_pointer(device))); serverworld->SetLevel("testlevel/"); serverworld->Bind(9192, local_game); serverworld->Start(); std::cout << "Server started" << std::endl; } clientworld.reset(new Sarona::NetWorld(get_pointer(device))); clientworld->SetLevel("testlevel/"); clientworld->Connect("localhost:9192", local_game); // The main thread has to run the irrlicht loop, apparently.. clientworld->Loop(); if(serverworld) { serverworld->Shutdown(); serverworld->Wait(); } } return 0; }
void JavaCalls::call_static(JavaValue* result, KlassHandle klass, Symbol* name, Symbol* signature, Handle arg1, TRAPS) { JavaCallArguments args(arg1); // One oop argument call_static(result, klass, name, signature, &args, CHECK); }
CmdLine::CmdLine(int aCnt, char **aVal, bool aUseDefaultsIfNoArguments) { // To support debugging these values are set if no arguments on the command line if(aUseDefaultsIfNoArguments && aCnt < 2 && getenv("CFP_DEBUG")) { #ifdef _MSC_VER mPoscarFile = "C:/mv/cfp/NewCrystalFpLib/gaas-8at_new.log"; mEnergyFile = "C:/mv/cfp/NewCrystalFpLib/gaas-8at_new.log.energy"; mCheckpointDir = "C:/mv/cfp/NewCrystalFpLib/test"; #else mPoscarFile = "/users/mvalle/cfp/NewCrystalFpLib/gaas-8at_new.log"; mEnergyFile = "/users/mvalle/cfp/NewCrystalFpLib/gaas-8at_new.log.energy"; mCheckpointDir = "/users/mvalle/cfp/NewCrystalFpLib/test"; #endif mVerboseLevel = 2; mStartStep = 3; mEndStep = 20; mEnergyIsPerAtom = false; mEnergyThreshold = 0; mHasEnergyThreshold = false; mHasReverseEnergyThreshold = false; mCutoffDistance = 0; mIsNanocluster = false; mDiffrBinSize = 0.05F; mDiffrPeakSize = 0.02F; mForcedFpLen = 0; mOverwriteChkptDir = true; mListFingerprintingMethods = false; mFingerprintingMethod = 0; mListDistanceMethods = false; mDistanceMethod = 0; mListGroupingMethods = false; mGroupingMethod = 0; mK = 2; mMaxDistanceForGrouping = 0.01F; mSummaryFile = 0; mFldOutFp = 0; mFldOutDist = 0; mSortedDistFile = 0; mMapFile = 0; mRemoveDuplicates = false; mListAnalysisMethods = false; mAnalysisMethod = CmdLine::NO_METHOD_SELECTED; mAnalysisMethod2 = CmdLine::NO_METHOD_SELECTED; mAnalysisFile = 0; mCreateScatterplot = false; mScatterplotFile = 0; mDiagnosticFile = 0; mSerializeFile = 0; return; } // Initialize options values mVerboseLevel = 0; mPoscarFile = 0; mEnergyFile = 0; mStartStep = 1; mEndStep = 0; mEnergyIsPerAtom = true; mEnergyThreshold = 0.0F; mHasEnergyThreshold = false; mHasReverseEnergyThreshold = false; mCutoffDistance = 0; mIsNanocluster = false; mDiffrBinSize = 0.05F; mDiffrPeakSize = 0.02F; mForcedFpLen = 0; mCheckpointDir = 0; mOverwriteChkptDir = false; mListFingerprintingMethods = false; mFingerprintingMethod = CmdLine::NO_METHOD_SELECTED; mListDistanceMethods = false; mDistanceMethod = CmdLine::NO_METHOD_SELECTED; mListGroupingMethods = false; mGroupingMethod = CmdLine::NO_METHOD_SELECTED; mK = 0; mMaxDistanceForGrouping = 0.01F; mSummaryFile = 0; mFldOutFp = 0; mFldOutDist = 0; mSortedDistFile = 0; mMapFile = 0; mRemoveDuplicates = false; mListAnalysisMethods = false; mAnalysisMethod = CmdLine::NO_METHOD_SELECTED; mAnalysisMethod2 = CmdLine::NO_METHOD_SELECTED; mAnalysisFile = 0; mCreateScatterplot = false; mScatterplotFile = 0; mDiagnosticFile = 0; mSerializeFile = 0; // Setup the command line parser enum { OPT_VERSION, OPT_VERBOSE, OPT_HELP, OPT_TYPES, OPT_MAX_STEP, OPT_MIN_STEP, OPT_ENERGY_PER_STR, OPT_THRESH, OPT_REV_THRESH, OPT_CUTOFF_DIST, OPT_NANO_CLUST, OPT_BIN_SIZE, OPT_PEAK_SIZE, OPT_FORCE_DIM, OPT_CHKPT_DIR, OPT_IGNORE_CHKPT, OPT_FP_METHOD, OPT_DIST_METHOD, OPT_GROUPING_METHOD, OPT_GROUPING_THRESH, OPT_K_VALUE, OPT_SUMMARY, OPT_FLD_FP, OPT_FLD_DIST, OPT_DIST_DISTRIB, OPT_REMOVE_DUPL, OPT_ANALYSIS, OPT_ANALYSIS_FILE, OPT_ANALYSIS_PARAM, OPT_SCATTER, OPT_SCATTER_FILE, OPT_SCATTER_PARAM, OPT_DIAGNOSTIC_FILE, OPT_SERIALIZE }; CSimpleOpt::SOption parser_options[] = { { OPT_VERSION, "--version", SO_NONE, "Library and driver version" }, { OPT_VERBOSE, "-v", SO_OPT, "Verbose level (if no argument, defaults to 1)" }, { OPT_VERBOSE, "--verbose", SO_OPT, "" }, { OPT_HELP, "-?", SO_NONE, "This help" }, { OPT_HELP, "-h", SO_NONE, "" }, { OPT_HELP, "--help", SO_NONE, "" }, { OPT_TYPES, "-t", SO_REQ_SEP, "List of chemical elements to be assigned to POSCAR atoms" }, { OPT_TYPES, "--elements", SO_REQ_SEP, "" }, { OPT_MAX_STEP, "-es", SO_REQ_SEP, "Last step to load (default: all)" }, { OPT_MAX_STEP, "--max-step", SO_REQ_SEP, ""}, { OPT_MAX_STEP, "--end-step", SO_REQ_SEP, ""}, { OPT_MIN_STEP, "-ss", SO_REQ_SEP, "First step to load (default: first)" }, { OPT_MIN_STEP, "--start-step", SO_REQ_SEP, ""}, { OPT_ENERGY_PER_STR, "-et", SO_NONE, "Energy from file is per structure, not per atom" }, { OPT_ENERGY_PER_STR, "--energy-per-structure", SO_NONE, "" }, { OPT_THRESH, "-e", SO_REQ_SEP, "Energy threshold" }, { OPT_THRESH, "--energy-threshold", SO_REQ_SEP, "" }, { OPT_REV_THRESH, "-r", SO_REQ_SEP, "Threshold from minimum energy" }, { OPT_REV_THRESH, "--threshold-from-min", SO_REQ_SEP, "" }, { OPT_CUTOFF_DIST, "-c", SO_REQ_SEP, "Fingerprint forced cutoff distance" }, { OPT_CUTOFF_DIST, "--cutoff-distance", SO_REQ_SEP, "" }, { OPT_NANO_CLUST, "-n", SO_NONE, "The structures are nanoclusters, not crystals" }, { OPT_NANO_CLUST, "--nano-clusters", SO_NONE, "" }, { OPT_NANO_CLUST, "--nanoclusters", SO_NONE, "" }, { OPT_BIN_SIZE, "-b", SO_REQ_SEP, "Bin size for the pseudo-diffraction methods" }, { OPT_BIN_SIZE, "--bin-size", SO_REQ_SEP, "" }, { OPT_PEAK_SIZE, "-p", SO_REQ_SEP, "Peak smearing size" }, { OPT_PEAK_SIZE, "--peak-size", SO_REQ_SEP, "" }, { OPT_FORCE_DIM, "-x", SO_REQ_SEP, "Force to this value the total length of the fingerprint (valid only on reloading from checkpoint)" }, { OPT_FORCE_DIM, "--force-dim", SO_REQ_SEP, "" }, { OPT_CHKPT_DIR, "-chk", SO_REQ_SEP, "Set fingerprint checkpoint directory" }, { OPT_CHKPT_DIR, "--checkpoint-dir", SO_REQ_SEP, "" }, { OPT_IGNORE_CHKPT, "-i", SO_NONE, "Ignore previous checkpoint" }, { OPT_IGNORE_CHKPT, "--ignore-checkpoint", SO_NONE, "" }, { OPT_FP_METHOD, "-f", SO_REQ_SEP, "Compute fingerprints using the given method ('help' to list all methods)" }, { OPT_FP_METHOD, "--fingerprint-method", SO_REQ_SEP, "" }, { OPT_DIST_METHOD, "-d", SO_REQ_SEP, "Compute distances using the given method ('help' to list all methods)"}, { OPT_DIST_METHOD, "--distance-method", SO_REQ_SEP, ""}, { OPT_GROUPING_METHOD, "-g", SO_REQ_SEP, "Grouping method ('help' to list all methods)" }, { OPT_GROUPING_METHOD, "--grouping-method", SO_REQ_SEP, "" }, { OPT_GROUPING_THRESH, "-gt", SO_REQ_SEP, "Grouping max distance threshold" }, { OPT_GROUPING_THRESH, "--grouping-threshold", SO_REQ_SEP, "" }, { OPT_K_VALUE, "-k", SO_REQ_SEP, "K value needed by some grouping algorithm" }, { OPT_K_VALUE, "--k", SO_REQ_SEP, "" }, { OPT_SUMMARY, "-s", SO_REQ_SEP, "Output a summary file to be used by another program" }, { OPT_SUMMARY, "--summary", SO_REQ_SEP, "" }, { OPT_FLD_FP, "-fo", SO_REQ_SEP, "Output fingerprints in FLD AVS format" }, { OPT_FLD_FP, "--fld-fingerprints", SO_REQ_SEP, "" }, { OPT_FLD_DIST, "-do", SO_REQ_SEP, "Output distance matrix in FLD AVS format" }, { OPT_FLD_DIST, "--fld-distances", SO_REQ_SEP, "" }, { OPT_DIST_DISTRIB, "-sd", SO_REQ_SEP, "Output distances in increasing order" }, { OPT_DIST_DISTRIB, "--sorted-distances", SO_REQ_SEP, "" }, { OPT_REMOVE_DUPL, "-rd", SO_OPT, "Remove duplicates substituting them with a representative structure and writing the map of indices to file" }, { OPT_REMOVE_DUPL, "--remove-dupl", SO_OPT, "" }, { OPT_ANALYSIS, "-a", SO_REQ_SEP, "Create a chart for the given analysis method (can be: ax,ay or ax)" }, { OPT_ANALYSIS, "--analysis", SO_REQ_SEP, "" }, { OPT_ANALYSIS_FILE, "-af", SO_REQ_SEP, "File output for analysis" }, { OPT_ANALYSIS_FILE, "--analysis-file", SO_REQ_SEP, "" }, { OPT_ANALYSIS_PARAM, "-ap", SO_MULTI, "Pass one parameter for the given analysis method as: code value (code: bins, part, idx)" }, { OPT_ANALYSIS_PARAM, "--analysis-param", SO_MULTI, "" }, { OPT_SCATTER, "-sc", SO_NONE, "Create a scatterplot" }, { OPT_SCATTER, "--scatterplot", SO_NONE, "" }, { OPT_SCATTER_FILE, "-sf", SO_REQ_SEP, "File output for scatterplot" }, { OPT_SCATTER_FILE, "--scatterplot-file", SO_REQ_SEP, "" }, { OPT_DIAGNOSTIC_FILE, "-df", SO_REQ_SEP, "File output for diagnostic chart assocated to the scatterplot" }, { OPT_DIAGNOSTIC_FILE, "--diagnostic-file", SO_REQ_SEP, "" }, { OPT_SCATTER_PARAM, "-sp", SO_MULTI, "Pass one parameter for the scatterplot as: code value (code: retry, energy, iterations, kind, diagnostic, timestep, mass, stiffness, damping, perturb, bins, wobble)" }, { OPT_SCATTER_PARAM, "--scatterplot-param", SO_MULTI, "" }, { OPT_SERIALIZE, "-sa", SO_REQ_SEP, "Save the current CrystalFp class to the given file" }, { OPT_SERIALIZE, "--save-file", SO_REQ_SEP, "" }, SO_END_OF_OPTIONS }; // Setup the usage string (to be concatenated with argv[0]) const char* usage_msg = " [options] POSCARfile [ENERGIESfile]"; // Declare our options parser, pass in the arguments from main as well as our array of valid options. CSimpleOpt args(aCnt, aVal, parser_options, SO_O_NOSLASH|SO_O_EXACT); // While there are arguments left to process while(args.Next()) { if(args.LastError() == SO_OPT_INVALID) { std::cerr << "Error: " << getLastErrorText(args) << ": " << args.OptionText() << std::endl; throw CmdLineFatal(); } if(args.LastError() != SO_SUCCESS) { std::cerr << "Error: " << getLastErrorText(args) << " for: " << args.OptionText() << std::endl; throw CmdLineFatal(); } int tmp; const char* list_methods_tmp; char **arg_param; switch(args.OptionId()) { case OPT_VERSION: // Get the last commit date from Git using: git log -n 1 --pretty=format:"%ci" std::cerr << "CrystalFp library and driver: " << "2012-10-19 12:59:56 +0200" << std::endl; throw CmdLineSuccess(); case OPT_VERBOSE: if(args.OptionArg()) { tmp = atoi(args.OptionArg()); if(tmp < 0) std::cerr << "Invalid value for " << args.OptionText() << " using 0" << std::endl; mVerboseLevel = static_cast<unsigned int>(tmp); } else mVerboseLevel = 1; break; case OPT_HELP: std::cerr << "Usage:" << std::endl; std::cerr << " " << aVal[0] << usage_msg << std::endl << std::endl; showHelp(parser_options); throw CmdLineSuccess(); case OPT_TYPES: convertAtomSymbolsToZ(args.OptionArg(), mAtomZ); break; case OPT_MIN_STEP: tmp = atoi(args.OptionArg()); if(tmp < 1) {std::cerr << "Invalid value for " << args.OptionText() << " using 1" << std::endl; tmp = 1;} mStartStep = static_cast<unsigned int>(tmp); break; case OPT_MAX_STEP: tmp = atoi(args.OptionArg()); if(tmp < 1) {std::cerr << "Invalid value for " << args.OptionText() << " using 0 (all steps)" << std::endl; tmp = 0;} mEndStep = static_cast<unsigned int>(tmp); break; case OPT_ENERGY_PER_STR: mEnergyIsPerAtom = false; break; case OPT_THRESH: mEnergyThreshold = (float)atof(args.OptionArg()); mHasEnergyThreshold = true; break; case OPT_REV_THRESH: mEnergyThreshold = (float)atof(args.OptionArg()); mHasReverseEnergyThreshold = true; break; case OPT_CUTOFF_DIST: mCutoffDistance = (float)atof(args.OptionArg()); break; case OPT_NANO_CLUST: mIsNanocluster = true; break; case OPT_BIN_SIZE: mDiffrBinSize = (float)atof(args.OptionArg()); break; case OPT_PEAK_SIZE: mDiffrPeakSize = (float)atof(args.OptionArg()); break; case OPT_FORCE_DIM: tmp = atoi(args.OptionArg()); if(tmp < 0) {std::cerr << "Invalid value for " << args.OptionText() << " ignoring" << std::endl; tmp = 0;} mForcedFpLen = static_cast<unsigned int>(tmp); break; case OPT_CHKPT_DIR: mCheckpointDir = args.OptionArg(); break; case OPT_IGNORE_CHKPT: mOverwriteChkptDir = true; break; case OPT_FP_METHOD: list_methods_tmp = args.OptionArg(); if(!strcasecmp(list_methods_tmp, "help")) mListFingerprintingMethods = true; else mFingerprintingMethod = atoi(list_methods_tmp); break; case OPT_DIST_METHOD: list_methods_tmp = args.OptionArg(); if(!strcasecmp(list_methods_tmp, "help")) mListDistanceMethods = true; else mDistanceMethod = atoi(list_methods_tmp); break; case OPT_GROUPING_METHOD: list_methods_tmp = args.OptionArg(); if(!strcasecmp(list_methods_tmp, "help")) mListGroupingMethods = true; else mGroupingMethod = atoi(list_methods_tmp); break; case OPT_GROUPING_THRESH: mMaxDistanceForGrouping = (float)atof(args.OptionArg()); break; case OPT_K_VALUE: tmp = atoi(args.OptionArg()); if(tmp < 0) {std::cerr << "Invalid value for " << args.OptionText() << " ignoring" << std::endl; tmp = 0;} mK = static_cast<unsigned int>(tmp); break; case OPT_SUMMARY: mSummaryFile = args.OptionArg(); break; case OPT_FLD_FP: mFldOutFp = args.OptionArg(); break; case OPT_FLD_DIST: mFldOutDist = args.OptionArg(); break; case OPT_DIST_DISTRIB: mSortedDistFile = args.OptionArg(); break; case OPT_REMOVE_DUPL: if(args.OptionArg()) mMapFile = args.OptionArg(); mRemoveDuplicates = true; break; case OPT_ANALYSIS: list_methods_tmp = args.OptionArg(); if(!strcasecmp(list_methods_tmp, "help")) { mListAnalysisMethods = true; } else { mAnalysisMethod = atoi(list_methods_tmp); int i; for(i=0; isdigit(list_methods_tmp[i]); ++i) {} for(; list_methods_tmp[i] && !isdigit(list_methods_tmp[i]); ++i) {} mAnalysisMethod2 = (list_methods_tmp[i]) ? atoi(list_methods_tmp+i) : CmdLine::NO_METHOD_SELECTED; } break; case OPT_ANALYSIS_PARAM: arg_param = args.MultiArg(2); if(!arg_param || !strncasecmp(arg_param[0], "help", 1)) { std::cerr << "bin " << "Number of bins for histograms" << std::endl; std::cerr << "parts " << "Fingerprint part to be show" << std::endl; std::cerr << "idx " << "Structure index" << std::endl; throw CmdLineSuccess(); } mAnalysisParams.insert(std::pair<std::string,std::string>(arg_param[0], arg_param[1])); break; case OPT_ANALYSIS_FILE: mAnalysisFile = args.OptionArg(); break; case OPT_SCATTER: mCreateScatterplot = true; break; case OPT_SCATTER_FILE: mScatterplotFile = args.OptionArg(); break; case OPT_SCATTER_PARAM: arg_param = args.MultiArg(2); if(!arg_param || !strncasecmp(arg_param[0], "help", 1)) { std::cerr << "retry " << "Number of retries" << std::endl; std::cerr << "mass " << "Ball mass" << std::endl; std::cerr << "stiffness " << "Of the spring" << std::endl; std::cerr << "damping " << "Damping factor for the movement" << std::endl; std::cerr << "perturb " << "Perturb scale for the retries (it perturb the initial position of the masses)" << std::endl; std::cerr << "bins " << "Number of bins for the binned distances diagnostics" << std::endl; std::cerr << "wobble " << "Wobble scale for the position of the binned points" << std::endl; std::cerr << "energy " << "Max kinetic energy to end iterations" << std::endl; std::cerr << "iterations " << "Max number of iterations" << std::endl; std::cerr << "kind " << "Kind of data to be output" << std::endl; std::cerr << "diagnostic " << "Kind of diagnostic chart to produce" << std::endl; std::cerr << "timestep " << "Timestep for the iterations" << std::endl; throw CmdLineSuccess(); } mScatterplotParams.insert(std::pair<std::string,std::string>(arg_param[0], arg_param[1])); break; case OPT_DIAGNOSTIC_FILE: mDiagnosticFile = args.OptionArg(); break; case OPT_SERIALIZE: mSerializeFile = args.OptionArg(); break; } } // Parse the file arguments switch(args.FileCount()) { case 0: // If method list requested, ignore files if(mListFingerprintingMethods || mListDistanceMethods || mListGroupingMethods || mListAnalysisMethods) return; std::cerr << "Missing POSCAR file" << std::endl << std::endl; std::cerr << "Usage:" << std::endl; std::cerr << " " << aVal[0] << usage_msg << std::endl << std::endl; showHelp(parser_options); throw CmdLineFatal(); case 1: mPoscarFile = args.File(0); break; default: mPoscarFile = args.File(0); mEnergyFile = args.File(1); break; } // Few sanity checks on the parameters if(mEndStep > 0 && mEndStep < mStartStep) { throw CmdLineFatal("End step should be >= start step"); } if(mHasEnergyThreshold && mHasReverseEnergyThreshold) { throw CmdLineFatal("Specify only one of energy threshold and reverse energy threshold"); } if(mDiffrBinSize <= 0) { throw CmdLineFatal("Bin size cannot be <= 0"); } if(mDiffrPeakSize < 0) { throw CmdLineFatal("Peak size cannot be < 0"); } if(mMaxDistanceForGrouping < 0) { throw CmdLineFatal("Max distance for grouping cannot be < 0"); } }
void JavaCalls::call_virtual(JavaValue* result, Handle receiver, KlassHandle spec_klass, Symbol* name, Symbol* signature, TRAPS) { JavaCallArguments args(receiver); // One oop argument call_virtual(result, spec_klass, name, signature, &args, CHECK); }
void JavaCalls::call_special(JavaValue* result, Handle receiver, KlassHandle klass, Symbol* name, Symbol* signature, Handle arg1, Handle arg2, TRAPS) { JavaCallArguments args(receiver); // One oop argument args.push_oop(arg1); args.push_oop(arg2); call_special(result, klass, name, signature, &args, CHECK); }
), "Returns its ServerEntity instance." ) .add_property("server_unknown", make_function( &CBaseEdict::GetUnknown, reference_existing_object_policy() ), "Returns its ServerUnknown instance." ) .def("set_edict", &CBaseEdict::SetEdict, "Set when initting an entity. If it's only a networkable, this is false.", args("unknown", "full_edict") ) .add_property("area_num", &CBaseEdict::AreaNum ) .add_property("classname", &CBaseEdict::GetClassName, "Returns the edict's class name." ) .add_property("free", &CBaseEdict::IsFree, &CBaseEdict::SetFree )
void Field::AutoComplete() { //We want to complete in the middle of a command text with potentially multiple commands //Add slash prefix and get command text up to cursor if (GetText().empty() || (GetText()[0] != '/' && GetText()[0] != '\\')) { GetText().insert(GetText().begin(), '/'); SetCursor(GetCursorPos() + 1); } std::string commandText = Str::UTF32To8(GetText().substr(1, GetCursorPos() - 1)); //Split the command text and find the command to complete const char* commandStart = commandText.data(); const char* commandEnd = commandText.data() + commandText.size(); while (true) { const char* next = Cmd::SplitCommand(commandStart, commandEnd); if (next != commandEnd) commandStart = next; else break; } //Parse the arguments and get the list of candidates Cmd::Args args(std::string(commandStart, commandEnd)); int argNum = args.Argc() - 1; std::string prefix; if (!args.Argc() || Str::cisspace(GetText()[GetCursorPos() - 1])) { argNum++; } else { prefix = args.Argv(argNum); } Cmd::CompletionResult candidates = Cmd::CompleteArgument(args, argNum); if (candidates.empty()) { return; } std::sort(candidates.begin(), candidates.end()); candidates.erase(std::unique(candidates.begin(), candidates.end()), candidates.end()); //Compute the longest common prefix of all the results int prefixSize = candidates[0].first.size(); size_t maxCandidateLength = 0; for (auto& candidate : candidates) { prefixSize = std::min(prefixSize, Str::LongestIPrefixSize(candidate.first, candidates[0].first)); maxCandidateLength = std::max(maxCandidateLength, candidate.first.length()); } std::string completedArg(candidates[0].first, 0, prefixSize); //Help the user bash the TAB key, but not when completing paths if (candidates.size() == 1 && !Str::cisspace(GetText()[GetCursorPos()]) && !Str::IsSuffix("/", completedArg)) { completedArg += " "; } //Insert the completed arg std::u32string toInsert = Str::UTF8To32(completedArg); DeletePrev(prefix.size()); GetText().insert(GetCursorPos(), toInsert); SetCursor(GetCursorPos() + toInsert.size()); //Print the matches if it is ambiguous if (candidates.size() >= 2) { Com_Printf(S_COLOR_YELLOW "-> " S_COLOR_WHITE "%s\n", Str::UTF32To8(GetText()).c_str()); for (const auto& candidate : candidates) { std::string filler(maxCandidateLength - candidate.first.length(), ' '); Com_Printf(" %s%s %s\n", candidate.first.c_str(), filler.c_str(), candidate.second.c_str()); } } }
MacroButtonEventHandler::MacroEvent MacroButtonEventHandler::macro_event_from_string(const std::string& str) { boost::tokenizer<boost::char_separator<char> > tokens(str, boost::char_separator<char>(" ")); std::vector<std::string> args(tokens.begin(), tokens.end()); if (args.size() >= 1) { if (!args[0].empty() && args[0][0] == '#') { // ignore '#' comments MacroEvent event; event.type = MacroEvent::kNull; return event; } else if (args[0] == "init") { // FIXME: generalize this for EV_KEY and EV_REL if (args.size() < 4) { raise_exception(std::runtime_error, "'init' requires at least three arguments: " << str); } else { MacroEvent event; event.type = MacroEvent::kInitOp; event.init.event = UIEvent::from_string(args[1]); event.init.emitter = 0; event.init.minimum = boost::lexical_cast<int>(args[2]); event.init.maximum = boost::lexical_cast<int>(args[3]); event.init.fuzz = 0; event.init.flat = 0; if (args.size() > 4) event.init.fuzz = boost::lexical_cast<int>(args[4]); if (args.size() > 5) event.init.flat = boost::lexical_cast<int>(args[5]); return event; } } else if (args[0] == "send") { if (args.size() != 3) { raise_exception(std::runtime_error, "'send' requires two arguments: " << str); } else { MacroEvent event; event.type = MacroEvent::kSendOp; event.send.event = UIEvent::from_string(args[1]); event.send.emitter = 0; event.send.value = boost::lexical_cast<int>(args[2]); return event; } } else if (args[0] == "wait") { if (args.size() != 2) { raise_exception(std::runtime_error, "'wait' requires one arguments: " << str); } else { MacroEvent event; event.type = MacroEvent::kWaitOp; event.wait.msec = boost::lexical_cast<int>(args[1]); return event; } } else { raise_exception(std::runtime_error, "unknown macro command: " << str); } } else { // no args, aka an empty line, just ignore it MacroEvent event; event.type = MacroEvent::kNull; return event; } }
void UFInstance::gatherVariables(carlVariables& vars) const { for (const auto& a: args()) { a.gatherVariables(vars); } }
static EncodedJSValue JSC_HOST_CALL callArrayConstructor(ExecState* exec) { ArgList args(exec); return JSValue::encode(constructArrayWithSizeQuirk(exec, args)); }
void UFInstance::gatherUFs(std::set<UninterpretedFunction>& ufs) const { ufs.insert(uninterpretedFunction()); for (const auto& a: args()) { a.gatherUFs(ufs); } }
void init_openravepy_trajectory() { void (PyTrajectoryBase::*Insert1)(size_t,object) = &PyTrajectoryBase::Insert; void (PyTrajectoryBase::*Insert2)(size_t,object,bool) = &PyTrajectoryBase::Insert; void (PyTrajectoryBase::*Insert3)(size_t,object,PyConfigurationSpecificationPtr) = &PyTrajectoryBase::Insert; void (PyTrajectoryBase::*Insert4)(size_t,object,PyConfigurationSpecificationPtr,bool) = &PyTrajectoryBase::Insert; object (PyTrajectoryBase::*Sample1)(dReal) const = &PyTrajectoryBase::Sample; object (PyTrajectoryBase::*Sample2)(dReal, PyConfigurationSpecificationPtr) const = &PyTrajectoryBase::Sample; object (PyTrajectoryBase::*GetWaypoints1)(size_t,size_t) const = &PyTrajectoryBase::GetWaypoints; object (PyTrajectoryBase::*GetWaypoints2)(size_t,size_t,PyConfigurationSpecificationPtr) const = &PyTrajectoryBase::GetWaypoints; object (PyTrajectoryBase::*GetWaypoints2D1)(size_t,size_t) const = &PyTrajectoryBase::GetWaypoints2D; object (PyTrajectoryBase::*GetWaypoints2D2)(size_t,size_t,PyConfigurationSpecificationPtr) const = &PyTrajectoryBase::GetWaypoints2D; object (PyTrajectoryBase::*GetWaypoint1)(int) const = &PyTrajectoryBase::GetWaypoint; object (PyTrajectoryBase::*GetWaypoint2)(int,PyConfigurationSpecificationPtr) const = &PyTrajectoryBase::GetWaypoint; class_<PyTrajectoryBase, boost::shared_ptr<PyTrajectoryBase>, bases<PyInterfaceBase> >("Trajectory", DOXY_CLASS(TrajectoryBase), no_init) .def("Init",&PyTrajectoryBase::Init,args("spec"),DOXY_FN(TrajectoryBase,Init)) .def("Insert",Insert1,args("index","data"),DOXY_FN(TrajectoryBase,Insert "size_t; const std::vector; bool")) .def("Insert",Insert2,args("index","data","overwrite"),DOXY_FN(TrajectoryBase,Insert "size_t; const std::vector; bool")) .def("Insert",Insert3,args("index","data","spec"),DOXY_FN(TrajectoryBase,Insert "size_t; const std::vector; const ConfigurationSpecification; bool")) .def("Insert",Insert4,args("index","data","spec","overwrite"),DOXY_FN(TrajectoryBase,Insert "size_t; const std::vector; const ConfigurationSpecification; bool")) .def("Remove",&PyTrajectoryBase::Remove,args("startindex","endindex"),DOXY_FN(TrajectoryBase,Remove)) .def("Sample",Sample1,args("time"),DOXY_FN(TrajectoryBase,Sample "std::vector; dReal")) .def("Sample",Sample2,args("time","spec"),DOXY_FN(TrajectoryBase,Sample "std::vector; dReal; const ConfigurationSpecification")) .def("GetConfigurationSpecification",&PyTrajectoryBase::GetConfigurationSpecification,DOXY_FN(TrajectoryBase,GetConfigurationSpecification)) .def("GetNumWaypoints",&PyTrajectoryBase::GetNumWaypoints,DOXY_FN(TrajectoryBase,GetNumWaypoints)) .def("GetWaypoints",GetWaypoints1,args("startindex","endindex"),DOXY_FN(TrajectoryBase, GetWaypoints "size_t; size_t; std::vector")) .def("GetWaypoints",GetWaypoints2,args("startindex","endindex","spec"),DOXY_FN(TrajectoryBase, GetWaypoints "size_t; size_t; std::vector, const ConfigurationSpecification&")) .def("GetWaypoints2D",GetWaypoints2D1,args("startindex","endindex"),DOXY_FN(TrajectoryBase, GetWaypoints "size_t; size_t; std::vector")) .def("GetWaypoints2D",GetWaypoints2D2,args("startindex","endindex","spec"),DOXY_FN(TrajectoryBase, GetWaypoints "size_t; size_t; std::vector, const ConfigurationSpecification&")) .def("GetWaypoint",GetWaypoint1,args("index"),DOXY_FN(TrajectoryBase, GetWaypoint "int; std::vector")) .def("GetWaypoint",GetWaypoint2,args("index","spec"),DOXY_FN(TrajectoryBase, GetWaypoint "int; std::vector; const ConfigurationSpecification")) .def("GetFirstWaypointIndexAfterTime",&PyTrajectoryBase::GetFirstWaypointIndexAfterTime, DOXY_FN(TrajectoryBase, GetFirstWaypointIndexAfterTime)) .def("GetDuration",&PyTrajectoryBase::GetDuration,DOXY_FN(TrajectoryBase, GetDuration)) .def("serialize",&PyTrajectoryBase::serialize,serialize_overloads(args("options"),DOXY_FN(TrajectoryBase,serialize))) .def("deserialize",&PyTrajectoryBase::deserialize,args("data"),DOXY_FN(TrajectoryBase,deserialize)) .def("Write",&PyTrajectoryBase::Write,args("options"),DOXY_FN(TrajectoryBase,Write)) .def("Read",&PyTrajectoryBase::Read,args("data","robot"),DOXY_FN(TrajectoryBase,Read)) ; def("RaveCreateTrajectory",openravepy::RaveCreateTrajectory,args("env","name"),DOXY_FN1(RaveCreateTrajectory)); }
int main(int argc, char* argv[]) { CommandLineArgs args(argc,argv); if (args.CheckCmdLineFlag("help")) { Usage(); return 0; } args.GetCmdLineArgument("enable_interop", useInterop); printf("useInterop=%d\n",useInterop); args.GetCmdLineArgument("enable_convexheightfield", useConvexHeightfield); printf("enable_convexheightfield=%d\n",useConvexHeightfield); args.GetCmdLineArgument("enable_gpusap", useSapGpuBroadphase); printf("enable_gpusap=%d\n",useSapGpuBroadphase); args.GetCmdLineArgument("pause_simulation", pauseSimulation); printf("pause_simulation=%d\n",pauseSimulation); args.GetCmdLineArgument("x_dim", NUM_OBJECTS_X); args.GetCmdLineArgument("y_dim", NUM_OBJECTS_Y); args.GetCmdLineArgument("z_dim", NUM_OBJECTS_Z); args.GetCmdLineArgument("x_gap", X_GAP); args.GetCmdLineArgument("y_gap", Y_GAP); args.GetCmdLineArgument("z_gap", Z_GAP); printf("x_dim=%d, y_dim=%d, z_dim=%d\n",NUM_OBJECTS_X,NUM_OBJECTS_Y,NUM_OBJECTS_Z); printf("x_gap=%f, y_gap=%f, z_gap=%f\n",X_GAP,Y_GAP,Z_GAP); args.GetCmdLineArgument("enable_static", keepStaticObjects); printf("enable_static=%d\n",keepStaticObjects); char* tmpfile = 0; args.GetCmdLineArgument("load_bulletfile", tmpfile ); if (tmpfile) fileName = tmpfile; printf("load_bulletfile=%s\n",fileName); printf("\n"); #ifdef _WIN32 Win32OpenGLWindow* window = new Win32OpenGLWindow(); #else MacOpenGLWindow* window = new MacOpenGLWindow(); #endif window->init(1024,768); #ifdef _WIN32 GLenum err = glewInit(); #endif window->startRendering(); window->endRendering(); GLInstancingRenderer render; CLPhysicsDemo demo(window); demo.init(-1,-1,useInterop); render.InitShaders(); if (useInterop) demo.setupInterop(); createScene(render, demo, useConvexHeightfield,fileName); printf("numPhysicsInstances= %d\n", demo.m_numPhysicsInstances); printf("numDynamicPhysicsInstances= %d\n", demo.m_numDynamicPhysicsInstances); render.writeTransforms(); window->startRendering(); render.RenderScene(); window->endRendering(); while (!window->requestedExit()) { CProfileManager::Reset(); if (shootObject) { shootObject = false; btVector3 linVel;// = (m_cameraPosition-m_cameraTargetPosition).normalize()*-100; int x,y; window->getMouseCoordinates(x,y); render.getMouseDirection(&linVel[0],x,y); linVel.normalize(); linVel*=100; // btVector3 startPos; demo.setObjectLinearVelocity(&linVel[0],0); float orn[4] = {0,0,0,1}; float pos[4] = {m_cameraPosition[0],m_cameraPosition[1],m_cameraPosition[2],1}; // demo.setObjectTransform(pos,orn,0); render.writeSingleTransform(pos,orn,0); // createScene(render, demo); // printf("numPhysicsInstances= %d\n", demo.m_numPhysicsInstances); // printf("numDynamicPhysicsInstances= %d\n", demo.m_numDynamicPhysicsInstances); // render.writeTransforms(); } if (!pauseSimulation ) demo.stepSimulation(); window->startRendering(); render.RenderScene(); window->endRendering(); { BT_PROFILE("glFinish"); glFinish(); } CProfileManager::Increment_Frame_Counter(); if (printStats && !pauseSimulation) { static int count = 3; count--; if (count<0) { count = 100; CProfileManager::dumpAll(); printf("total broadphase pairs= %d\n", numPairsTotal); printf("numPairsOut (culled) = %d\n", numPairsOut); //printStats = false; } else { // printf("."); } } } demo.cleanup(); render.CleanupShaders(); window->exit(); delete window; return 0; }
/* * @brief This is called by LibMV to retrieve an image either for reference or as search frame. */ mv::FrameAccessor::Key TrackerFrameAccessor::GetImage(int /*clip*/, int frame, mv::FrameAccessor::InputMode input_mode, int downscale, // Downscale by 2^downscale. const mv::Region* region, // Get full image if NULL. const mv::FrameAccessor::Transform* /*transform*/, // May be NULL. mv::FloatImage** destination) { // Since libmv only uses MONO images for now we have only optimized for this case, remove and handle properly // other case(s) when they get integrated into libmv. assert(input_mode == mv::FrameAccessor::MONO); FrameAccessorCacheKey key; key.frame = frame; key.mipMapLevel = downscale; key.mode = input_mode; /* Check if a frame exists in the cache with matching key and bounds enclosing the given region */ RectI roi; if (region) { convertLibMVRegionToRectI(*region, _imp->formatHeight, &roi); QMutexLocker k(&_imp->cacheMutex); std::pair<FrameAccessorCache::iterator, FrameAccessorCache::iterator> range = _imp->cache.equal_range(key); for (FrameAccessorCache::iterator it = range.first; it != range.second; ++it) { if ( (roi.x1 >= it->second.bounds.x1) && (roi.x2 <= it->second.bounds.x2) && ( roi.y1 >= it->second.bounds.y1) && ( roi.y2 <= it->second.bounds.y2) ) { #ifdef TRACE_LIB_MV qDebug() << QThread::currentThread() << "FrameAccessor::GetImage():" << "Found cached image at frame" << frame << "with RoI x1=" << region->min(0) << "y1=" << region->max(1) << "x2=" << region->max(0) << "y2=" << region->min(1); #endif // LibMV is kinda dumb on this we must necessarily copy the data either via CopyFrom or the // assignment constructor: // EDIT: fixed libmv *destination = it->second.image.get(); //destination->CopyFrom<float>(*it->second.image); ++it->second.referenceCount; return (mv::FrameAccessor::Key)it->second.image.get(); } } } EffectInstancePtr effect; if (_imp->trackerInput) { effect = _imp->trackerInput->getEffectInstance(); } if (!effect) { return (mv::FrameAccessor::Key)0; } // Not in accessor cache, call renderRoI RenderScale scale; scale.y = scale.x = Image::getScaleFromMipMapLevel( (unsigned int)downscale ); RectD precomputedRoD; if (!region) { bool isProjectFormat; StatusEnum stat = effect->getRegionOfDefinition_public(_imp->trackerInput->getHashValue(), frame, scale, ViewIdx(0), &precomputedRoD, &isProjectFormat); if (stat == eStatusFailed) { return (mv::FrameAccessor::Key)0; } double par = effect->getAspectRatio(-1); precomputedRoD.toPixelEnclosing( (unsigned int)downscale, par, &roi ); } std::list<ImageComponents> components; components.push_back( ImageComponents::getRGBComponents() ); NodePtr node = _imp->context->getNode(); const bool isRenderUserInteraction = true; const bool isSequentialRender = false; AbortableRenderInfoPtr abortInfo = AbortableRenderInfo::create(false, 0); AbortableThread* isAbortable = dynamic_cast<AbortableThread*>( QThread::currentThread() ); if (isAbortable) { isAbortable->setAbortInfo( isRenderUserInteraction, abortInfo, node->getEffectInstance() ); } ParallelRenderArgsSetter::CtorArgsPtr tlsArgs(new ParallelRenderArgsSetter::CtorArgs); tlsArgs->time = frame; tlsArgs->view = ViewIdx(0); tlsArgs->isRenderUserInteraction = isRenderUserInteraction; tlsArgs->isSequential = isSequentialRender; tlsArgs->abortInfo = abortInfo; tlsArgs->treeRoot = node; tlsArgs->textureIndex = 0; tlsArgs->timeline = node->getApp()->getTimeLine(); tlsArgs->activeRotoPaintNode = NodePtr(); tlsArgs->activeRotoDrawableItem = RotoDrawableItemPtr(); tlsArgs->isDoingRotoNeatRender = false; tlsArgs->isAnalysis = true; tlsArgs->draftMode = false; tlsArgs->stats = RenderStatsPtr(); ParallelRenderArgsSetter frameRenderArgs(tlsArgs); // Stats EffectInstance::RenderRoIArgs args( frame, scale, downscale, ViewIdx(0), false, roi, precomputedRoD, components, eImageBitDepthFloat, true, _imp->context->getNode()->getEffectInstance(), eStorageModeRAM /*returnOpenGLTex*/, frame); std::map<ImageComponents, ImagePtr> planes; EffectInstance::RenderRoIRetCode stat = effect->renderRoI(args, &planes); if ( (stat != EffectInstance::eRenderRoIRetCodeOk) || planes.empty() ) { #ifdef TRACE_LIB_MV qDebug() << QThread::currentThread() << "FrameAccessor::GetImage():" << "Failed to call renderRoI on input at frame" << frame << "with RoI x1=" << roi.x1 << "y1=" << roi.y1 << "x2=" << roi.x2 << "y2=" << roi.y2; #endif return (mv::FrameAccessor::Key)0; } assert( !planes.empty() ); const ImagePtr& sourceImage = planes.begin()->second; RectI sourceBounds = sourceImage->getBounds(); RectI intersectedRoI; if ( !roi.intersect(sourceBounds, &intersectedRoI) ) { #ifdef TRACE_LIB_MV qDebug() << QThread::currentThread() << "FrameAccessor::GetImage():" << "RoI does not intersect the source image bounds (RoI x1=" << roi.x1 << "y1=" << roi.y1 << "x2=" << roi.x2 << "y2=" << roi.y2 << ")"; #endif return (mv::FrameAccessor::Key)0; } #ifdef TRACE_LIB_MV qDebug() << QThread::currentThread() << "FrameAccessor::GetImage():" << "renderRoi (frame" << frame << ") OK (BOUNDS= x1=" << sourceBounds.x1 << "y1=" << sourceBounds.y1 << "x2=" << sourceBounds.x2 << "y2=" << sourceBounds.y2 << ") (ROI = " << roi.x1 << "y1=" << roi.y1 << "x2=" << roi.x2 << "y2=" << roi.y2 << ")"; #endif /* Copy the Natron image to the LivMV float image */ FrameAccessorCacheEntry entry; entry.image.reset( new MvFloatImage( intersectedRoI.height(), intersectedRoI.width() ) ); entry.bounds = intersectedRoI; entry.referenceCount = 1; natronImageToLibMvFloatImage(_imp->enabledChannels, sourceImage.get(), intersectedRoI, *entry.image); // we ignore the transform parameter and do it in natronImageToLibMvFloatImage instead *destination = entry.image.get(); //destination->CopyFrom<float>(*entry.image); //insert into the cache { QMutexLocker k(&_imp->cacheMutex); _imp->cache.insert( std::make_pair(key, entry) ); } #ifdef TRACE_LIB_MV qDebug() << QThread::currentThread() << "FrameAccessor::GetImage():" << "Rendered frame" << frame << "with RoI x1=" << intersectedRoI.x1 << "y1=" << intersectedRoI.y1 << "x2=" << intersectedRoI.x2 << "y2=" << intersectedRoI.y2; #endif return (mv::FrameAccessor::Key)entry.image.get(); } // TrackerFrameAccessor::GetImage
variant execute(const game_logic::formula_callable& variables) const { const std::string key = args()[0]->evaluate(variables).as_string(); return variant(hex_object::get_hex_tile(key).get()); }
void CommandHandler::handleCommand(const std::string &command, ChatTab *tab) { std::string::size_type pos = command.find(' '); std::string type(command, 0, pos); std::string args(command, pos == std::string::npos ? command.size() : pos + 1); if (type == "help") // Do help before tabs so they can't override it { handleHelp(args, tab); } else if (tab->handleCommand(type, args)) { // Nothing to do } else if (type == "announce") { handleAnnounce(args, tab); } else if (type == "where") { handleWhere(args, tab); } else if (type == "who") { handleWho(args, tab); } else if (type == "msg" || type == "whisper" || type == "w") { handleMsg(args, tab); } else if (type == "query" || type == "q") { handleQuery(args, tab); } else if (type == "ignore") { handleIgnore(args, tab); } else if (type == "unignore") { handleUnignore(args, tab); } else if (type == "join") { handleJoin(args, tab); } else if (type == "list") { handleListChannels(args, tab); } else if (type == "clear") { handleClear(args, tab); } else if (type == "createparty") { handleCreateParty(args, tab); } else if (type == "party") { handleParty(args, tab); } else if (type == "me") { handleMe(args, tab); } else if (type == "record") { handleRecord(args, tab); } else if (type == "toggle") { handleToggle(args, tab); } else if (type == "present") { handlePresent(args, tab); } else if (type == "away") { handleAway(args, tab); } else { tab->chatLog(_("Unknown command.")); } }
int main(int argc, char *argv[]) { std::vector<std::string> args(argv + 1, argv + argc); if (args.size() < 1 || (args.size() > 1 && args[1] != "--")) { utils::generateUsageStr(); return -1; } const std::string path(args[0]); const std::string json("compile_commands.json"); // Load compile commands auto db = utils::loadDB(path + json); if (!db) { utils::generateUsageStr(); return -1; } ct::ClangTool tool(*db, db->getAllFiles()); // Pass compiler options if (args.size() > 2) { std::vector<std::string> compilerArgs(args.begin() + 2, args.end()); ct::ArgumentInsertPosition pos = ct::ArgumentInsertPosition::END; tool.appendArgumentsAdjuster(ct::getInsertArgumentAdjuster(compilerArgs, pos)); } // Add matchers ca::MatchFinder finder; std::string pathRegex(path + "*"); match::SimpleMatcher functionHandler; match::Matcher<clang::IfStmt> ifHandler; match::Matcher<clang::ForStmt> forHandler; match::Matcher<clang::CXXForRangeStmt> rangeHandler; match::Matcher<clang::WhileStmt> whileHandler; match::Matcher<clang::DoStmt> doHandler; match::Matcher<clang::CaseStmt> caseHandler; match::Matcher<clang::CXXCatchStmt> catchHandler; match::Matcher<clang::BinaryOperator> binaryOpHandler; match::Matcher<clang::ConditionalOperator> condOpHandler; match::Matcher<clang::BinaryConditionalOperator> binaryCondOpHandler; finder.addMatcher(match::getMatcher<clang::FunctionDecl>(pathRegex), &functionHandler); finder.addMatcher(match::getMatcher<clang::IfStmt>(pathRegex), &ifHandler); finder.addMatcher(match::getMatcher<clang::ForStmt>(pathRegex), &forHandler); finder.addMatcher(match::getMatcher<clang::CXXForRangeStmt>(pathRegex), &rangeHandler); finder.addMatcher(match::getMatcher<clang::WhileStmt>(pathRegex), &whileHandler); finder.addMatcher(match::getMatcher<clang::DoStmt>(pathRegex), &doHandler); finder.addMatcher(match::getMatcher<clang::CaseStmt>(pathRegex), &caseHandler); finder.addMatcher(match::getMatcher<clang::CXXCatchStmt>(pathRegex), &catchHandler); finder.addMatcher(match::getMatcher<clang::BinaryOperator>(pathRegex), &binaryOpHandler); finder.addMatcher(match::getMatcher<clang::ConditionalOperator>(pathRegex), &condOpHandler); finder.addMatcher(match::getMatcher<clang::BinaryConditionalOperator>(pathRegex), &binaryCondOpHandler); // Run tool int rc = tool.run(ct::newFrontendActionFactory(&finder).get()); if (rc) { utils::generateUsageStr(); return -1; } // Output results std::ofstream output; output.open("results.txt"); if (!output.is_open()) { std::cerr << "Error while opening file for writing\n"; return -1; } output << "Path\tLine\tColumn\tName\tSignature\tLOC\tCyclomaticN\n"; auto stats = match::MatcherBase::getStats(); for (auto it = stats.begin(); it != stats.end(); ++it) { output << it->first.path << "\t" << it->first.line << "\t" << it->first.column << "\t" << it->first.name << "\t" << it->first.signature << "\t" << it->second.loc << "\t" << it->second.cyclomaticN << "\n"; } return 0; }
int main(int argc, char* argv[]) { b3CommandLineArgs args(argc,argv); char* fileName; args.GetCmdLineArgument("fileName",fileName); if (fileName==0) { printf("required --fileName=\"name\""); exit(0); } std::string matLibName = StripExtension(fileName); printf("fileName = %s\n", fileName); if (fileName==0) { printf("Please use --fileName=\"pathToObj\"."); exit(0); } bool mergeMaterials = args.CheckCmdLineFlag("mergeMaterials"); char fileNameWithPath[MAX_PATH_LEN]; bool fileFound = (b3ResourcePath::findResourcePath(fileName,fileNameWithPath,MAX_PATH_LEN))>0; char materialPrefixPath[MAX_PATH_LEN]; b3FileUtils::extractPath(fileNameWithPath,materialPrefixPath,MAX_PATH_LEN); std::vector<tinyobj::shape_t> shapes; std::string err = tinyobj::LoadObj(shapes, fileNameWithPath, materialPrefixPath); char sdfFileName[MAX_PATH_LEN]; sprintf(sdfFileName,"%s%s.sdf",materialPrefixPath,"newsdf"); FILE* sdfFile = fopen(sdfFileName,"w"); if (sdfFile==0) { printf("Fatal error: cannot create sdf file %s\n",sdfFileName); exit(0); } fprintf(sdfFile, "<sdf version='1.6'>\n\t<world name='default'>\n\t<gravity>0 0 -9.8</gravity>\n"); for (int s = 0; s < (int)shapes.size(); s++) { tinyobj::shape_t& shape = shapes[s]; tinyobj::material_t mat = shape.material; b3HashString key = mat.name.length() ? mat.name.c_str() : ""; if (!gMaterialNames.find(key)) { ShapeContainer container; container.m_matName = mat.name; container.m_shapeName = shape.name; container.material = mat; gMaterialNames.insert(key, container); } ShapeContainer* shapeC = gMaterialNames.find(key); if (shapeC) { shapeC->m_shapeIndices.push_back(s); int curPositions = shapeC->positions.size()/3; int curNormals = shapeC->normals.size()/3; int curTexcoords = shapeC->texcoords.size()/2; int faceCount = shape.mesh.indices.size(); int vertexCount = shape.mesh.positions.size(); for (int v = 0; v < vertexCount; v++) { shapeC->positions.push_back(shape.mesh.positions[v]); } int numNormals = int(shape.mesh.normals.size()); for (int vn = 0; vn < numNormals; vn++) { shapeC->normals.push_back(shape.mesh.normals[vn]); } int numTexCoords = int(shape.mesh.texcoords.size()); for (int vt = 0; vt < numTexCoords; vt++) { shapeC->texcoords.push_back(shape.mesh.texcoords[vt]); } for (int face = 0; face < faceCount; face += 3) { if (face < 0 && face >= int(shape.mesh.indices.size())) { continue; } shapeC->indices.push_back(shape.mesh.indices[face] + curPositions); shapeC->indices.push_back(shape.mesh.indices[face+1] + curPositions); shapeC->indices.push_back(shape.mesh.indices[face + 2] + curPositions); } } } printf("unique materials=%d\n", gMaterialNames.size()); if (mergeMaterials) { for (int m = 0; m < gMaterialNames.size();m++) { if (gMaterialNames.getAtIndex(m)->m_shapeIndices.size() == 0) continue; ShapeContainer* shapeCon =gMaterialNames.getAtIndex(m); printf("object name = %s\n", shapeCon->m_shapeName.c_str()); char objSdfPartFileName[MAX_PATH_LEN]; sprintf(objSdfPartFileName, "part%d.obj", m); char objFileName[MAX_PATH_LEN]; if (strlen(materialPrefixPath) > 0) { sprintf(objFileName, "%s/part%d.obj", materialPrefixPath, m); } else { sprintf(objFileName, "part%d.obj", m); } FILE* f = fopen(objFileName, "w"); if (f == 0) { printf("Fatal error: cannot create part obj file %s\n", objFileName); exit(0); } fprintf(f, "# Exported using automatic converter by Erwin Coumans\n"); if (matLibName.length()) { fprintf(f, "mtllib %s.mtl\n", matLibName.c_str()); } else { fprintf(f, "mtllib bedroom.mtl\n"); } int faceCount = shapeCon->indices.size(); int vertexCount = shapeCon->positions.size(); tinyobj::material_t mat = shapeCon->material; if (shapeCon->m_matName.length()) { const char* objName = shapeCon->m_matName.c_str(); printf("mat.name = %s\n", objName); fprintf(f, "#object %s\n\n", objName); } for (int v = 0; v < vertexCount / 3; v++) { fprintf(f, "v %f %f %f\n", shapeCon->positions[v * 3 + 0], shapeCon->positions[v * 3 + 1], shapeCon->positions[v * 3 + 2]); } if (mat.name.length()) { fprintf(f, "usemtl %s\n", mat.name.c_str()); } else { fprintf(f, "usemtl wire_028089177\n"); } fprintf(f, "\n"); int numNormals = int(shapeCon->normals.size()); for (int vn = 0; vn < numNormals / 3; vn++) { fprintf(f, "vn %f %f %f\n", shapeCon->normals[vn * 3 + 0], shapeCon->normals[vn * 3 + 1], shapeCon->normals[vn * 3 + 2]); } fprintf(f, "\n"); int numTexCoords = int(shapeCon->texcoords.size()); for (int vt = 0; vt < numTexCoords / 2; vt++) { fprintf(f, "vt %f %f\n", shapeCon->texcoords[vt * 2 + 0], shapeCon->texcoords[vt * 2 + 1]); } fprintf(f, "s off\n"); for (int face = 0; face < faceCount; face += 3) { if (face < 0 && face >= int(shapeCon->indices.size())) { continue; } fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", shapeCon->indices[face] + 1, shapeCon->indices[face] + 1, shapeCon->indices[face] + 1, shapeCon->indices[face + 1] + 1, shapeCon->indices[face + 1] + 1, shapeCon->indices[face + 1] + 1, shapeCon->indices[face + 2] + 1, shapeCon->indices[face + 2] + 1, shapeCon->indices[face + 2] + 1); } fclose(f); float kdRed = mat.diffuse[0]; float kdGreen = mat.diffuse[1]; float kdBlue = mat.diffuse[2]; float transparency = mat.transparency; fprintf(sdfFile, "\t\t<model name='%s'>\n" "\t\t\t<static>1</static>\n" "\t\t\t<pose frame=''>0 0 0 0 0 0</pose>\n" "\t\t\t<link name='link_d%d'>\n" "\t\t\t<inertial>\n" "\t\t\t<mass>0</mass>\n" "\t\t\t<inertia>\n" "\t\t\t<ixx>0.166667</ixx>\n" "\t\t\t<ixy>0</ixy>\n" "\t\t\t<ixz>0</ixz>\n" "\t\t\t<iyy>0.166667</iyy>\n" "\t\t\t<iyz>0</iyz>\n" "\t\t\t<izz>0.166667</izz>\n" "\t\t\t</inertia>\n" "\t\t\t</inertial>\n" "\t\t\t<collision concave='yes' name='collision_%d'>\n" "\t\t\t<geometry>\n" "\t\t\t<mesh>\n" "\t\t\t<scale>1 1 1</scale>\n" "\t\t\t\t<uri>%s</uri>\n" "\t\t\t</mesh>\n" "\t\t\t</geometry>\n" "\t\t\t </collision>\n" "\t\t\t<visual name='visual'>\n" "\t\t\t\t<geometry>\n" "\t\t\t\t<mesh>\n" "\t\t\t\t\t<scale>1 1 1</scale>\n" "\t\t\t\t\t<uri>%s</uri>\n" "\t\t\t\t</mesh>\n" "\t\t\t\t</geometry>\n" "\t\t\t<material>\n" "\t\t\t\t<ambient>1 0 0 1</ambient>\n" "\t\t\t\t<diffuse>%f %f %f %f</diffuse>\n" "\t\t\t\t<specular>0.1 0.1 0.1 1</specular>\n" "\t\t\t\t<emissive>0 0 0 0</emissive>\n" "\t\t\t </material>\n" "\t\t\t </visual>\n" "\t\t\t </link>\n" "\t\t\t</model>\n", objSdfPartFileName, m, m, objSdfPartFileName, objSdfPartFileName, kdRed, kdGreen, kdBlue, transparency); } } else { for (int s = 0; s < (int)shapes.size(); s++) { tinyobj::shape_t& shape = shapes[s]; if (shape.name.length()) { printf("object name = %s\n", shape.name.c_str()); } char objFileName[MAX_PATH_LEN]; if (strlen(materialPrefixPath) > 0) { sprintf(objFileName, "%s/part%d.obj", materialPrefixPath, s); } else { sprintf(objFileName, "part%d.obj", s); } FILE* f = fopen(objFileName, "w"); if (f == 0) { printf("Fatal error: cannot create part obj file %s\n", objFileName); exit(0); } fprintf(f, "# Exported using automatic converter by Erwin Coumans\n"); if (matLibName.length()) { fprintf(f, "mtllib %s.mtl\n", matLibName.c_str()); } else { fprintf(f, "mtllib bedroom.mtl\n"); } int faceCount = shape.mesh.indices.size(); int vertexCount = shape.mesh.positions.size(); tinyobj::material_t mat = shape.material; if (shape.name.length()) { const char* objName = shape.name.c_str(); printf("mat.name = %s\n", objName); fprintf(f, "#object %s\n\n", objName); } for (int v = 0; v < vertexCount / 3; v++) { fprintf(f, "v %f %f %f\n", shape.mesh.positions[v * 3 + 0], shape.mesh.positions[v * 3 + 1], shape.mesh.positions[v * 3 + 2]); } if (mat.name.length()) { fprintf(f, "usemtl %s\n", mat.name.c_str()); } else { fprintf(f, "usemtl wire_028089177\n"); } fprintf(f, "\n"); int numNormals = int(shape.mesh.normals.size()); for (int vn = 0; vn < numNormals / 3; vn++) { fprintf(f, "vn %f %f %f\n", shape.mesh.normals[vn * 3 + 0], shape.mesh.normals[vn * 3 + 1], shape.mesh.normals[vn * 3 + 2]); } fprintf(f, "\n"); int numTexCoords = int(shape.mesh.texcoords.size()); for (int vt = 0; vt < numTexCoords / 2; vt++) { fprintf(f, "vt %f %f\n", shape.mesh.texcoords[vt * 2 + 0], shape.mesh.texcoords[vt * 2 + 1]); } fprintf(f, "s off\n"); for (int face = 0; face < faceCount; face += 3) { if (face < 0 && face >= int(shape.mesh.indices.size())) { continue; } fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", shape.mesh.indices[face] + 1, shape.mesh.indices[face] + 1, shape.mesh.indices[face] + 1, shape.mesh.indices[face + 1] + 1, shape.mesh.indices[face + 1] + 1, shape.mesh.indices[face + 1] + 1, shape.mesh.indices[face + 2] + 1, shape.mesh.indices[face + 2] + 1, shape.mesh.indices[face + 2] + 1); } fclose(f); float kdRed = mat.diffuse[0]; float kdGreen = mat.diffuse[1]; float kdBlue = mat.diffuse[2]; float transparency = mat.transparency; char objSdfPartFileName[MAX_PATH_LEN]; sprintf(objSdfPartFileName, "part%d.obj", s); fprintf(sdfFile, "\t\t<model name='%s'>\n" "\t\t\t<static>1</static>\n" "\t\t\t<pose frame=''>0 0 0 0 0 0</pose>\n" "\t\t\t<link name='link_d%d'>\n" "\t\t\t<inertial>\n" "\t\t\t<mass>0</mass>\n" "\t\t\t<inertia>\n" "\t\t\t<ixx>0.166667</ixx>\n" "\t\t\t<ixy>0</ixy>\n" "\t\t\t<ixz>0</ixz>\n" "\t\t\t<iyy>0.166667</iyy>\n" "\t\t\t<iyz>0</iyz>\n" "\t\t\t<izz>0.166667</izz>\n" "\t\t\t</inertia>\n" "\t\t\t</inertial>\n" "\t\t\t<collision name='collision_%d'>\n" "\t\t\t<geometry>\n" "\t\t\t<mesh>\n" "\t\t\t<scale>1 1 1</scale>\n" "\t\t\t\t<uri>%s</uri>\n" "\t\t\t</mesh>\n" "\t\t\t</geometry>\n" "\t\t\t </collision>\n" "\t\t\t<visual name='visual'>\n" "\t\t\t\t<geometry>\n" "\t\t\t\t<mesh>\n" "\t\t\t\t\t<scale>1 1 1</scale>\n" "\t\t\t\t\t<uri>%s</uri>\n" "\t\t\t\t</mesh>\n" "\t\t\t\t</geometry>\n" "\t\t\t<material>\n" "\t\t\t\t<ambient>1 0 0 1</ambient>\n" "\t\t\t\t<diffuse>%f %f %f %f</diffuse>\n" "\t\t\t\t<specular>0.1 0.1 0.1 1</specular>\n" "\t\t\t\t<emissive>0 0 0 0</emissive>\n" "\t\t\t </material>\n" "\t\t\t </visual>\n" "\t\t\t </link>\n" "\t\t\t</model>\n", objSdfPartFileName, s, s, objSdfPartFileName, objSdfPartFileName, kdRed, kdGreen, kdBlue, transparency); } } fprintf(sdfFile,"\t</world>\n</sdf>\n"); fclose(sdfFile); return 0; }
/** process the command-line, ; arguments appear in any order IN : User::CommandLine() OUT : iTestCasesIdentities iHelpRequested gSemiAutomated gVerboseOutput gOpenIterations gOOMIterations gTestRoleMaster gUSBVidPid */ void CTestEngine::ProcessCommandLineL() { // example t_otgdi.exe /ALL /G:0468 /VERBOSE TInt cmdLineLength(User::CommandLineLength()); HBufC* cmdLine = HBufC::NewMaxLC(cmdLineLength); TPtr cmdLinePtr = cmdLine->Des(); User::CommandLine(cmdLinePtr); TBool tokenParsed(EFalse); TLex args(*cmdLine); args.SkipSpace(); // args are separated by spaces // first arg is the exe name, skip it TPtrC cmdToken = args.NextToken(); HBufC* tc = HBufC::NewLC(KParameterTextLenMax); *tc = cmdToken; while (tc->Length()) { tokenParsed = EFalse; // '/?' help wanted flag '?' or /? parameter TInt pos(0); if ((0== tc->FindF(_L("?"))) || (0==tc->FindF(_L("/?")))) { iHelpRequested = ETrue; tokenParsed = ETrue; } // '/ALL' parameter pos = tc->FindF(KArgAllTestCases); if (pos != KErrNotFound) { AddAllDefaultTests(); tokenParsed = ETrue; } // '/AUTO' pos = tc->FindF(KArgAutomatedTest); if (pos != KErrNotFound) { // skip some of the press-any key things test.Printf(_L("Test semi-automated mode.\n")); OstTrace0(TRACE_NORMAL, CTESTENGINE_PROCESSCOMMANDLINEL, "Test semi-automated mode.\n"); gSemiAutomated = ETrue; tokenParsed = ETrue; } // '/G:TESTNAME' pos = tc->FindF(KArgGoTestCase); if (pos != KErrNotFound) { HBufC* tcPart = HBufC::NewLC(KTestCaseIdLength); TPtrC testID = tc->Right(tc->Length() - pos - KArgGoTestCase().Length()); LOG_VERBOSE2(_L("Parameter found:'%S'\n"), &testID); if(gVerboseOutput) { OstTraceExt1(TRACE_VERBOSE, CTESTENGINE_PROCESSCOMMANDLINEL_DUP01, "Parameter found:'%S'\n", testID); } // Check if it is a test we know of in our suite, users may provide the full // name "PBASE-USB_OTGDI-0466", or just the last 4 digits "0466", in such cases, fetch the full name if (!RTestFactory::TestCaseExists(testID)) { // try use just the test#part TPtr tcDes = tcPart->Des(); // build and add the full name tcDes.Format(KidFormatterS, &testID); if (!RTestFactory::TestCaseExists(tcDes)) { test.Printf(_L("Test case does NOT Exist: '%lS'\n"), &testID); OstTraceExt1(TRACE_NORMAL, CTESTENGINE_PROCESSCOMMANDLINEL_DUP02, "Test case does NOT Exist: '%lS'\n", testID); } else { // only the number was supplied, copy the full name testID.Set(tcDes); } } // check that it's valid before adding it to the run-list if (RTestFactory::TestCaseExists(testID)) { HBufC* testIdentity = HBufC::NewLC(KTestCaseIdLength); *testIdentity = testID; test.Printf(_L("Test case specified: %lS\n"), testIdentity); OstTraceExt1(TRACE_NORMAL, CTESTENGINE_PROCESSCOMMANDLINEL_DUP03, "Test case specified: %lS\n", *testIdentity); iTestCasesIdentities.Append(testIdentity); CleanupStack::Pop(testIdentity); } CleanupStack::PopAndDestroy(tcPart); tokenParsed = ETrue; } // '/VERBOSE' option pos = tc->FindF(KArgVerboseOutput); if (pos != KErrNotFound) { gVerboseOutput = ETrue; tokenParsed = ETrue; // turn on logging of test Printf() output to serial debug/log at the same time test.SetLogged(ETrue); } // '/LOOPO:n' option (Set #times to run open/close tests amongst others) pos = tc->FindF(KArgSetOpenIterations); if (pos != KErrNotFound) { TPtrC iterationStr = tc->Right(tc->Length() - pos - KArgSetOpenIterations().Length()); TLex lex(iterationStr); lex.Val(gOpenIterations); MINMAX_CLAMPVALUE(gOpenIterations, OPEN_MINREPEATS, OPEN_MAXREPEATS); tokenParsed = ETrue; } // '/LOOPM:n' option (Set # of allocs to start at for OOM test) pos = tc->FindF(KArgSetOOMIterations); if (pos != KErrNotFound) { TPtrC iterationStr = tc->Right(tc->Length() - pos - KArgSetOOMIterations().Length()); TLex lex(iterationStr); lex.Val(gOOMIterations); MINMAX_CLAMPVALUE(gOOMIterations, OOM_MINREPEATS, OOM_MAXREPEATS); tokenParsed = ETrue; } // '/VID:nnnn' option (Set Symbian or other VID-Pid example /VID:0670) pos = tc->FindF(KArgOverrideVidPid); if (pos != KErrNotFound) { TPtrC vidpidStr = tc->Right(tc->Length() - pos - KArgOverrideVidPid().Length()); TUint16 prodID; TLex lex(vidpidStr); if (KErrNone == lex.Val(prodID, EHex)) { if (prodID> 0xFFFF) prodID = 0xFFFF; tokenParsed = ETrue; LOG_VERBOSE2(_L(" accept param %04X \n\n"), prodID); if(gVerboseOutput) { OstTrace1(TRACE_VERBOSE, CTESTENGINE_PROCESSCOMMANDLINEL_DUP05, " accept param %04X \n\n", prodID); } gUSBVidPid = prodID; // replace the vid-pid with the user-supplied one } else { // print error test.Printf(_L("Warning: VID+PID '%lS' not parsed .\n"), tc); OstTraceExt1(TRACE_NORMAL, CTESTENGINE_PROCESSCOMMANDLINEL_DUP06, "Warning: VID+PID '%lS' not parsed .\n", *tc); } } // '/SLAVE' (peer) pos = tc->FindF(KArgSetRoleSlave); if (pos != KErrNotFound) { gTestRoleMaster = EFalse; tokenParsed = ETrue; } // '/MASTER' - default role pos = tc->FindF(KArgSetRoleMaster); // note that master is the default role, so this parameter is optional if (pos != KErrNotFound) { gTestRoleMaster = ETrue; tokenParsed = ETrue; } if (!tokenParsed) { // warn about unparsed parameter test.Printf(_L("Warning: '%lS'??? not parsed\n"), tc); OstTraceExt1(TRACE_NORMAL, CTESTENGINE_PROCESSCOMMANDLINEL_DUP07, "Warning: '%lS'??? not parsed\n", *tc); iHelpRequested = ETrue; } // next parameter *tc = args.NextToken(); } CleanupStack::PopAndDestroy(tc); CleanupStack::PopAndDestroy(cmdLine); }
int main(int argc, char *argv[]) { #ifdef HAVE_MPI Teuchos::GlobalMPISession mpiSession(&argc, &argv,0); choice::MpiArgs args( argc, argv ); #else choice::Args args( argc, argv ); #endif int commRank = Teuchos::GlobalMPISession::getRank(); int numProcs = Teuchos::GlobalMPISession::getNProc(); // Required arguments double epsilon = args.Input<double>("--epsilon", "diffusion parameter"); int numRefs = args.Input<int>("--numRefs", "number of refinement steps"); bool enforceLocalConservation = args.Input<bool>("--conserve", "enforce local conservation"); bool graphNorm = args.Input<bool>("--graphNorm", "use the graph norm rather than robust test norm"); // Optional arguments (have defaults) bool highLiftAirfoil = args.Input("--highLift", "use high lift airfoil rather than NACA0012", false); args.Process(); //////////////////// DECLARE VARIABLES /////////////////////// // define test variables VarFactory varFactory; VarPtr tau = varFactory.testVar("tau", HDIV); VarPtr v = varFactory.testVar("v", HGRAD); // define trial variables VarPtr uhat = varFactory.traceVar("uhat"); VarPtr beta_n_u_minus_sigma_n = varFactory.fluxVar("fhat"); VarPtr u = varFactory.fieldVar("u"); VarPtr sigma = varFactory.fieldVar("sigma", VECTOR_L2); vector<double> beta; beta.push_back(1.0); beta.push_back(0.25); //////////////////// DEFINE BILINEAR FORM /////////////////////// BFPtr bf = Teuchos::rcp( new BF(varFactory) ); // tau terms: bf->addTerm(sigma / epsilon, tau); bf->addTerm(u, tau->div()); bf->addTerm(-uhat, tau->dot_normal()); // v terms: bf->addTerm( sigma, v->grad() ); bf->addTerm( beta * u, - v->grad() ); bf->addTerm( beta_n_u_minus_sigma_n, v); //////////////////// DEFINE INNER PRODUCT(S) /////////////////////// IPPtr ip = Teuchos::rcp(new IP); if (graphNorm) { ip = bf->graphNorm(); } else { // robust test norm FunctionPtr ip_scaling = Teuchos::rcp( new EpsilonScaling(epsilon) ); if (!enforceLocalConservation) ip->addTerm( ip_scaling * v ); ip->addTerm( sqrt(epsilon) * v->grad() ); // Weight these two terms for inflow ip->addTerm( beta * v->grad() ); ip->addTerm( tau->div() ); ip->addTerm( ip_scaling/sqrt(epsilon) * tau ); if (enforceLocalConservation) ip->addZeroMeanTerm( v ); } //////////////////// SPECIFY RHS /////////////////////// Teuchos::RCP<RHSEasy> rhs = Teuchos::rcp( new RHSEasy ); FunctionPtr f = Teuchos::rcp( new ConstantScalarFunction(0.0) ); rhs->addTerm( f * v ); // obviously, with f = 0 adding this term is not necessary! //////////////////// CREATE BCs /////////////////////// Teuchos::RCP<BCEasy> bc = Teuchos::rcp( new BCEasy ); Teuchos::RCP<PenaltyConstraints> pc = Teuchos::rcp( new PenaltyConstraints ); SpatialFilterPtr lBoundary = Teuchos::rcp( new LeftBoundary ); SpatialFilterPtr tBoundary = Teuchos::rcp( new TopBoundary ); SpatialFilterPtr bBoundary = Teuchos::rcp( new BottomBoundary ); SpatialFilterPtr rBoundary = Teuchos::rcp( new RightBoundary ); FunctionPtr n = Teuchos::rcp( new UnitNormalFunction ); SpatialFilterPtr airfoilInflowBoundary = Teuchos::rcp( new AirfoilInflowBoundary(beta) ); SpatialFilterPtr airfoilOutflowBoundary = Teuchos::rcp( new AirfoilOutflowBoundary(beta) ); FunctionPtr u0 = Teuchos::rcp( new ZeroBC ); FunctionPtr u1 = Teuchos::rcp( new OneBC ); bc->addDirichlet(beta_n_u_minus_sigma_n, lBoundary, u0); bc->addDirichlet(beta_n_u_minus_sigma_n, bBoundary, u0); // bc->addDirichlet(uhat, airfoilInflowBoundary, u1); // bc->addDirichlet(uhat, tBoundary, u0); bc->addDirichlet(beta_n_u_minus_sigma_n, airfoilInflowBoundary, beta*n*u1); bc->addDirichlet(uhat, airfoilOutflowBoundary, u1); // pc->addConstraint(beta*uhat->times_normal() - beta_n_u_minus_sigma_n == u0, rBoundary); // pc->addConstraint(beta*uhat->times_normal() - beta_n_u_minus_sigma_n == u0, tBoundary); //////////////////// BUILD MESH /////////////////////// // define nodes for mesh int H1Order = 3, pToAdd = 2; Teuchos::RCP<Mesh> mesh; if (highLiftAirfoil) mesh = Mesh::readTriangle(Camellia_MeshDir+"HighLift/HighLift.1", bf, H1Order, pToAdd); else mesh = Mesh::readTriangle(Camellia_MeshDir+"NACA0012/NACA0012.1", bf, H1Order, pToAdd); //////////////////// SOLVE & REFINE /////////////////////// Teuchos::RCP<Solution> solution = Teuchos::rcp( new Solution(mesh, bc, rhs, ip) ); // solution->setFilter(pc); if (enforceLocalConservation) { FunctionPtr zero = Teuchos::rcp( new ConstantScalarFunction(0.0) ); solution->lagrangeConstraints()->addConstraint(beta_n_u_minus_sigma_n == zero); } double energyThreshold = 0.2; // for mesh refinements RefinementStrategy refinementStrategy( solution, energyThreshold ); VTKExporter exporter(solution, mesh, varFactory); for (int refIndex=0; refIndex<=numRefs; refIndex++) { solution->solve(false); if (commRank == 0) { stringstream outfile; if (highLiftAirfoil) outfile << "highlift_" << refIndex; else outfile << "naca0012_" << refIndex; exporter.exportSolution(outfile.str()); // Check local conservation FunctionPtr flux = Teuchos::rcp( new PreviousSolutionFunction(solution, beta_n_u_minus_sigma_n) ); FunctionPtr zero = Teuchos::rcp( new ConstantScalarFunction(0.0) ); Teuchos::Tuple<double, 3> fluxImbalances = checkConservation(flux, zero, varFactory, mesh); cout << "Mass flux: Largest Local = " << fluxImbalances[0] << ", Global = " << fluxImbalances[1] << ", Sum Abs = " << fluxImbalances[2] << endl; } if (refIndex < numRefs) { // refinementStrategy.refine(commRank==0); // print to console on commRank 0 // Try pseudo-hp adaptive vector<int> cellsToRefine; vector<int> cells_h; vector<int> cells_p; refinementStrategy.getCellsAboveErrorThreshhold(cellsToRefine); for (int i=0; i < cellsToRefine.size(); i++) if (sqrt(mesh->getCellMeasure(cellsToRefine[i])) < epsilon) { int pOrder = mesh->cellPolyOrder(cellsToRefine[i]); if (pOrder < 8) cells_p.push_back(cellsToRefine[i]); else cells_h.push_back(cellsToRefine[i]); } else cells_h.push_back(cellsToRefine[i]); refinementStrategy.pRefineCells(mesh, cells_p); refinementStrategy.hRefineCells(mesh, cells_h); } } return 0; }
void Editbox::onSemanticInputEvent(SemanticEventArgs& e) { if (isDisabled()) return; if (e.d_semanticValue == SV_SelectAll && e.d_payload.source == CIS_Left) { d_dragAnchorIdx = 0; setCaretIndex(getText().length()); setSelection(d_dragAnchorIdx, d_caretPos); ++e.handled; } else if (e.d_semanticValue == SV_SelectWord && e.d_payload.source == CIS_Left) { // if masked, set up to select all if (isTextMaskingEnabled()) { d_dragAnchorIdx = 0; setCaretIndex(getText().length()); } // not masked, so select the word that was double-clicked. else { d_dragAnchorIdx = TextUtils::getWordStartIdx(getText(), (d_caretPos == getText().length()) ? d_caretPos : d_caretPos + 1); d_caretPos = TextUtils::getNextWordStartIdx(getText(), d_caretPos); } // perform actual selection operation. setSelection(d_dragAnchorIdx, d_caretPos); ++e.handled; } if (e.handled == 0 && hasInputFocus()) { if (isReadOnly()) { Window::onSemanticInputEvent(e); return; } if (getSelectionLength() == 0 && isSelectionSemanticValue(e.d_semanticValue)) d_dragAnchorIdx = d_caretPos; // Check if the semantic value to be handled is of a general type and can thus be // handled via common EditboxBase handlers bool isSemanticValueHandled = handleBasicSemanticValue(e); // If the semantic value was not handled, check for specific values if (!isSemanticValueHandled) { // We assume it will be handled now, if not it will be set to false in default-case isSemanticValueHandled = true; switch (e.d_semanticValue) { case SV_Confirm: { WindowEventArgs args(this); // Fire 'input accepted' event onTextAcceptedEvent(args); break; } case SV_GoToStartOfLine: handleHome(false); break; case SV_GoToEndOfLine: handleEnd(false); break; case SV_SelectToStartOfLine: handleHome(true); break; case SV_SelectToEndOfLine: handleEnd(true); break; default: Window::onSemanticInputEvent(e); isSemanticValueHandled = false; } } if (isSemanticValueHandled) ++e.handled; } }
void CClientApp::parseArgs(int argc, const char* const* argv) { // asserts values, sets defaults, and parses args int i; CApp::parseArgs(argc, argv, i); // exactly one non-option argument (server-address) if (i == argc) { LOG((CLOG_PRINT "%s: a server address or name is required" BYE, args().m_pname, args().m_pname)); m_bye(kExitArgs); } if (i + 1 != argc) { LOG((CLOG_PRINT "%s: unrecognized option `%s'" BYE, args().m_pname, argv[i], args().m_pname)); m_bye(kExitArgs); } // save server address try { *args().m_serverAddress = CNetworkAddress(argv[i], kDefaultPort); args().m_serverAddress->resolve(); } catch (XSocketAddress& e) { // allow an address that we can't look up if we're restartable. // we'll try to resolve the address each time we connect to the // server. a bad port will never get better. patch by Brent // Priddy. if (!args().m_restartable || e.getError() == XSocketAddress::kBadPort) { LOG((CLOG_PRINT "%s: %s" BYE, args().m_pname, e.what(), args().m_pname)); m_bye(kExitFailed); } } // set log filter if (!CLOG->setFilter(args().m_logFilter)) { LOG((CLOG_PRINT "%s: unrecognized log level `%s'" BYE, args().m_pname, args().m_logFilter, args().m_pname)); m_bye(kExitArgs); } // identify system LOG((CLOG_INFO "%s Client on %s %s", kAppVersion, ARCH->getOSName().c_str(), ARCH->getPlatformName().c_str())); loggingFilterWarning(); }
void TrackerHelper::trackMarkers(const std::list<TrackMarkerPtr >& markers, int start, int end, int frameStep, OverlaySupport* overlayInteract) { if ( markers.empty() ) { Q_EMIT trackingFinished(); return; } TrackerParamsProviderPtr provider = _imp->provider.lock(); if (!provider) { Q_EMIT trackingFinished(); return; } NodePtr trackerNode = provider->getTrackerNode(); if (!trackerNode) { Q_EMIT trackingFinished(); return; } if (trackerNode->hasMandatoryInputDisconnected()) { Q_EMIT trackingFinished(); return; } ViewerInstancePtr viewer; if (overlayInteract) { viewer = overlayInteract->getInternalViewerNode(); } // The channels we are going to use for tracking bool enabledChannels[3]; provider->getTrackChannels(&enabledChannels[0], &enabledChannels[1], &enabledChannels[2]); double formatWidth, formatHeight; Format f; trackerNode->getApp()->getProject()->getProjectDefaultFormat(&f); formatWidth = f.width(); formatHeight = f.height(); bool autoKeyingOnEnabledParamEnabled = provider->canDisableMarkersAutomatically(); /// The accessor and its cache is local to a track operation, it is wiped once the whole sequence track is finished. boost::shared_ptr<TrackerFrameAccessor> accessor( new TrackerFrameAccessor(trackerNode, enabledChannels, formatHeight) ); boost::shared_ptr<mv::AutoTrack> trackContext( new mv::AutoTrack( accessor.get() ) ); std::vector<TrackMarkerAndOptionsPtr > trackAndOptions; mv::TrackRegionOptions mvOptions; /* Get the global parameters for the LivMV track: pre-blur sigma, No iterations, normalized intensities, etc... */ _imp->beginLibMVOptionsForTrack(&mvOptions); /* For the given markers, do the following: - Get the "User" keyframes that have been set and create a LibMV marker for each keyframe as well as for the "start" time - Set the "per-track" parameters that were given by the user, that is the mv::TrackRegionOptions - t->mvMarker will contain the marker that evolves throughout the tracking */ int trackIndex = 0; for (std::list<TrackMarkerPtr >::const_iterator it = markers.begin(); it != markers.end(); ++it, ++trackIndex) { if (autoKeyingOnEnabledParamEnabled) { (*it)->setEnabledAtTime(start, true); } TrackMarkerAndOptionsPtr t(new TrackMarkerAndOptions); t->natronMarker = *it; int mode_i = (*it)->getMotionModelKnob()->getValue(); mvOptions.mode = motionModelIndexToLivMVMode(mode_i); // Set a keyframe on the marker to initialize its position { KnobDoublePtr centerKnob = (*it)->getCenterKnob(); std::vector<double> values(2); values[0] = centerKnob->getValueAtTime(start, DimIdx(0)); values[1] = centerKnob->getValueAtTime(start, DimIdx(1)); centerKnob->setValueAtTimeAcrossDimensions(start, values); } // For a translation warp, we do not need to add an animation curve for the pattern which stays constant. if (mvOptions.mode != libmv::TrackRegionOptions::TRANSLATION) { KnobDoublePtr patternCorners[4]; patternCorners[0] = (*it)->getPatternBtmLeftKnob(); patternCorners[1] = (*it)->getPatternBtmRightKnob(); patternCorners[2] = (*it)->getPatternTopRightKnob(); patternCorners[3] = (*it)->getPatternTopLeftKnob(); for (int c = 0; c < 4; ++c) { KnobDoublePtr k = patternCorners[c]; std::vector<double> values(2); values[0] = k->getValueAtTime(start, DimIdx(0)); values[1] = k->getValueAtTime(start, DimIdx(1)); k->setValueAcrossDimensions(values); } } std::set<double> userKeys; t->natronMarker->getMasterKeyFrameTimes(ViewIdx(0), &userKeys); if ( userKeys.empty() ) { // Set a user keyframe on tracking start if the marker does not have any user keys t->natronMarker->setKeyFrame(start, ViewSetSpec(0), 0); } PreviouslyTrackedFrameSet previousFramesOrdered; // Make sure to create a marker at the start time userKeys.insert(start); // Add a libmv marker for all keyframes for (std::set<double>::iterator it2 = userKeys.begin(); it2 != userKeys.end(); ++it2) { // Add the marker to the markers ordered only if it can contribute to predicting its next position if ( ( (frameStep > 0) && (*it2 <= start) ) || ( (frameStep < 0) && (*it2 >= start) ) ) { previousFramesOrdered.insert( PreviouslyComputedTrackFrame(*it2, true) ); } } //For all already tracked frames which are not keyframes, add them to the AutoTrack too std::set<double> centerKeys; t->natronMarker->getCenterKeyframes(¢erKeys); for (std::set<double>::iterator it2 = centerKeys.begin(); it2 != centerKeys.end(); ++it2) { if ( userKeys.find(*it2) != userKeys.end() ) { continue; } // Add the marker to the markers ordered only if it can contribute to predicting its next position if ( ( ( (frameStep > 0) && (*it2 < start) ) || ( (frameStep < 0) && (*it2 > start) ) ) ) { previousFramesOrdered.insert( PreviouslyComputedTrackFrame(*it2, false) ); } } // Taken from libmv, only initialize the filter to this amount of frames (max) const int max_frames_to_predict_from = 20; std::list<mv::Marker> previouslyComputedMarkersOrdered; // Find the first keyframe that's not considered to go before start or end PreviouslyTrackedFrameSet::iterator prevFramesIt = previousFramesOrdered.lower_bound(PreviouslyComputedTrackFrame(start, false)); if (frameStep < 0) { if (prevFramesIt != previousFramesOrdered.end()) { while (prevFramesIt != previousFramesOrdered.end() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) { mv::Marker mvMarker; TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker); trackContext->AddMarker(mvMarker); // insert in the front of the list so that the order is reversed previouslyComputedMarkersOrdered.push_front(mvMarker); ++prevFramesIt; } } // previouslyComputedMarkersOrdered is now ordererd by decreasing order } else { if (prevFramesIt != previousFramesOrdered.end()) { while (prevFramesIt != previousFramesOrdered.begin() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) { mv::Marker mvMarker; TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker); trackContext->AddMarker(mvMarker); // insert in the front of the list so that the order is reversed previouslyComputedMarkersOrdered.push_front(mvMarker); --prevFramesIt; } if (prevFramesIt == previousFramesOrdered.begin() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) { mv::Marker mvMarker; TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker); trackContext->AddMarker(mvMarker); // insert in the front of the list so that the order is reversed previouslyComputedMarkersOrdered.push_front(mvMarker); } } // previouslyComputedMarkersOrdered is now ordererd by increasing order } // There must be at least 1 marker at the start time assert( !previouslyComputedMarkersOrdered.empty() ); // Initialise the kalman state with the marker at the position std::list<mv::Marker>::iterator mIt = previouslyComputedMarkersOrdered.begin(); t->mvState.Init(*mIt, frameStep); ++mIt; for (; mIt != previouslyComputedMarkersOrdered.end(); ++mIt) { mv::Marker predictedMarker; if ( !t->mvState.PredictForward(mIt->frame, &predictedMarker) ) { break; } else { t->mvState.Update(*mIt); } } t->mvOptions = mvOptions; trackAndOptions.push_back(t); } /* Launch tracking in the scheduler thread. */ boost::shared_ptr<TrackArgs> args( new TrackArgs(start, end, frameStep, trackerNode->getApp()->getTimeLine(), viewer, trackContext, accessor, trackAndOptions, formatWidth, formatHeight, autoKeyingOnEnabledParamEnabled) ); _imp->scheduler->track(args); } // TrackerHelper::trackMarkers
void PostRouteHandler::handleRequest(ServerEventArgs& evt) { try { Poco::Net::HTTPServerResponse& response = evt.response(); // This uuid helps us track form progress updates. std::string postId = Poco::UUIDGenerator::defaultGenerator().createOne().toString(); // Get the content type header (already checked in parent route). Poco::Net::MediaType contentType(evt.request().get("Content-Type", "")); if (contentType.matches(POST_CONTENT_TYPE_URLENCODED) || contentType.matches(POST_CONTENT_TYPE_MULTIPART)) { // Prepare the upload directory if needed. if (contentType.matches(POST_CONTENT_TYPE_MULTIPART)) { ofDirectory _uploadFolder(route().settings().getUploadFolder()); if (!_uploadFolder.exists()) { ofLogError("PostRouteHandler::handleRequest") << "Upload folder does not exist and cannot be created."; response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); route().handleRequest(evt); return; } } PostRouteFileHandler postRoutePartHandler(route(), evt, postId); Poco::Net::HTMLForm form(contentType.toString()); form.setFieldLimit(route().settings().getFieldLimit()); form.load(evt.request(), evt.request().stream(), postRoutePartHandler); PostFormEventArgs args(evt, postId, form); ofNotifyEvent(route().events.onHTTPFormEvent, args, &route()); std::string redirectDestination = form.get("destination", ""); if (!redirectDestination.empty()) { response.redirect(redirectDestination); return; } } else { // Poco::Net::HTMLForm, like php does not handle text/plain because // it cannot be unambiguously encoded. Here we simply return // the raw text with the event. std::string result; Poco::StreamCopier::copyToString(evt.request().stream(), result); IO::ByteBuffer buffer(result); PostEventArgs args(evt, postId, buffer); ofNotifyEvent(route().events.onHTTPPostEvent, args, &route()); } if (response.sent()) { return; } else if (!route().settings().getUploadRedirect().empty()) { response.redirect(route().settings().getUploadRedirect()); return; } else { // Send a successful 200 and be done. response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK); response.setContentLength(0); response.send(); return; } } catch (const Poco::Exception& exc) { evt.response().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.displayText()); } catch (const std::exception& exc) { evt.response().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.what()); } catch (...) { evt.response().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); } }