bool IServerApp::OnMessage( Packet* pMsg ) { CHECK_MSG_SIZE(stMsg,pMsg->_len) ; stMsg* pmsg = (stMsg*)pMsg->_orgdata ; if ( pmsg->cSysIdentifer == ID_MSG_VERIFY ) { LOGFMTI("no need recieve verify msg") ; return true ; } stMsg* pRet = pmsg; if ( pRet->usMsgType != MSG_TRANSER_DATA ) { LOGFMTE("why msg type is not transfer data , type = %d",pRet->usMsgType ) ; return true; } stMsgTransferData* pData = (stMsgTransferData*)pRet ; stMsg* preal = (stMsg*)( pMsg->_orgdata + sizeof(stMsgTransferData)); // check async request if ( preal->usMsgType == MSG_ASYNC_REQUEST ) { stMsgAsyncRequest* pRet = (stMsgAsyncRequest*)preal ; Json::Value jsReqContent ; if ( pRet->nReqContentLen > 0 ) { char* pBuffer = (char*)pRet ; pBuffer += sizeof(stMsgAsyncRequest) ; Json::Reader jsReader ; jsReader.parse(pBuffer,pBuffer + pRet->nReqContentLen,jsReqContent,false); } Json::Value jsResult ; if ( !onAsyncRequest(pRet->nReqType,jsReqContent,jsResult) ) { LOGFMTE("async request type = %u , not process from port = %u",pRet->nReqType,pData->nSenderPort) ; assert(0 && "must process the req" ); } stMsgAsyncRequestRet msgBack ; msgBack.cSysIdentifer = (eMsgPort)pData->nSenderPort ; msgBack.nReqSerailID = pRet->nReqSerailID ; msgBack.nResultContentLen = 0 ; if ( jsResult.isNull() == true ) { sendMsg(pData->nSessionID,(char*)&msgBack,sizeof(msgBack)) ; } else { Json::StyledWriter jsWrite ; auto strResult = jsWrite.write(jsResult); msgBack.nResultContentLen = strResult.size() ; CAutoBuffer auBuffer(sizeof(msgBack) + msgBack.nResultContentLen ); auBuffer.addContent(&msgBack,sizeof(msgBack)); auBuffer.addContent(strResult.c_str(),msgBack.nResultContentLen) ; sendMsg(pData->nSessionID,auBuffer.getBufferPtr(),auBuffer.getContentSize()) ; } return true ; } if ( preal->usMsgType == MSG_JSON_CONTENT ) { stMsgJsonContent* pRet = (stMsgJsonContent*)preal ; char* pBuffer = (char*)preal ; pBuffer += sizeof(stMsgJsonContent); //#ifdef __DEBUG static char pLog[1024] = { 0 }; if ( pRet->nJsLen >= 1024 ) { LOGFMTE("session id = %u send a invalid len json msg, len = %u ",pData->nSessionID,pRet->nJsLen) ; return true; } memset(pLog,0,sizeof(pLog)) ; memcpy_s(pLog,sizeof(pLog),pBuffer,pRet->nJsLen); //LOGFMTD("session id = %u rec : %s",pData->nSessionID,pLog); //#endif // __DEBUG Json::Reader reader ; Json::Value rootValue ; auto bRet = reader.parse(pBuffer,pBuffer + pRet->nJsLen,rootValue,false) ; if ( !bRet ) { LOGFMTE("session id = %u send a invalid json msg format error ",pData->nSessionID ) ; return true ; } if ( rootValue[JS_KEY_MSG_TYPE].isNull() || rootValue[JS_KEY_MSG_TYPE].isNumeric() == false ) { LOGFMTE("not have msg key type , session id = %u rec : %s",pData->nSessionID,pLog); return true ; } uint16_t nMsgType = rootValue[JS_KEY_MSG_TYPE].asUInt() ; if ( onLogicMsg(rootValue,nMsgType,(eMsgPort)pData->nSenderPort,pData->nSessionID) ) { return true ; } LOGFMTE("unprocessed json from port = %d , session id = %d js : %s",pData->nSenderPort,pData->nSessionID,pLog) ; return false ; } // normal logic msg ; if ( onLogicMsg(preal,(eMsgPort)pData->nSenderPort,pData->nSessionID) ) { return true ; } LOGFMTE("unprocessed msg = %d , from port = %d , session id = %d",preal->usMsgType,pData->nSenderPort,pData->nSessionID) ; return false ; }
void TestController::traverseTestSuite(TestSuite* testSuite) { auto scheduler = _director->getScheduler(); int testIndex = 0; float testCaseDuration = 0.0f; _logIndentation += LOG_INDENTATION; logEx("%s%sBegin traverse TestSuite:%s", LOG_TAG, _logIndentation.c_str(), testSuite->getTestName().c_str()); _logIndentation += LOG_INDENTATION; auto logIndentation = _logIndentation; for (auto& callback : testSuite->_testCallbacks) { auto testName = testSuite->_childTestNames[testIndex++]; Scene* testScene = nullptr; TestCase* testCase = nullptr; TransitionScene* transitionScene = nullptr; if (_stopAutoTest) break; while (_isRunInBackground) { logEx("_director is paused"); _sleepCondition.wait_for(_sleepUniqueLock, std::chrono::milliseconds(500)); } //Run test case in the cocos[GL] thread. scheduler->performFunctionInCocosThread([&, logIndentation, testName](){ if (_stopAutoTest) return; logEx("%s%sRun test:%s.", LOG_TAG, logIndentation.c_str(), testName.c_str()); auto scene = callback(); if (_stopAutoTest) return; if (scene) { transitionScene = dynamic_cast<TransitionScene*>(scene); if (transitionScene) { testCase = (TestCase*)transitionScene->getInScene(); testCaseDuration = transitionScene->getDuration() + 0.5f; } else { testCase = (TestCase*)scene; testCaseDuration = testCase->getDuration(); } testCase->setTestSuite(testSuite); testCase->setTestCaseName(testName); _director->replaceScene(scene); testScene = scene; } }); if (_stopAutoTest) break; //Wait for the test case be created. float waitTime = 0.0f; while (!testScene && !_stopAutoTest) { _sleepCondition.wait_for(_sleepUniqueLock, std::chrono::milliseconds(50)); if (!_isRunInBackground) { waitTime += 0.05f; } if (waitTime > CREATE_TIME_OUT) { logEx("%sCreate test %s time out", LOG_TAG, testName.c_str()); _stopAutoTest = true; break; } } if (_stopAutoTest) break; //Wait for test completed. _sleepCondition.wait_for(_sleepUniqueLock, std::chrono::milliseconds(int(1000 * testCaseDuration))); if (transitionScene == nullptr) { waitTime = 0.0f; while (!_stopAutoTest && testCase->getRunTime() < testCaseDuration) { _sleepCondition.wait_for(_sleepUniqueLock, std::chrono::milliseconds(50)); if (!_isRunInBackground) { waitTime += 0.05f; } if (waitTime > TEST_TIME_OUT) { logEx("%sRun test %s time out", LOG_TAG, testName.c_str()); _stopAutoTest = true; break; } } if (!_stopAutoTest) { //Check the result of test. checkTest(testCase); } } } if (!_stopAutoTest) { //Backs up one level and release TestSuite object. auto parentTest = testSuite->_parentTest; scheduler->performFunctionInCocosThread([&](){ parentTest->runThisTest(); }); _sleepCondition.wait_for(_sleepUniqueLock, std::chrono::milliseconds(1000)); testSuite->release(); } _logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION)); _logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION)); }
const char* entity_header_get_content_encoding(entity_header eh) { assert(eh != NULL); assert(entity_header_flag_is_set(eh, ENTITY_HEADER_CONTENT_ENCODING_SET)); return c_str(eh->content_encoding); }
const char* entity_header_get_content_location(entity_header eh) { assert(eh != NULL); assert(entity_header_flag_is_set(eh, ENTITY_HEADER_CONTENT_LOCATION_SET)); return c_str(eh->content_location); }
bool Effect::initGLProgramState(const std::string &fragmentFilename) { auto fileUtiles = FileUtils::getInstance(); auto fragmentFullPath = fileUtiles->fullPathForFilename(fragmentFilename); auto fragSource = fileUtiles->getStringFromFile(fragmentFullPath); auto glprogram = GLProgram::createWithByteArrays(ccPositionTextureColor_noMVP_vert, fragSource.c_str()); _glprogramstate = GLProgramState::getOrCreateWithGLProgram(glprogram); _glprogramstate->retain(); return _glprogramstate != nullptr; }
std::unique_ptr<Process> createSmallDeformationProcess( MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<ProcessVariable> const& variables, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, unsigned const integration_order, BaseLib::ConfigTree const& config) { //! \ogs_file_param{prj__processes__process__type} config.checkConfigParameter("type", "SMALL_DEFORMATION_WITH_LIE"); DBUG("Create SmallDeformationProcess with LIE."); // Process variables //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__process_variables} auto const pv_conf = config.getConfigSubtree("process_variables"); auto range = //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__process_variables__process_variable} pv_conf.getConfigParameterList<std::string>("process_variable"); std::vector<std::reference_wrapper<ProcessVariable>> per_process_variables; std::size_t n_var_du = 0; for (std::string const& pv_name : range) { if (pv_name != "displacement" && pv_name.find("displacement_jump") != 0) { OGS_FATAL( "Found a process variable name '%s'. It should be " "'displacement' or 'displacement_jumpN' or " "'displacement_junctionN'"); } if (pv_name.find("displacement_jump") == 0) { n_var_du++; } auto variable = std::find_if(variables.cbegin(), variables.cend(), [&pv_name](ProcessVariable const& v) { return v.getName() == pv_name; }); if (variable == variables.end()) { OGS_FATAL( "Could not find process variable '%s' in the provided " "variables " "list for config tag <%s>.", pv_name.c_str(), "process_variable"); } DBUG("Found process variable '%s' for config tag <%s>.", variable->getName().c_str(), "process_variable"); per_process_variables.emplace_back( const_cast<ProcessVariable&>(*variable)); } if (n_var_du < 1) { OGS_FATAL("No displacement jump variables are specified"); } DBUG("Associate displacement with process variable '%s'.", per_process_variables.back().get().getName().c_str()); if (per_process_variables.back().get().getNumberOfComponents() != DisplacementDim) { OGS_FATAL( "Number of components of the process variable '%s' is different " "from the displacement dimension: got %d, expected %d", per_process_variables.back().get().getName().c_str(), per_process_variables.back().get().getNumberOfComponents(), DisplacementDim); } std::vector<std::vector<std::reference_wrapper<ProcessVariable>>> process_variables; process_variables.push_back(std::move(per_process_variables)); auto solid_constitutive_relations = MaterialLib::Solids::createConstitutiveRelations<DisplacementDim>( parameters, config); // Fracture constitutive relation. // read type; auto const fracture_model_config = //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__fracture_model} config.getConfigSubtree("fracture_model"); auto const frac_type = //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__fracture_model__type} fracture_model_config.peekConfigParameter<std::string>("type"); std::unique_ptr<MaterialLib::Fracture::FractureModelBase<DisplacementDim>> fracture_model = nullptr; if (frac_type == "LinearElasticIsotropic") { fracture_model = MaterialLib::Fracture::createLinearElasticIsotropic< DisplacementDim>(parameters, fracture_model_config); } else if (frac_type == "MohrCoulomb") { fracture_model = MaterialLib::Fracture::createMohrCoulomb<DisplacementDim>( parameters, fracture_model_config); } else if (frac_type == "CohesiveZoneModeI") { fracture_model = MaterialLib::Fracture::CohesiveZoneModeI::createCohesiveZoneModeI< DisplacementDim>(parameters, fracture_model_config); } else { OGS_FATAL( "Cannot construct fracture constitutive relation of given type " "'%s'.", frac_type.c_str()); } // Fracture properties std::vector<FractureProperty> fracture_properties; for ( auto fracture_properties_config : //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__fracture_properties} config.getConfigSubtreeList("fracture_properties")) { fracture_properties.emplace_back( fracture_properties.size(), //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__fracture_properties__material_id} fracture_properties_config.getConfigParameter<int>("material_id"), ParameterLib::findParameter<double>( //! \ogs_file_param_special{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__fracture_properties__initial_aperture} fracture_properties_config, "initial_aperture", parameters, 1)); } if (n_var_du < fracture_properties.size()) { OGS_FATAL( "The number of displacement jumps and the number of " "<fracture_properties> " "are not consistent"); } // Reference temperature const auto& reference_temperature = //! \ogs_file_param{prj__processes__process__SMALL_DEFORMATION_WITH_LIE__reference_temperature} config.getConfigParameter<double>( "reference_temperature", std::numeric_limits<double>::quiet_NaN()); SmallDeformationProcessData<DisplacementDim> process_data( materialIDs(mesh), std::move(solid_constitutive_relations), std::move(fracture_model), std::move(fracture_properties), reference_temperature); SecondaryVariableCollection secondary_variables; NumLib::NamedFunctionCaller named_function_caller( {"SmallDeformation_displacement"}); ProcessLib::createSecondaryVariables(config, secondary_variables, named_function_caller); return std::make_unique<SmallDeformationProcess<DisplacementDim>>( mesh, std::move(jacobian_assembler), parameters, integration_order, std::move(process_variables), std::move(process_data), std::move(secondary_variables), std::move(named_function_caller)); }
bool run(const char* config_file, const char* config_arguments, bool sleep_after_init, std::string& app_list) { dsn_core_init(); ::dsn::task::set_tls_dsn_context(nullptr, nullptr, nullptr); dsn_all.engine_ready = false; dsn_all.config_completed = false; dsn_all.tool = nullptr; dsn_all.engine = &::dsn::service_engine::instance(); dsn_all.config.reset(new ::dsn::configuration()); dsn_all.memory = nullptr; dsn_all.magic = 0xdeadbeef; if (!dsn_all.config->load(config_file, config_arguments)) { printf("Fail to load config file %s\n", config_file); return false; } // pause when necessary if (dsn_all.config->get_value<bool>("core", "pause_on_start", false, "whether to pause at startup time for easier debugging")) { #if defined(_WIN32) printf("\nPause for debugging (pid = %d)...\n", static_cast<int>(::GetCurrentProcessId())); #else printf("\nPause for debugging (pid = %d)...\n", static_cast<int>(getpid())); #endif getchar(); } // regiser external app roles by loading all shared libraries // so all code and app factories are automatically registered dsn::service_spec::load_app_shared_libraries(dsn_all.config); for (int i = 0; i <= dsn_task_code_max(); i++) { dsn_all.task_specs.push_back(::dsn::task_spec::get(i)); } // initialize global specification from config file ::dsn::service_spec spec; spec.config = dsn_all.config; if (!spec.init()) { printf("error in config file %s, exit ...\n", config_file); return false; } dsn_all.config_completed = true; // setup data dir auto& data_dir = spec.data_dir; dassert(!dsn::utils::filesystem::file_exists(data_dir), "%s should not be a file.", data_dir.c_str()); if (!dsn::utils::filesystem::directory_exists(data_dir.c_str())) { if (!dsn::utils::filesystem::create_directory(data_dir)) { dassert(false, "Fail to create %s.", data_dir.c_str()); } } std::string cdir; if (!dsn::utils::filesystem::get_absolute_path(data_dir.c_str(), cdir)) { dassert(false, "Fail to get absolute path from %s.", data_dir.c_str()); } spec.data_dir = cdir; // setup coredump dir spec.dir_coredump = ::dsn::utils::filesystem::path_combine(cdir, "coredumps"); dsn::utils::filesystem::create_directory(spec.dir_coredump); ::dsn::utils::coredump::init(spec.dir_coredump.c_str()); // setup log dir spec.dir_log = ::dsn::utils::filesystem::path_combine(cdir, "logs"); dsn::utils::filesystem::create_directory(spec.dir_log); // init tools dsn_all.tool = ::dsn::utils::factory_store< ::dsn::tools::tool_app>::create(spec.tool.c_str(), ::dsn::PROVIDER_TYPE_MAIN, spec.tool.c_str()); dsn_all.tool->install(spec); // init app specs if (!spec.init_app_specs()) { printf("error in config file %s, exit ...\n", config_file); return false; } // init tool memory dsn_all.memory = ::dsn::utils::factory_store< ::dsn::memory_provider>::create( spec.tools_memory_factory_name.c_str(), ::dsn::PROVIDER_TYPE_MAIN); // prepare minimum necessary ::dsn::service_engine::fast_instance().init_before_toollets(spec); // init logging dsn_log_init(); // init toollets for (auto it = spec.toollets.begin(); it != spec.toollets.end(); ++it) { auto tlet = dsn::tools::internal_use_only::get_toollet(it->c_str(), ::dsn::PROVIDER_TYPE_MAIN); dassert(tlet, "toolet not found"); tlet->install(spec); } // init provider specific system inits dsn::tools::sys_init_before_app_created.execute(::dsn::service_engine::fast_instance().spec().config); // TODO: register sys_exit execution // init runtime ::dsn::service_engine::fast_instance().init_after_toollets(); dsn_all.engine_ready = true; // split app_name and app_index std::list<std::string> applistkvs; ::dsn::utils::split_args(app_list.c_str(), applistkvs, ';'); // init apps for (auto& sp : spec.app_specs) { if (!sp.run) continue; bool create_it = false; if (app_list == "") // create all apps { create_it = true; } else { for (auto &kv : applistkvs) { std::list<std::string> argskvs; ::dsn::utils::split_args(kv.c_str(), argskvs, '@'); if (std::string("apps.") + argskvs.front() == sp.config_section) { if (argskvs.size() < 2) create_it = true; else create_it = (std::stoi(argskvs.back()) == sp.index); break; } } } if (create_it) { ::dsn::service_engine::fast_instance().start_node(sp); } } if (::dsn::service_engine::fast_instance().get_all_nodes().size() == 0) { printf("no app are created, usually because \n" "app_name is not specified correctly, should be 'xxx' in [apps.xxx]\n" "or app_index (1-based) is greater than specified count in config file\n" ); exit(1); } // start cli if necessary if (dsn_all.config->get_value<bool>("core", "cli_local", true, "whether to enable local command line interface (cli)")) { ::dsn::command_manager::instance().start_local_cli(); } if (dsn_all.config->get_value<bool>("core", "cli_remote", true, "whether to enable remote command line interface (using dsn.cli)")) { ::dsn::command_manager::instance().start_remote_cli(); } // register local cli commands ::dsn::register_command("config-dump", "config-dump - dump configuration", "config-dump [to-this-config-file]", [](const std::vector<std::string>& args) { std::ostringstream oss; std::ofstream off; std::ostream* os = &oss; if (args.size() > 0) { off.open(args[0]); os = &off; oss << "config dump to file " << args[0] << std::endl; } dsn_all.config->dump(*os); return oss.str(); }); // invoke customized init after apps are created dsn::tools::sys_init_after_app_created.execute(::dsn::service_engine::fast_instance().spec().config); // start the tool dsn_all.tool->run(); // if (sleep_after_init) { while (true) { std::this_thread::sleep_for(std::chrono::hours(1)); } } // add this to allow mimic app call from this thread. memset((void*)&dsn::tls_dsn, 0, sizeof(dsn::tls_dsn)); return true; }
int run(const arguments_t& args) { // Load the deps resolver deps_resolver_t resolver(args); if (!resolver.valid()) { trace::error(_X("Invalid .deps file")); return StatusCode::ResolverInitFailure; } // Add packages directory pal::string_t packages_dir = args.nuget_packages; if (!pal::directory_exists(packages_dir)) { (void)pal::get_default_packages_directory(&packages_dir); } trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str()); pal::string_t clr_path = resolver.resolve_coreclr_dir(args.app_dir, packages_dir, args.dotnet_packages_cache); if (clr_path.empty() || !pal::realpath(&clr_path)) { trace::error(_X("Could not resolve coreclr path")); return StatusCode::CoreClrResolveFailure; } else { trace::info(_X("CoreCLR directory: %s"), clr_path.c_str()); } probe_paths_t probe_paths; if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths)) { return StatusCode::ResolverResolveFailure; } // Build CoreCLR properties const char* property_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "PLATFORM_RESOURCE_ROOTS", "AppDomainCompatSwitch", // TODO: pipe this from corehost.json "SERVER_GC", // Workaround: mscorlib does not resolve symlinks for AppContext.BaseDirectory dotnet/coreclr/issues/2128 "APP_CONTEXT_BASE_DIRECTORY", }; auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa); auto app_base_cstr = pal::to_stdstring(args.app_dir); auto native_dirs_cstr = pal::to_stdstring(probe_paths.native); auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture); // Workaround for dotnet/cli Issue #488 and #652 pal::string_t server_gc; std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : "0"; const char* property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpa_paths_cstr.c_str(), // APP_PATHS app_base_cstr.c_str(), // APP_NI_PATHS app_base_cstr.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES native_dirs_cstr.c_str(), // PLATFORM_RESOURCE_ROOTS culture_dirs_cstr.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified", // SERVER_GC server_gc_cstr.c_str(), // APP_CONTEXT_BASE_DIRECTORY app_base_cstr.c_str() }; size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]); // Bind CoreCLR if (!coreclr::bind(clr_path)) { trace::error(_X("Failed to bind to coreclr")); return StatusCode::CoreClrBindFailure; } // Verbose logging if (trace::is_enabled()) { for (size_t i = 0; i < property_size; ++i) { pal::string_t key, val; pal::to_palstring(property_keys[i], &key); pal::to_palstring(property_values[i], &val); trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str()); } } std::string own_path; pal::to_stdstring(args.own_path.c_str(), &own_path); // Initialize CoreCLR coreclr::host_handle_t host_handle; coreclr::domain_id_t domain_id; auto hr = coreclr::initialize( own_path.c_str(), "clrhost", property_keys, property_values, property_size, &host_handle, &domain_id); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr); return StatusCode::CoreClrInitFailure; } if (trace::is_enabled()) { pal::string_t arg_str; for (int i = 0; i < args.app_argc; i++) { arg_str.append(args.app_argv[i]); arg_str.append(_X(",")); } trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(), args.managed_application.c_str(), args.app_argc, arg_str.c_str()); } // Initialize with empty strings std::vector<std::string> argv_strs(args.app_argc); std::vector<const char*> argv(args.app_argc); for (int i = 0; i < args.app_argc; i++) { pal::to_stdstring(args.app_argv[i], &argv_strs[i]); argv[i] = argv_strs[i].c_str(); } std::string managed_app = pal::to_stdstring(args.managed_application); // Execute the application unsigned int exit_code = 1; hr = coreclr::execute_assembly( host_handle, domain_id, argv.size(), argv.data(), managed_app.c_str(), &exit_code); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr); return StatusCode::CoreClrExeFailure; } // Shut down the CoreCLR hr = coreclr::shutdown(host_handle, domain_id); if (!SUCCEEDED(hr)) { trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr); } coreclr::unload(); return exit_code; }
void BucketManagerImpl::forgetUnreferencedBuckets() { std::lock_guard<std::recursive_mutex> lock(mBucketMutex); std::set<Hash> referenced; for (uint32_t i = 0; i < BucketList::kNumLevels; ++i) { auto const& level = mBucketList.getLevel(i); referenced.insert(level.getCurr()->getHash()); referenced.insert(level.getSnap()->getHash()); for (auto const& h : level.getNext().getHashes()) { referenced.insert(hexToBin256(h)); } } // Implicitly retain any buckets that are referenced by a state in // the publish queue. auto pub = mApp.getHistoryManager().getBucketsReferencedByPublishQueue(); { for (auto const& h : pub) { CLOG(DEBUG, "Bucket") << "BucketManager::forgetUnreferencedBuckets: " << h << " referenced by publish queue"; referenced.insert(hexToBin256(h)); } } for (auto i = mSharedBuckets.begin(); i != mSharedBuckets.end();) { // Standard says map iterators other than the one you're erasing remain // valid. auto j = i; ++i; // Only drop buckets if the bucketlist has forgotten them _and_ // no other in-progress structures (worker threads, shadow lists) // have references to them, just us. It's ok to retain a few too // many buckets, a little longer than necessary. // // This conservatism is important because we want to enforce that only // one bucket ever exists in memory with a given filename, and that // we're the first and last to know about it. Otherwise buckets might // race on deleting the underlying file from one another. if (referenced.find(j->first) == referenced.end() && j->second.use_count() == 1) { auto filename = j->second->getFilename(); CLOG(TRACE, "Bucket") << "BucketManager::forgetUnreferencedBuckets dropping " << filename; if (!filename.empty()) { CLOG(TRACE, "Bucket") << "removing bucket file: " << filename; std::remove(filename.c_str()); } mSharedBuckets.erase(j); } } mSharedBucketsSize.set_count(mSharedBuckets.size()); }
//------------------------------------------------------------------------------------- void ScriptDefModule::onLoaded(void) { if(EntityDef::entitydefAliasID()) { int aliasID = ENTITY_BASE_PROPERTY_ALIASID_MAX; PROPERTYDESCRIPTION_MAP::iterator iter1 = cellPropertyDescr_.begin(); for(; iter1 != cellPropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { propertyDescr_aliasmap_[aliasID] = iter1->second; iter1->second->aliasID(aliasID++); } } iter1 = basePropertyDescr_.begin(); for(; iter1 != basePropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { propertyDescr_aliasmap_[aliasID] = iter1->second; iter1->second->aliasID(aliasID++); } } iter1 = clientPropertyDescr_.begin(); for(; iter1 != clientPropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { propertyDescr_aliasmap_[aliasID] = iter1->second; iter1->second->aliasID(aliasID++); } } if(aliasID > 255) { iter1 = cellPropertyDescr_.begin(); for(; iter1 != cellPropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { iter1->second->aliasID(-1); } } iter1 = basePropertyDescr_.begin(); for(; iter1 != basePropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { iter1->second->aliasID(-1); } } iter1 = clientPropertyDescr_.begin(); for(; iter1 != clientPropertyDescr_.end(); iter1++) { if(iter1->second->hasClient()) { iter1->second->aliasID(-1); } } propertyDescr_aliasmap_.clear(); } else { usePropertyDescrAlias_ = true; } aliasID = 0; METHODDESCRIPTION_MAP::iterator iter2 = methodClientDescr_.begin(); for(; iter2 != methodClientDescr_.end(); iter2++) { methodDescr_aliasmap_[aliasID] = iter2->second; iter2->second->aliasID(aliasID++); } if(aliasID > 255) { METHODDESCRIPTION_MAP::iterator iter2 = methodClientDescr_.begin(); for(; iter2 != methodClientDescr_.end(); iter2++) { iter2->second->aliasID(-1); methodDescr_aliasmap_.clear(); } } else { useMethodDescrAlias_ = true; } } if(g_debugEntity) { c_str(); } }
jstring Java_opencl_executor_Executor_getDeviceType(JNIEnv * env, jclass) { auto type = getDeviceType(); return env->NewStringUTF(type.c_str()); }
jstring Java_opencl_executor_Executor_getDeviceName(JNIEnv * env, jclass) { auto name = getDeviceName(); return env->NewStringUTF(name.c_str()); }
advance(); range fileName; MEOW_EMPTY_OR_NOT(store<many<not_<char_<')'>>>>(fileName), "expected file name") MEOW_EMPTY("expected right parenthesis to end include-file"); advance(); parser_context backupContext(*this); // TODO: overload + to return a chain, and create std::string // operator for the chain file_path_ = chilon::string_range(file_path_.begin(), meta_file_path_end_); file_path_.append(fileName); MEOW_NOT(load(file_path_.c_str()), "could not load file") if (! parse()) return false; advance(); // skip final ) *this = std::move(backupContext); continue; } else { MEOW_FAIL("expected ! or include-file") } } } }
void* HttpRequest::RequestParse(void*arg) { int n; int again_flag = true; //again flag decide to close the fd or try again while(true) { errno = 0; //this is important memset(usr_buf,0,RIO_BUFSIZE); //reset the buf n = rio_readn(fd,(void*)usr_buf,RIO_BUFSIZE-1); if(n==-1) { debug("error."); again_flag = false; break; } else if(n==0) { if(errno==EAGAIN) { //debug("again read"); again_flag = true; } else //EOF { //debug("EOF read close fd"); again_flag = false; } //debug("there is not any more data,errno is: %d",errno); break; } read_data = usr_buf; /* cout<<"read data:--------------------------------------------"<<endl; cout<<read_data<<endl; cout<<"-------------------------------------------------------"<<endl; */ //debug_cpp(read_data.size()); CommandParse(); //requese line parse HeaderParse(); //head parse //int data_n = read_data.size(); if(read_data.size()!=0) { BodyParse(); //body parse } /*parse complete,do method,url ,version check*/ HttpError e; int check_res = e.RequireCheck(command,head,out,file_stat); if(check_res!=D_OK) { //debug("require error: %d",check_res); //then send the wrong information page command.uri = "/40x.html"; // reset the file_stat; string file_name = file_root+command.uri; stat(file_name.c_str(),&file_stat); out.SetStaticServer(true); } /**********check over,send the result to the client********/ if(out.GetStaticServer()) { //set the length out.SetFileSize(file_stat.st_size); auto out_line = out.SetOutLine_C(); out_line += out.SetOutHeaders_C(head); char* res_line_buf = const_cast<char*>(out_line.c_str()); n = rio_writen(fd,(void*)res_line_buf,strlen(res_line_buf)); //write command line //debug("send Response line and Out Header."); StaticServer(); //debug("----------static server over-----------"); } else //dynamic server { //debug("----------dynamic server on-------------"); DynamicServer(); //debug("----------dynamic server over-----------"); } //server -------**over**---------- if(head.head.find("Connection")==head.head.end()) //keep alive { again_flag = false; //debug("-----------no keep alive,will break---------"); break; } else { again_flag = true; } } if(!again_flag) { //debug("close fd ,%d",fd); close(fd); //close fd ,there is no other request } else { head.head.clear(); //clear the request head read_data=""; again_flag = true; out.clear(); //clear the output data InitHttpRequest(ep,fd,epfd); //no need to initialize.because the ep,fd,and the epfd etc do not change ep->SetEpollEvent((void*)this,D_EPOLLIN|D_EPOLLET|D_EPOLLONESHOT); //set event ep->EpollCTL(D_EPOLL_CTL_MOD,fd); //add fd to the event module } return NULL; }
void test_any_point() { // This tests configures the parser so that Odometry messages are stored // into capnproto any types. std::cout << std::endl << std::endl << "test_any_point" << std::endl << std::endl; std::string container_name = "thisisatest"; geometry_msgs::Point point; double x = 1.0; double y = 2.0; double z = 3.0; //set the position point.x = x; point.y = y; point.z = z; // transform to shapeshifter object topic_tools::ShapeShifter shape_shifter; shape_shifter.morph( ros::message_traits::MD5Sum<geometry_msgs::Point>::value(), ros::message_traits::DataType<geometry_msgs::Point>::value(), ros::message_traits::Definition<geometry_msgs::Point>::value(), "" ); std::vector<uint8_t> buffer; serialize_message_to_array(point, buffer); ros::serialization::OStream stream( buffer.data(), buffer.size() ); shape_shifter.read( stream ); // The parser std::map<std::string, std::string> typemap; typemap["geometry_msgs/Point"] = "Point"; knowledge::KnowledgeBase knowledge; gams::utility::ros::RosParser parser (&knowledge, "", "", typemap, plugin_types); // register the type using the topic_name as identifier. This allows us to // use RosIntrospection const std::string topic_name = "point"; const std::string datatype = shape_shifter.getDataType(); const std::string definition = shape_shifter.getMessageDefinition(); parser.registerMessageDefinition (topic_name, RosIntrospection::ROSType (datatype), definition); // Load the schemas from disk auto point_schema_path = madara::utility::expand_envs( "$(GAMS_ROOT)/src/gams/types/Point.capnp.bin"); parser.load_capn_schema(point_schema_path); parser.print_schemas(); // parse to capnp format parser.parse_any(topic_name, shape_shifter, container_name); knowledge.print(); madara::knowledge::GenericCapnObject any = knowledge.get(container_name).to_any<madara::knowledge::GenericCapnObject>(); int fd = open(point_schema_path.c_str(), 0, O_RDONLY); capnp::StreamFdMessageReader schema_message_reader(fd); auto schema_reader = schema_message_reader.getRoot<capnp::schema::CodeGeneratorRequest>(); capnp::SchemaLoader loader; auto schema = loader.load(schema_reader.getNodes()[0]); auto capn_point = any.reader(schema.asStruct()); TEST(capn_point.get("x").as<float>(), x); TEST(capn_point.get("y").as<float>(), y); TEST(capn_point.get("z").as<float>(), z); auto capn_point2 = any.reader<gams::types::Point>(); TEST(capn_point2.getX(), x); TEST(capn_point2.getY(), y); TEST(capn_point2.getZ(), z); }
/*static*/ void framework_info::get_all_framework_infos( const pal::string_t& own_dir, const pal::string_t& fx_name, std::vector<framework_info>* framework_infos) { std::vector<pal::string_t> global_dirs; bool multilevel_lookup = multilevel_lookup_enabled(); // own_dir contains DIR_SEPARATOR appended that we need to remove. pal::string_t own_dir_temp = own_dir; remove_trailing_dir_seperator(&own_dir_temp); std::vector<pal::string_t> hive_dir; hive_dir.push_back(own_dir_temp); if (multilevel_lookup && pal::get_global_dotnet_dirs(&global_dirs)) { for (pal::string_t dir : global_dirs) { if (!pal::are_paths_equal_with_normalized_casing(dir, own_dir_temp)) { hive_dir.push_back(dir); } } } for (pal::string_t dir : hive_dir) { auto fx_shared_dir = dir; append_path(&fx_shared_dir, _X("shared")); if (pal::directory_exists(fx_shared_dir)) { std::vector<pal::string_t> fx_names; if (fx_name.length()) { // Use the provided framework name fx_names.push_back(fx_name); } else { // Read all frameworks, including "Microsoft.NETCore.App" pal::readdir_onlydirectories(fx_shared_dir, &fx_names); } for (pal::string_t fx_name : fx_names) { auto fx_dir = fx_shared_dir; append_path(&fx_dir, fx_name.c_str()); if (pal::directory_exists(fx_dir)) { trace::verbose(_X("Gathering FX locations in [%s]"), fx_dir.c_str()); std::vector<pal::string_t> versions; pal::readdir_onlydirectories(fx_dir, &versions); for (const auto& ver : versions) { // Make sure we filter out any non-version folders. fx_ver_t parsed; if (fx_ver_t::parse(ver, &parsed, false)) { trace::verbose(_X("Found FX version [%s]"), ver.c_str()); framework_info info(fx_name, fx_dir, parsed); framework_infos->push_back(info); } } } } } } std::sort(framework_infos->begin(), framework_infos->end(), compare_by_name_and_version); }
void test_any_bool() { // This tests configures the parser so that Odometry messages are stored // into capnproto any types. std::cout << std::endl << std::endl << "test_any_bool" << std::endl << std::endl; std::string container_name = "thisisatest"; sensor_msgs::RegionOfInterest roi; //set the position roi.x_offset = 10; roi.y_offset = 11; roi.height = 12; roi.width = 13; roi.do_rectify = true; // transform to shapeshifter object topic_tools::ShapeShifter shape_shifter; shape_shifter.morph( ros::message_traits::MD5Sum<sensor_msgs::RegionOfInterest>::value(), ros::message_traits::DataType<sensor_msgs::RegionOfInterest>::value(), ros::message_traits::Definition<sensor_msgs::RegionOfInterest>::value(), "" ); std::vector<uint8_t> buffer; serialize_message_to_array(roi, buffer); ros::serialization::OStream stream( buffer.data(), buffer.size() ); shape_shifter.read( stream ); // The parser std::map<std::string, std::string> typemap; typemap["sensor_msgs/RegionOfInterest"] = "RegionOfInterest"; knowledge::KnowledgeBase knowledge; gams::utility::ros::RosParser parser (&knowledge, "", "", typemap, plugin_types); // register the type using the topic_name as identifier. This allows us to // use RosIntrospection const std::string topic_name = "roi"; const std::string datatype = shape_shifter.getDataType(); const std::string definition = shape_shifter.getMessageDefinition(); parser.registerMessageDefinition (topic_name, RosIntrospection::ROSType (datatype), definition); // Load the schemas from disk auto point_schema_path = madara::utility::expand_envs( "$(GAMS_ROOT)/src/gams/types/RegionOfInterest.capnp.bin"); parser.load_capn_schema(point_schema_path); parser.print_schemas(); // parse to capnp format parser.parse_any(topic_name, shape_shifter, container_name); knowledge.print(); madara::knowledge::GenericCapnObject any = knowledge.get(container_name).to_any<madara::knowledge::GenericCapnObject>(); int fd = open(point_schema_path.c_str(), 0, O_RDONLY); capnp::StreamFdMessageReader schema_message_reader(fd); auto schema_reader = schema_message_reader.getRoot<capnp::schema::CodeGeneratorRequest>(); capnp::SchemaLoader loader; std::map<std::string, capnp::Schema> schemas; for (auto schema : schema_reader.getNodes()) { schemas[gams::utility::ros::cleanCapnpSchemaName(schema.getDisplayName())] = loader.load(schema); } auto capn_roi = any.reader(schemas[typemap["sensor_msgs/RegionOfInterest"]].asStruct()); TEST(capn_roi.get("doRectify").as<bool>(), true); auto capn_roi2 = any.reader<gams::types::RegionOfInterest>(); TEST(capn_roi2.getDoRectify(), true); }
void Viewer::mainloop() { Timer timer; Timer total; if (m_print_perf) fmt::print("Rendering frame {}\n", m_frame); m_scene_changed = false; m_frame++; int current_time = SDL_GetTicks(); double dt = (current_time - m_last_frame_time) / 1000.0; m_last_frame_time = current_time; auto fps = 1. / dt; // Input SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { shutdown(); } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) { shutdown(); } if (e.key.keysym.sym == SDLK_b) { m_debug = !m_debug; } if (e.key.keysym.sym == SDLK_n) { m_print_perf = !m_print_perf; } if (e.key.keysym.sym == SDLK_1) { m_stride_x = 1; m_stride_y = 1; m_scene_changed = true; } if (e.key.keysym.sym == SDLK_2) { m_stride_x = 2; m_stride_y = 2; m_scene_changed = true; } if (e.key.keysym.sym == SDLK_3) { m_stride_x = 4; m_stride_y = 4; m_scene_changed = true; } } if (e.type == SDL_MOUSEBUTTONDOWN) { if (e.button.button == SDL_BUTTON_RIGHT) { if (m_look_mode) { m_look_mode = false; SDL_SetRelativeMouseMode(SDL_FALSE); } else if (!m_look_mode) { m_look_mode = true; SDL_SetRelativeMouseMode(SDL_TRUE); } } } } float cam_speed = .8f * dt; // Left/right const uint8_t *keystates = SDL_GetKeyboardState(0); if (keystates[SDL_SCANCODE_A]) { m_scene_changed = true; Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::right(m_camera) * cam_speed); } else if (keystates[SDL_SCANCODE_D]) { Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::right(m_camera) * cam_speed); m_scene_changed = true; } // Up/down if (keystates[SDL_SCANCODE_SPACE]) { m_scene_changed = true; Camera::set_pos(m_camera, Camera::pos(m_camera) + glm::vec3{0, 1, 0} * cam_speed); } else if (keystates[SDL_SCANCODE_LCTRL]) { m_scene_changed = true; Camera::set_pos(m_camera, Camera::pos(m_camera) - glm::vec3{0, 1, 0} * cam_speed); } // Roll if (keystates[SDL_SCANCODE_Q]) { m_scene_changed = true; Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), 0.1f)); } else if (keystates[SDL_SCANCODE_E]) { m_scene_changed = true; Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), -0.1f)); } // Front/back if (keystates[SDL_SCANCODE_W]) { m_scene_changed = true; Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::dir(m_camera) * cam_speed); } else if (keystates[SDL_SCANCODE_S]) { m_scene_changed = true; Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::dir(m_camera) * cam_speed); } // Rendering here int width; int height; SDL_GetWindowSize(m_window, &width, &height); glm::ivec2 mouse_pos; if (m_look_mode) { // Yaw SDL_GetRelativeMouseState(&(mouse_pos.x), &(mouse_pos.y)); if (mouse_pos.x != 0) { m_scene_changed = true; Camera::set_dir(m_camera, glm::rotateY(Camera::dir(m_camera), mouse_pos.x * 0.001f)); } // Pitch if (mouse_pos.y != 0) { m_scene_changed = true; Camera::set_dir(m_camera, glm::rotate(Camera::dir(m_camera), mouse_pos.y * 0.001f, glm::cross(Camera::up(m_camera), Camera::dir(m_camera)))); } } else if (!m_look_mode) { SDL_GetMouseState(&(mouse_pos.x), &(mouse_pos.y)); } if (m_scene_changed) { m_samples_accumulated = 0; } if (m_print_perf) fmt::print(" {:<15} {:>10.3f} ms\n", "Input handling", timer.elapsed()); Scene::rebuild(m_scene); if (m_print_perf) fmt::print(" {:<15} {:=10.3f} ms\n", "Scene rebuild", timer.elapsed()); const auto luminance = m_renderer->render(m_scene_changed, m_stride_x, m_stride_y); if (m_print_perf) { m_renderer->print_last_frame_timings(); } m_samples_accumulated += 1; timer.reset(); // This striding is just for speeding up // We're basically drawing really big pixels here #pragma omp parallel for collapse(2) schedule(dynamic, 1024) for (auto x = 0; x < width; x += m_stride_x) { for (auto y = 0; y < height; y += m_stride_y) { glm::vec4 color = luminance[y * width + x] / static_cast<float>(m_samples_accumulated); for (auto u = 0; u < m_stride_x; u++) { for (auto v = 0; v < m_stride_y; v++) { m_pixels[(y + v) * width + (x + u)] = trac0r::pack_color_argb(color); } } } } if (m_print_perf) fmt::print(" {:<15} {:>10.3f} ms\n", "Pixel transfer", timer.elapsed()); // std::vector<uint32_t> m_pixels_filtered; // m_pixels_filtered.resize(m_screen_width * m_screen_height, 0); // trac0r::box_filter(m_pixels, width, height, m_pixels_filtered); // m_pixels = m_pixels_filtered; // // if (m_print_perf) // fmt::print(" {:<15} {:>10.3f} ms\n", "Image filtering", timer.elapsed()); SDL_RenderClear(m_render); SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t)); SDL_RenderCopy(m_render, m_render_tex, 0, 0); if (m_debug) { // Lots of debug info glm::vec2 mouse_rel_pos = Camera::screenspace_to_camspace(m_camera, mouse_pos.x, mouse_pos.y); glm::vec3 mouse_canvas_pos = Camera::camspace_to_worldspace(m_camera, mouse_rel_pos); auto fps_debug_info = "FPS: " + std::to_string(int(fps)); auto scene_changing_info = "Samples : " + std::to_string(m_samples_accumulated); scene_changing_info += " Scene Changing: " + std::to_string(m_scene_changed); auto cam_look_debug_info = "Cam Look Mode: " + std::to_string(m_look_mode); auto cam_pos_debug_info = "Cam Pos: " + glm::to_string(Camera::pos(m_camera)); auto cam_dir_debug_info = "Cam Dir: " + glm::to_string(Camera::dir(m_camera)); auto cam_up_debug_info = "Cam Up: " + glm::to_string(Camera::up(m_camera)); auto cam_fov_debug_info = "Cam FOV (H/V): " + std::to_string(int(glm::degrees(Camera::horizontal_fov(m_camera)))) + "/"; cam_fov_debug_info += std::to_string(int(glm::degrees(Camera::vertical_fov(m_camera)))); auto cam_canvas_center_pos_info = "Cam Canvas Center: " + glm::to_string(Camera::canvas_center_pos(m_camera)); auto mouse_pos_screen_info = "Mouse Pos Screen Space: " + glm::to_string(mouse_pos); auto mouse_pos_relative_info = "Mouse Pos Cam Space: " + glm::to_string(mouse_rel_pos); auto mouse_pos_canvas_info = "Mouse Pos Canvas World Space: " + glm::to_string(mouse_canvas_pos); auto fps_debug_tex = trac0r::make_text(m_render, m_font, fps_debug_info, {200, 100, 100, 200}); auto scene_changing_tex = trac0r::make_text(m_render, m_font, scene_changing_info, {200, 100, 100, 200}); auto cam_look_debug_tex = trac0r::make_text(m_render, m_font, cam_look_debug_info, {200, 100, 100, 200}); auto cam_pos_debug_tex = trac0r::make_text(m_render, m_font, cam_pos_debug_info, {200, 100, 100, 200}); auto cam_dir_debug_tex = trac0r::make_text(m_render, m_font, cam_dir_debug_info, {200, 100, 100, 200}); auto cam_up_debug_tex = trac0r::make_text(m_render, m_font, cam_up_debug_info, {200, 100, 100, 200}); auto cam_fov_debug_tex = trac0r::make_text(m_render, m_font, cam_fov_debug_info, {200, 100, 100, 200}); auto cam_canvas_center_pos_tex = trac0r::make_text(m_render, m_font, cam_canvas_center_pos_info, {200, 100, 100, 200}); auto mouse_pos_screen_tex = trac0r::make_text(m_render, m_font, mouse_pos_screen_info, {200, 100, 100, 200}); auto mouse_pos_relative_tex = trac0r::make_text(m_render, m_font, mouse_pos_relative_info, {200, 100, 100, 200}); auto mouse_pos_canvas_tex = trac0r::make_text(m_render, m_font, mouse_pos_canvas_info, {200, 100, 100, 200}); trac0r::render_text(m_render, fps_debug_tex, 10, 10); trac0r::render_text(m_render, scene_changing_tex, 10, 25); trac0r::render_text(m_render, cam_look_debug_tex, 10, 40); trac0r::render_text(m_render, cam_pos_debug_tex, 10, 55); trac0r::render_text(m_render, cam_dir_debug_tex, 10, 70); trac0r::render_text(m_render, cam_up_debug_tex, 10, 85); trac0r::render_text(m_render, cam_fov_debug_tex, 10, 100); trac0r::render_text(m_render, cam_canvas_center_pos_tex, 10, 115); trac0r::render_text(m_render, mouse_pos_screen_tex, 10, 130); trac0r::render_text(m_render, mouse_pos_relative_tex, 10, 145); trac0r::render_text(m_render, mouse_pos_canvas_tex, 10, 160); // Let's draw some debug to the display (such as AABBs) if (m_debug) { auto &accel_struct = Scene::accel_struct(m_scene); for (auto &shape : FlatStructure::shapes(accel_struct)) { auto &aabb = Shape::aabb(shape); const auto &verts = AABB::vertices(aabb); std::array<glm::i8vec2, 12> pairs; pairs[0] = {0, 1}; pairs[1] = {1, 3}; pairs[2] = {2, 3}; pairs[3] = {0, 2}; pairs[4] = {4, 5}; pairs[5] = {5, 7}; pairs[6] = {6, 7}; pairs[7] = {4, 6}; pairs[8] = {0, 4}; pairs[9] = {1, 5}; pairs[10] = {2, 6}; pairs[11] = {3, 7}; for (auto pair : pairs) { auto ws1 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[0]]); auto ss1 = glm::i32vec2(0); if (ws1 != glm::vec3(0)) { auto cs1 = Camera::worldspace_to_camspace(m_camera, ws1); ss1 = Camera::camspace_to_screenspace(m_camera, cs1); } auto ws2 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[1]]); auto ss2 = glm::i32vec2(0); if (ws2 != glm::vec3(0)) { auto cs2 = Camera::worldspace_to_camspace(m_camera, ws2); ss2 = Camera::camspace_to_screenspace(m_camera, cs2); } if (ss1 != glm::i32vec2(0) && ss2 != glm::i32vec2(0)) { aalineRGBA(m_render, ss1.x, ss1.y, ss2.x, ss2.y, 255, 255, 0, 200); } } } } SDL_DestroyTexture(fps_debug_tex); SDL_DestroyTexture(scene_changing_tex); SDL_DestroyTexture(cam_look_debug_tex); SDL_DestroyTexture(cam_pos_debug_tex); SDL_DestroyTexture(cam_dir_debug_tex); SDL_DestroyTexture(cam_up_debug_tex); SDL_DestroyTexture(cam_fov_debug_tex); SDL_DestroyTexture(cam_canvas_center_pos_tex); SDL_DestroyTexture(mouse_pos_screen_tex); SDL_DestroyTexture(mouse_pos_relative_tex); SDL_DestroyTexture(mouse_pos_canvas_tex); } SDL_RenderPresent(m_render); if (m_print_perf) { fmt::print(" {:<15} {:>10.3f} ms\n", "Rendering", timer.elapsed()); fmt::print(" {:<15} {:>10.3f} ms\n", "=> Budget", 1000.f / 60.f - total.peek()); fmt::print(" {:<15} {:>10.3f} ms\n\n", "=> Total", total.peek()); } m_frame_total += total.elapsed(); if (m_benchmark_mode < 0 && m_max_frames != 0 && m_frame > m_max_frames) { auto filename = std::string("trac0r-") + std::to_string(m_max_frames) + std::string(".bmp"); SDL_Surface *sshot = SDL_CreateRGBSurface(0, m_screen_width, m_screen_height, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000); SDL_RenderReadPixels(m_render, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch); SDL_SaveBMP(sshot, filename.c_str()); SDL_FreeSurface(sshot); shutdown(); } else if (m_benchmark_mode > 0 && m_max_frames != 0 && m_frame > m_max_frames) { fmt::print("Benchmark results:\n"); fmt::print(" {:<15} {:>10}\n", "Frames rendered", m_max_frames); fmt::print(" {:<15} {:>10.3f} ms\n", "Total runtime", m_frame_total); fmt::print(" {:<15} {:>10.3f} ms\n", "Avg. frame", m_frame_total / m_max_frames); fmt::print(" {:<15} {:>10.3f} FPS\n", "Avg. FPS", 1.f / ((m_frame_total / 1000.f) / m_max_frames)); shutdown(); } }
void test_any_odom() { // This tests configures the parser so that Odometry messages are stored // into capnproto any types. std::cout << std::endl << std::endl << "test_any_odom" << std::endl << std::endl; std::string container_name = "thisisatest"; nav_msgs::Odometry odom; //odom.header.stamp = ros::Time::now(); odom.header.frame_id = "odom"; double x = 1.0; double y = 2.0; double z = 3.0; double vx = 0.1; double vy = 0.2; double vz = 0.3; double cov = 0.123; geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(10.0); //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = z; odom.pose.pose.orientation = odom_quat; odom.pose.covariance[17] = cov; //set the velocity odom.child_frame_id = "base_link"; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = vz; // transform to shapeshifter object topic_tools::ShapeShifter shape_shifter; shape_shifter.morph( ros::message_traits::MD5Sum<nav_msgs::Odometry>::value(), ros::message_traits::DataType<nav_msgs::Odometry>::value(), ros::message_traits::Definition<nav_msgs::Odometry>::value(), "" ); std::vector<uint8_t> buffer; serialize_message_to_array(odom, buffer); ros::serialization::OStream stream( buffer.data(), buffer.size() ); shape_shifter.read( stream ); // The parser std::map<std::string, std::string> typemap; typemap["nav_msgs/Odometry"] = "Odometry"; knowledge::KnowledgeBase knowledge; gams::utility::ros::RosParser parser (&knowledge, "", "", typemap, plugin_types); // register the type using the topic_name as identifier. This allows us to // use RosIntrospection const std::string topic_name = "odom"; const std::string datatype = shape_shifter.getDataType(); const std::string definition = shape_shifter.getMessageDefinition(); parser.registerMessageDefinition (topic_name, RosIntrospection::ROSType (datatype), definition); // Load the schemas from disk auto path = madara::utility::expand_envs( "$(GAMS_ROOT)/src/gams/types/Odometry.capnp.bin"); parser.load_capn_schema(path); parser.print_schemas(); // parse to capnp format parser.parse_any(topic_name, shape_shifter, container_name); knowledge.print(); madara::knowledge::GenericCapnObject any = knowledge.get(container_name).to_any<madara::knowledge::GenericCapnObject>(); int fd = open(path.c_str(), 0, O_RDONLY); capnp::StreamFdMessageReader schema_message_reader(fd); auto schema_reader = schema_message_reader.getRoot<capnp::schema::CodeGeneratorRequest>(); capnp::SchemaLoader loader; std::map<std::string, capnp::Schema> schemas; for (auto schema : schema_reader.getNodes()) { schemas[gams::utility::ros::cleanCapnpSchemaName(schema.getDisplayName())] = loader.load(schema); } auto capn_odom = any.reader(schemas[typemap["nav_msgs/Odometry"]].asStruct()); std::string cfd = capn_odom.get("childFrameId").as<capnp::Text>().cStr(); if (cfd != odom.child_frame_id) { std::cout << "childFrameId ?= " << odom.child_frame_id << " FAIL! got " << cfd << " instead" << std::endl; ++gams_fails; } auto pose_with_cov = capn_odom.get("pose").as<capnp::DynamicStruct>(); auto pose = pose_with_cov.get("pose").as<capnp::DynamicStruct>(); auto position = pose.get("position").as<capnp::DynamicStruct>(); auto orientation = pose.get("orientation").as<capnp::DynamicStruct>(); TEST(position.get("x").as<double>(), x); TEST(position.get("y").as<double>(), y); TEST(position.get("z").as<double>(), z); TEST(orientation.get("x").as<double>(), odom_quat.x); TEST(orientation.get("y").as<double>(), odom_quat.y); TEST(orientation.get("z").as<double>(), odom_quat.z); TEST(orientation.get("w").as<double>(), odom_quat.w); auto pose_covariance = pose_with_cov.get("covariance").as<capnp::DynamicList>(); TEST(pose_covariance[0].as<double>(), 0); TEST(pose_covariance[17].as<double>(), cov); }
// Implement refresh(F5 click, etc) based on // http://www.codeproject.com/Articles/3632/Detecting-the-IE-Refresh-button-using-IWebBrowser2 void CBrowserHelperObject::OnRefresh() { auto manifest = _AtlModule.moduleManifest; wstring location; wstringset dupes; CComBSTR bstr = nullptr; CComPtr<IDispatch> disp = nullptr; CComQIPtr<IHTMLWindow2, &IID_IHTMLWindow2> htmlWindow2 = nullptr; HRESULT hr = S_OK; for (;;) { // VARIANT *url chops off file:\\\ for local filesystem CComQIPtr<IWebBrowser2, &IID_IWebBrowser2> webBrowser2(m_webBrowser2); BreakOnNull(webBrowser2, hr); hr = webBrowser2->get_LocationURL(&bstr); BreakOnFailed(hr); location = wstring(bstr); // was m_strUrl if (location.empty()) { logger->debug(L"BrowserHelperObject::OnRefresh blank location, not interested -> " + manifest->uuid + L" -> " + location); break; } // match location against manifest auto& match = MatchManifest(webBrowser2, manifest, location); if (match.first.empty() && match.second.empty()) { logger->debug(L"BrowserHelperObject::OnRefresh not interested -> " + manifest->uuid + L" -> " + location); break; } logger->debug(L"BrowserHelperObject::OnRefresh -> " + manifest->uuid + L" -> " + location); // get IHTMLWindow2 hr = webBrowser2->get_Document(&disp); BreakOnNullWithErrorLog(disp, L"BrowserHelperObject::OnRefresh get_Document failed"); BreakOnFailed(hr); CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> htmlDocument2(disp); BreakOnNullWithErrorLog(htmlDocument2, L"BrowserHelperObject::OnRefresh IHTMLDocument2 failed"); hr = htmlDocument2->get_parentWindow(&htmlWindow2); BreakOnNullWithErrorLog(htmlWindow2, L"BrowserHelperObject::OnRefresh IHTMLWindow2 failed"); BreakOnFailed(hr); // attach forge extensions when pages like target=_blank didn't trigger navComplete event if (!m_isAttached) OnAttachForgeExtensions(m_webBrowser2, location, L"OnRefresh"); // was L"OnDocumentComplete" // Inject styles HTMLDocument document(webBrowser2); auto& matches = m_scriptExtensions->read_styles(match.first); for (auto& i : matches) { if (dupes.find(i.first) != dupes.end()) { logger->debug(L"BrowserHelperObject::OnRefresh already injected -> " + i.first); continue; } auto style = i.second; if (!style) { logger->debug(L"BrowserHelperObject::OnRefresh invalid stylesheet -> " + i.first); continue; } hr = document.InjectStyle(style); if (FAILED(hr)) { logger->error(L"BrowserHelperObject::OnRefresh failed to inject style -> " + i.first + L" -> " + logger->parse(hr)); continue; } dupes.insert(i.first); logger->debug(L"BrowserHelperObject::OnRefresh injected: " + i.first); } // Inject scripts dupes.clear(); matches = m_scriptExtensions->read_scripts(match.second); for (auto& i : matches) { if (dupes.find(i.first) != dupes.end()) { logger->debug(L"BrowserHelperObject::OnRefresh already injected -> " + i.first); continue; } auto script = i.second; if (!script) { logger->debug(L"BrowserHelperObject::OnRefresh invalid script -> " + i.first); continue; } CComVariant ret; hr = htmlWindow2->execScript(CComBSTR(script->c_str()), L"javascript", &ret); if (FAILED(hr)) { logger->error(L"BrowserHelperObject::OnRefresh failed to inject script -> " + i.first + L" -> " + logger->parse(hr)); continue; } dupes.insert(i.first); logger->debug(L"BrowserHelperObject::OnRefresh injected -> " + location + L" -> " + i.first); } break; } }
void test_any_compressed_image() { // This tests configures the parser so that Odometry messages are stored // into capnproto any types. std::cout << std::endl << std::endl << "test_any_compressed_image" << std::endl << std::endl; std::string container_name = "thisisatest"; sensor_msgs::CompressedImage image; image.header.frame_id = "img"; image.format = "jpeg"; int size = 100; std::vector<uint8_t> data_reference; for ( int i = 0; i < size; ++i) { uint8_t r = rand() % 255; image.data.push_back(r); data_reference.push_back(r); } // transform to shapeshifter object topic_tools::ShapeShifter shape_shifter; shape_shifter.morph( ros::message_traits::MD5Sum<sensor_msgs::CompressedImage>::value(), ros::message_traits::DataType<sensor_msgs::CompressedImage>::value(), ros::message_traits::Definition<sensor_msgs::CompressedImage>::value(), "" ); std::vector<uint8_t> buffer; serialize_message_to_array(image, buffer); ros::serialization::OStream stream( buffer.data(), buffer.size() ); shape_shifter.read( stream ); // The parser std::map<std::string, std::string> typemap; typemap["sensor_msgs/CompressedImage"] = "CompressedImage"; knowledge::KnowledgeBase knowledge; gams::utility::ros::RosParser parser (&knowledge, "", "", typemap, plugin_types); // register the type using the topic_name as identifier. This allows us to // use RosIntrospection const std::string topic_name = "img"; const std::string datatype = shape_shifter.getDataType(); const std::string definition = shape_shifter.getMessageDefinition(); parser.registerMessageDefinition (topic_name, RosIntrospection::ROSType (datatype), definition); // Load the schemas from disk auto path = madara::utility::expand_envs( "$(GAMS_ROOT)/src/gams/types/CompressedImage.capnp.bin"); parser.load_capn_schema(path); parser.print_schemas(); // parse to capnp format parser.parse_any(topic_name, shape_shifter, container_name); knowledge.print(); madara::knowledge::GenericCapnObject any = knowledge.get(container_name).to_any<madara::knowledge::GenericCapnObject>(); int fd = open(path.c_str(), 0, O_RDONLY); capnp::StreamFdMessageReader schema_message_reader(fd); auto schema_reader = schema_message_reader.getRoot<capnp::schema::CodeGeneratorRequest>(); capnp::SchemaLoader loader; std::map<std::string, capnp::Schema> schemas; for (auto schema : schema_reader.getNodes()) { schemas[gams::utility::ros::cleanCapnpSchemaName (schema.getDisplayName ())] = loader.load(schema); } auto capn_img = any.reader(schemas[typemap["sensor_msgs/CompressedImage"]].asStruct ()); auto data = capn_img.get ("data").as<capnp::DynamicList> (); TEST (data.size(), data_reference.size()); for ( int i = 0; i < size; ++i) { TEST(image.data[i], data_reference[i]); } auto format = capn_img.get("format").as<capnp::Text>().cStr(); std::cout << "Format: " << format << std::endl; }
const char* entity_header_get_allow(entity_header eh) { assert(eh != NULL); assert(entity_header_flag_is_set(eh, ENTITY_HEADER_ALLOW_SET)); return c_str(eh->allow); }
void HOSTFXR_UTILITY::GetHostFxrParameters( const fs::path &processPath, const fs::path &applicationPhysicalPath, const std::wstring &applicationArguments, fs::path &hostFxrDllPath, fs::path &dotnetExePath, std::vector<std::wstring> &arguments ) { LOG_INFOF(L"Resolving hostfxr parameters for application: '%ls' arguments: '%ls' path: '%ls'", processPath.c_str(), applicationArguments.c_str(), applicationPhysicalPath.c_str()); arguments = std::vector<std::wstring>(); fs::path expandedProcessPath = Environment::ExpandEnvironmentVariables(processPath); const auto expandedApplicationArguments = Environment::ExpandEnvironmentVariables(applicationArguments); LOG_INFOF(L"Known dotnet.exe location: '%ls'", dotnetExePath.c_str()); if (!expandedProcessPath.has_extension()) { // The only executable extension inprocess supports expandedProcessPath.replace_extension(".exe"); } else if (!ends_with(expandedProcessPath, L".exe", true)) { throw InvalidOperationException(format(L"Process path '%s' doesn't have '.exe' extension.", expandedProcessPath.c_str())); } // Check if the absolute path is to dotnet or not. if (IsDotnetExecutable(expandedProcessPath)) { LOG_INFOF(L"Process path '%ls' is dotnet, treating application as portable", expandedProcessPath.c_str()); if (applicationArguments.empty()) { throw InvalidOperationException(L"Application arguments are empty."); } if (dotnetExePath.empty()) { dotnetExePath = GetAbsolutePathToDotnet(applicationPhysicalPath, expandedProcessPath); } hostFxrDllPath = GetAbsolutePathToHostFxr(dotnetExePath); arguments.push_back(dotnetExePath); AppendArguments( expandedApplicationArguments, applicationPhysicalPath, arguments, true); } else { LOG_INFOF(L"Process path '%ls' is not dotnet, treating application as standalone or portable with bootstrapper", expandedProcessPath.c_str()); auto executablePath = expandedProcessPath; if (executablePath.is_relative()) { executablePath = applicationPhysicalPath / expandedProcessPath; } // // The processPath is a path to the application executable // like: C:\test\MyApp.Exe or MyApp.Exe // Check if the file exists, and if it does, get the parameters for a standalone application // if (is_regular_file(executablePath)) { auto applicationDllPath = executablePath; applicationDllPath.replace_extension(".dll"); LOG_INFOF(L"Checking application.dll at '%ls'", applicationDllPath.c_str()); if (!is_regular_file(applicationDllPath)) { throw InvalidOperationException(format(L"Application .dll was not found at %s", applicationDllPath.c_str())); } hostFxrDllPath = executablePath.parent_path() / "hostfxr.dll"; LOG_INFOF(L"Checking hostfxr.dll at '%ls'", hostFxrDllPath.c_str()); if (is_regular_file(hostFxrDllPath)) { LOG_INFOF(L"hostfxr.dll found app local at '%ls', treating application as standalone", hostFxrDllPath.c_str()); // For standalone apps we need .exe to be argv[0], dll would be discovered next to it arguments.push_back(executablePath); } else { LOG_INFOF(L"hostfxr.dll found app local at '%ls', treating application as portable with launcher", hostFxrDllPath.c_str()); // passing "dotnet" here because we don't know where dotnet.exe should come from // so trying all fallbacks is appropriate if (dotnetExePath.empty()) { dotnetExePath = GetAbsolutePathToDotnet(applicationPhysicalPath, L"dotnet"); } hostFxrDllPath = GetAbsolutePathToHostFxr(dotnetExePath); // For portable with launcher apps we need dotnet.exe to be argv[0] and .dll be argv[1] arguments.push_back(dotnetExePath); arguments.push_back(applicationDllPath); } AppendArguments( expandedApplicationArguments, applicationPhysicalPath, arguments); } else { // // If the processPath file does not exist and it doesn't include dotnet.exe or dotnet // then it is an invalid argument. // throw InvalidOperationException(format(L"Executable was not found at '%s'", executablePath.c_str())); } } }
const char* entity_header_get_content_language(entity_header eh) { assert(eh != NULL); assert(entity_header_flag_is_set(eh, ENTITY_HEADER_CONTENT_LANGUAGE_SET)); return c_str(eh->content_language); }
HostFileHandle::HostFileHandle(const std::string &path, File::OpenMode mode) : mMode(mode) { auto hostMode = translateMode(mode); mHandle = fopen(path.c_str(), hostMode.c_str()); }
const char* entity_header_get_content_md5(entity_header eh) { assert(eh != NULL); assert(entity_header_flag_is_set(eh, ENTITY_HEADER_CONTENT_MD5_SET)); return c_str(eh->content_md5); }
//呼びかけを設定します。 //設定したあと、 CommitRule() てしてね。 xreturn::r<bool> Recognition_SAPI::SetYobikake(const std::list<std::string> & yobikakeList) { _USE_WINDOWS_ENCODING; HRESULT hr; this->RuleGrammar->ClearRule(this->YobikakeRuleHandle); this->DictationGrammar->ClearRule(this->FilterRuleHandleHandle); // this->DictationGrammar->ClearRule(this->FilterRuleHandleHandle2); SPSTATEHANDLE appendState; //あとに続くを表現するためには、 新規にステートを作らないといけない。 hr = this->RuleGrammar->CreateNewState(this->YobikakeRuleHandle, &appendState); if(FAILED(hr)) return xreturn::windowsError(hr); hr = this->RuleGrammar->AddRuleTransition(appendState , NULL, this->CommandRuleHandle , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); this->YobikakeListArray = yobikakeList; for(auto it = this->YobikakeListArray.begin(); this->YobikakeListArray.end() != it ; ++it) { //ふつー使う呼びかけ hr = this->RuleGrammar->AddWordTransition(this->YobikakeRuleHandle , appendState , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); //ディクテーションフィルターの呼びかけ // hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); // hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle2 , NULL , _A2W( it->c_str() ) , L" " , SPWT_LEXICAL , 2.0f , NULL ); // if(FAILED(hr)) return xreturn::windowsError(hr); } //ディクテーションフィルター その1はディクテーションノードを加える // hr = this->DictationGrammar->AddRuleTransition(this->FilterRuleHandleHandle, NULL, SPRULETRANS_DICTATION, 1.0f, NULL); // if(FAILED(hr)) return xreturn::windowsError(hr); //ディクテーションフィルター その2はあ-んを加える. { wchar_t word[2]; word[0] = L'あ'; word[1] = 0; for(; word[0] < L'ん' ; word[0] ++ ) { hr = this->DictationGrammar->AddWordTransition(this->FilterRuleHandleHandle , NULL , word , L" " , SPWT_LEXICAL , 1.0f , NULL ); if(FAILED(hr)) return xreturn::windowsError(hr); } } //ルールに変更が加わったのでコミットしないといけません。 this->IsNeedUpdateRule = true; return true; }