void OBJWriter::write(const std::shared_ptr<gameplay::Model>& model, const std::string& baseName, const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap1, const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap2, const glm::vec3& ambientColor) const { Expects(model != nullptr); auto fullPath = m_basePath / baseName; Assimp::Exporter exporter; std::string formatIdentifier; for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i) { auto descr = exporter.GetExportFormatDescription(i); BOOST_ASSERT(descr != nullptr); std::string exporterExtension = std::string(".") + descr->fileExtension; if(exporterExtension == fullPath.extension().string()) { formatIdentifier = descr->id; break; } } if(formatIdentifier.empty()) { BOOST_LOG_TRIVIAL(error) << "Failed to find an exporter for the supplied file extension"; BOOST_LOG_TRIVIAL(info) << "Here's the list of registered exporters"; for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i) { auto descr = exporter.GetExportFormatDescription(i); BOOST_ASSERT(descr != nullptr); BOOST_LOG_TRIVIAL(info) << descr->description << ", extension `" << descr->fileExtension << "`, id `" << descr->id << "`"; } BOOST_THROW_EXCEPTION(std::runtime_error("Failed to find an exporter for the supplied file extension")); } std::unique_ptr<aiScene> scene = std::make_unique<aiScene>(); BOOST_ASSERT(scene->mRootNode == nullptr); scene->mRootNode = new aiNode(); { size_t totalPartCount = 0; for( const auto& mesh : model->getMeshes() ) { totalPartCount += mesh->getPartCount(); } scene->mNumMaterials = totalPartCount; scene->mMaterials = new aiMaterial*[totalPartCount]; std::fill_n(scene->mMaterials, totalPartCount, nullptr); scene->mNumMeshes = totalPartCount; scene->mMeshes = new aiMesh*[totalPartCount]; std::fill_n(scene->mMeshes, totalPartCount, nullptr); scene->mRootNode->mNumMeshes = totalPartCount; scene->mRootNode->mMeshes = new unsigned int[totalPartCount]; for( size_t i = 0; i < totalPartCount; ++i ) scene->mRootNode->mMeshes[i] = i; } for( size_t mi = 0, globalPartIndex = 0; mi < model->getMeshes().size(); ++mi ) { BOOST_ASSERT(mi < scene->mNumMeshes); const auto& mesh = model->getMeshes()[mi]; for( size_t pi = 0; pi < mesh->getPartCount(); ++pi , ++globalPartIndex ) { BOOST_ASSERT(globalPartIndex < scene->mNumMaterials); const std::shared_ptr<gameplay::MeshPart>& part = mesh->getPart(pi); scene->mMeshes[globalPartIndex] = new aiMesh(); aiMesh* outMesh = scene->mMeshes[globalPartIndex]; allocateElementMemory(mesh, outMesh); copyVertexData(mesh, outMesh); BOOST_ASSERT(part->getPrimitiveType() == gameplay::Mesh::PrimitiveType::TRIANGLES && part->getIndexCount() % 3 == 0); outMesh->mMaterialIndex = globalPartIndex; scene->mMaterials[globalPartIndex] = new aiMaterial(); scene->mMaterials[globalPartIndex]->AddProperty(new aiColor4D(ambientColor.r, ambientColor.g, ambientColor.b, 1), 1, AI_MATKEY_COLOR_AMBIENT); { // try to find the texture for our material using Entry = decltype(*mtlMap1.begin()); auto finder = [&part](const Entry& entry) { return entry.second == part->getMaterial(); }; auto texIt = std::find_if(mtlMap1.begin(), mtlMap1.end(), finder); bool found = false; if( texIt != mtlMap1.end() ) { scene->mMaterials[globalPartIndex]->AddProperty(new aiString(makeTextureName(texIt->first.tileAndFlag & TextureIndexMask) + ".png"), AI_MATKEY_TEXTURE_DIFFUSE(0)); found = true; } if( !found ) { texIt = std::find_if(mtlMap2.begin(), mtlMap2.end(), finder); if( texIt != mtlMap2.end() ) { scene->mMaterials[globalPartIndex]->AddProperty(new aiString(makeTextureName(texIt->first.tileAndFlag & TextureIndexMask) + ".png"), AI_MATKEY_TEXTURE_DIFFUSE(0)); } } } outMesh->mNumFaces = part->getIndexCount() / 3; outMesh->mFaces = new aiFace[outMesh->mNumFaces]; switch( part->getIndexFormat() ) { case gameplay::Mesh::INDEX8: copyIndices<uint8_t>(part, outMesh); break; case gameplay::Mesh::INDEX16: copyIndices<uint16_t>(part, outMesh); break; case gameplay::Mesh::INDEX32: copyIndices<uint32_t>(part, outMesh); break; default: break; } } } exporter.Export(scene.get(), formatIdentifier.c_str(), fullPath.string(), aiProcess_JoinIdenticalVertices | aiProcess_ValidateDataStructure | aiProcess_FlipUVs); }
void GameArbiter::process_command(Message *command) { switch (command->type) { case UnitMove: { auto cmd = dynamic_cast<UnitMoveMessage *>(command); int stack_id = cmd->data1; IntSet units = cmd->data2; Path& path = cmd->data3; int target_id = cmd->data4; UnitStack::pointer stack = game->stacks.get(stack_id); if (units.empty() || !stack->has_units(units) || path.empty()) { throw DataError() << "Invalid UnitMove message"; } /* Check that the move is allowed; shorten it if necessary */ Point end_pos = path.back(); UnitStack::pointer end_stack = game->level.tiles[end_pos].stack; int end_stack_id = end_stack ? end_stack->id : 0; if (end_stack_id != target_id) { path.pop_back(); target_id = 0; } MovementModel movement(game); UnitStack::pointer selected_stack = stack->copy_subset(units); unsigned int allowed_steps = movement.check_path(*selected_stack, path); bool truncated = allowed_steps < path.size(); int attack_target_id = target_id; if (truncated) target_id = 0; path.resize(allowed_steps); if (!path.empty()) { end_pos = path.back(); /* Generate updates. */ Faction::pointer faction = stack->owner; bool move = units.size() == stack->units.size() && target_id == 0; bool split = units.size() < stack->units.size() && target_id == 0; bool merge = units.size() == stack->units.size() && target_id != 0; UnitStack::pointer target = game->stacks.find(target_id); if (move) target_id = stack_id; if (split) target_id = game->get_free_stack_id(); // Send the moves for (auto iter = path.begin(); iter != path.end(); iter++) { emit(create_message(MoveUnits, stack_id, units, *iter)); } // If the stack is splitting to a new empty position, create a stack there if (split) { emit(create_message(CreateStack, target_id, end_pos, faction->id)); } emit(create_message(TransferUnits, stack_id, units, path, target_id)); // If the whole stack merged with an existing one, destroy it if (merge) { emit(create_message(DestroyStack, stack_id)); } } else { end_pos = stack->position; } UnitStack::pointer attack_target = game->stacks.find(attack_target_id); bool attack = attack_target && (attack_target->owner != stack->owner); if (attack) { BOOST_LOG_TRIVIAL(debug) << "Attack!"; Point target_point = attack_target->position; Point attacking_point = end_pos; Battle battle(game, target_point, attacking_point); battle.run(); emit(create_message(DoBattle, end_stack_id, target_point, battle.moves)); } } break; case FactionReady: { auto cmd = dynamic_cast<FactionReadyMessage *>(command); int faction_id = cmd->data1; bool ready = cmd->data2; if (game->mark_faction_ready(faction_id, ready)) { emit(create_message(FactionReady, faction_id, ready)); } if (game->all_factions_ready()) { emit(create_message(TurnEnd)); // process turn end spawn_units(); game->turn_number++; emit(create_message(TurnBegin, game->turn_number)); } } break; case Chat: { auto chat_msg = dynamic_cast<ChatMessage *>(command); emit(create_message(Chat, chat_msg->data)); } break; case SetLevelData: case CreateStructure: case DestroyStructure: { emit(command->shared_from_this()); } break; default: break; } }
/** BN vertex file: see SINGLE format. * BN distribution file: see above. */ void BayesGraphLoad::operator()( std::shared_ptr<Graph> graph, const std::string labPosFileName, const std::string vertexFileName, const std::string distributionFileName, const std::string cndDataFileName, const std::string dataFileName ) const { BOOST_LOG_TRIVIAL(trace) << "begin loading label..." << std::endl; LabPosMap labPosMap = readLabPos(labPosFileName); BOOST_LOG_TRIVIAL(trace) << "end loading label..." << std::endl; std::ifstream vertexFile(vertexFileName.c_str()), distributionFile(distributionFileName.c_str()), dataFile(dataFileName.c_str()); CSVIterator<std::string> vertexLine(vertexFile); ++vertexLine; // skips header. BOOST_LOG_TRIVIAL(trace) << "begin loading vertices\n"; for( ; vertexLine != CSVIterator<std::string>(); ++vertexLine ) { size_t id = boost::lexical_cast<size_t>( (*vertexLine)[0] ); int level = boost::lexical_cast<int>( (*vertexLine)[2] ); int cardinality = boost::lexical_cast<int>( (*vertexLine)[3] ); // printf("id: %lu, level: %d, card: %d, label: %s, pos: %d", id, level, cardinality, label.c_str(), position); std::string label = labPosMap[id].first; int position = labPosMap[id].second; create_graph_node( graph, cardinality, label, position, level ); } Graph& graphRef = *graph; BOOST_LOG_TRIVIAL(trace) << "end loading vertices: " << boost::num_vertices(graphRef) << "\n\n"; BOOST_LOG_TRIVIAL(trace) << "begin loading dist\n"; CSVIterator<std::string> distributionLine(distributionFile); while ( distributionLine != CSVIterator<std::string>() ) { plVariablesConjunction variables; // holds child variables plComputableObjectList jointDistri; size_t latentId = boost::lexical_cast<size_t>( (*distributionLine)[BN_LATENT_ID] ); size_t nbrChildren = boost::lexical_cast<size_t>( (*distributionLine)[NBR_CHILDREN] ); Node& latentNode = graphRef[ latentId ]; ++distributionLine; // reads next line. std::vector< plProbValue > probValuesZ; for ( size_t latentVal = 0; latentVal < latentNode.variable.cardinality(); ++latentVal) { // loads probability table for the latent var probValuesZ.push_back( boost::lexical_cast<plProbValue>( (*distributionLine)[latentVal] ) ); } const plProbTable probTabZ(latentNode.variable, probValuesZ); ++distributionLine; for ( size_t child = 0; child < nbrChildren; ++child ) { size_t childId = boost::lexical_cast<size_t>( (*distributionLine)[BN_LATENT_ID] ); ++distributionLine; Node& childNode = graphRef[ childId ]; variables ^= childNode.variable; plDistributionTable distTab_Xi_Z ( childNode.variable, latentNode.variable ); for ( size_t latentVal = 0; latentVal < latentNode.variable.cardinality(); ++latentVal ) { std::vector< plProbValue > probValuesXiZ_vals; for ( size_t childVal = 0; childVal < childNode.variable.cardinality(); ++childVal ) { probValuesXiZ_vals.push_back( boost::lexical_cast<plProbValue>( (*distributionLine)[childVal] ) ); } distTab_Xi_Z.push( plProbTable( childNode.variable, probValuesXiZ_vals), (int)latentVal ); ++distributionLine; } jointDistri *= distTab_Xi_Z; // adds the conditional table to result boost::add_edge( latentId, childId, graphRef ); } auto jd = ( probTabZ * jointDistri ); ++distributionLine; latentNode.set_joint_distribution( plJointDistribution(latentNode.variable ^ variables, probTabZ * jointDistri) ); } distributionFile.close(); vertexFile.close(); set_data(*graph, cndDataFileName, dataFileName); }
void UnitPainter::repaint(UnitView& unit_view, Unit& unit) { Timer paint_time(unit_paint_time); unit_view.paint.clear(); if (!unit_view.view_def) return; Script *script = unit_view.view_def->script.get(); if (!script) return; // The properties order for a unit paint script is: // - Variables // - Unit view // - Unit view def // - Unit // - Unit type // - Tile // - Tile type // Initial variables set: // - terrain_type // - faction_type (if owned) // - selected PaintExecution execution(&resources->scripts, resources, &unit_view.paint); //execution.add_properties(&unit_view.properties); //execution.add_properties(&unit_view.view_def->properties); execution.add_properties(&unit.properties); if (unit.type) execution.add_properties(&unit.type->properties); //execution.add_properties(&tile.properties); //execution.add_properties(&tile.type->properties); //Atom terrain_type_atom = AtomRegistry::atom("terrain_type"); //execution.variables.set<std::string>(terrain_type_atom, tile.type->name); /*if (unit.owner) { Atom faction_type_atom = AtomRegistry::atom("faction_type"); execution.variables.set<std::string>(faction_type_atom, unit.owner->type_name); }*/ Atom selected_atom = AtomRegistry::get_instance().atom("selected"); execution.variables.set<bool>(selected_atom, unit_view.selected); Atom shadow_atom = AtomRegistry::get_instance().atom("shadow"); execution.variables.set<bool>(shadow_atom, unit_view.shadow); Atom unit_facing_atom = AtomRegistry::get_instance().atom("unit_facing"); execution.variables.set<int>(unit_facing_atom, unit_view.facing); Atom unit_posture_atom = AtomRegistry::get_instance().atom("unit_posture"); Atom posture_atoms[] = { AtomRegistry::get_instance().atom("holding"), AtomRegistry::get_instance().atom("moving"), AtomRegistry::get_instance().atom("attacking"), AtomRegistry::get_instance().atom("recoiling"), AtomRegistry::get_instance().atom("dying") }; execution.variables.set<Atom>(unit_posture_atom, posture_atoms[unit_view.posture]); Atom unit_variation_atom = AtomRegistry::get_instance().atom("unit_variation"); execution.variables.set<int>(unit_variation_atom, unit_view.variation); try { execution.run(script); } catch (ScriptError& err) { BOOST_LOG_TRIVIAL(error) << boost::format("Error in script %s: %s") % script->name % err.what(); ++script_error_counter; } ++unit_paint_counter; }
void EDBLayer::query(QSQQuery *query, TupleTable *outputTable, std::vector<uint8_t> *posToFilter, std::vector<Term_t> *valuesToFilter) { PredId_t predid = query->getLiteral()->getPredicate().getId(); if (dbPredicates.count(predid)) { auto el = dbPredicates.find(predid); el->second.manager->query(query, outputTable, posToFilter, valuesToFilter); } else { IndexedTupleTable *rel = tmpRelations[predid]; uint8_t size = rel->getSizeTuple(); switch (size) { case 1: { uint64_t row[1]; if (posToFilter != NULL) { assert(posToFilter->size() == 1 && posToFilter->at(0) == (uint8_t) 0); for (std::vector<Term_t>::iterator itr = valuesToFilter->begin(); itr != valuesToFilter->end(); ++itr) { if (rel->exists(*itr)) { row[0] = *itr; outputTable->addRow(row); } } } else { //Copy all values for (std::vector <Term_t>::iterator itr = rel->getSingleColumn()->begin(); itr != rel->getSingleColumn()->end(); ++itr) { row[0] = *itr; outputTable->addRow(row); } } break; } case 2: { const uint8_t nRepeatedVars = query->getNRepeatedVars(); uint64_t row[2]; if (posToFilter == NULL || posToFilter->size() == 0) { for (std::vector<std::pair<Term_t, Term_t>>::iterator itr = rel->getTwoColumn1()->begin(); itr != rel->getTwoColumn1()->end(); ++itr) { bool valid = true; if (nRepeatedVars > 0) { for (uint8_t i = 0; i < nRepeatedVars; ++i) { std::pair<uint8_t, uint8_t> rp = query->getRepeatedVar(i); if (row[rp.first] != row[rp.second]) { valid = false; break; } } } if (valid) { row[0] = itr->first; row[1] = itr->second; outputTable->addRow(row); } } } else if (posToFilter->size() == 1) { std::vector<std::pair<Term_t, Term_t>> *pairs; bool inverted = posToFilter->at(0) != 0; if (!inverted) { pairs = rel->getTwoColumn1(); std::vector<std::pair<Term_t, Term_t>>::iterator itr1 = pairs->begin(); std::vector<Term_t>::iterator itr2 = valuesToFilter->begin(); while (itr1 != pairs->end() && itr2 != valuesToFilter->end()) { while (itr1 != pairs->end() && itr1->first < *itr2) { itr1++; } if (itr1 == pairs->end()) continue; while (itr2 != valuesToFilter->end() && itr1->first > *itr2) { itr2++; } if (itr1 != pairs->end() && itr2 != valuesToFilter->end()) { bool valid = true; if (nRepeatedVars > 0) { for (uint8_t i = 0; i < nRepeatedVars; ++i) { std::pair<uint8_t, uint8_t> rp = query->getRepeatedVar(i); if (row[rp.first] != row[rp.second]) { valid = false; break; } } } if (valid) { row[0] = itr1->first; row[1] = itr1->second; outputTable->addRow(row); } itr1++; } } } else { pairs = rel->getTwoColumn2(); std::vector<std::pair<Term_t, Term_t>>::iterator itr1 = pairs->begin(); std::vector<Term_t>::iterator itr2 = valuesToFilter->begin(); while (itr1 != pairs->end() && itr2 != valuesToFilter->end()) { while (itr1 != pairs->end() && itr1->second < *itr2) { itr1++; } if (itr1 == pairs->end()) continue; while (itr2 != valuesToFilter->end() && itr1->second > *itr2) { itr2++; } if (itr1 != pairs->end() && itr2 != valuesToFilter->end()) { bool valid = true; if (nRepeatedVars > 0) { for (uint8_t i = 0; i < nRepeatedVars; ++i) { std::pair<uint8_t, uint8_t> rp = query->getRepeatedVar(i); if (row[rp.first] != row[rp.second]) { valid = false; break; } } } if (valid) { row[0] = itr1->first; row[1] = itr1->second; outputTable->addRow(row); } itr1++; } } } } else { //posToFilter==2 std::vector<std::pair<Term_t, Term_t>> *pairs; bool inverted = posToFilter->at(0) != 0; if (!inverted) { pairs = rel->getTwoColumn1(); } else { pairs = rel->getTwoColumn2(); } for (std::vector<Term_t>::iterator itr = valuesToFilter->begin(); itr != valuesToFilter->end(); ) { //Binary search Term_t first = *itr; itr++; Term_t second = *itr; itr++; if (std::binary_search(pairs->begin(), pairs->end(), std::make_pair(first, second))) { bool valid = true; if (nRepeatedVars > 0) { for (uint8_t i = 0; i < nRepeatedVars; ++i) { std::pair<uint8_t, uint8_t> rp = query->getRepeatedVar(i); if (row[rp.first] != row[rp.second]) { valid = false; break; } } } if (valid) { row[0] = first; row[1] = second; outputTable->addRow(row); } } } } break; } default: BOOST_LOG_TRIVIAL(error) << "This should not happen"; throw 10; } } }
void Publisher::startThread(std::string& protocol, std::string& hostname, int port, std::string msg) { BOOST_LOG_TRIVIAL(info) << "Starting Req/Rep listener with reply message: " << msg << " on port " << port; _rep_thread = boost::thread(threaded_rep, connect_name(protocol, hostname, port), msg); _rep_thread.detach(); }
Connection_Generator_Factory::Connection_Generator_Factory() : m_class_name("Connection_Generator_Factory") { BOOST_LOG_TRIVIAL(trace) << CLASS_LOG << ", Running Constructor."; }
surface::instance_t make(const description_t& description) { BOOST_LOG_TRIVIAL(debug) << "Make surface sor"; const auto& points = description.points; spline_t spline = make_spline(points.begin(), points.end()); derivations_t derivations; rtree_t rtree; for (std::size_t i = 0; i < spline.size(); ++i) { const spline_segment_t& segment = spline[i]; const polynomial5_t derivation = differentiate(std::get<2>(segment) * std::get<2>(segment)); const float delta = std::get<1>(segment) - std::get<0>(segment); float max = std::max ( evaluate(std::get<2>(segment), 0.0f), evaluate(std::get<2>(segment), delta) ); std::array<float, 5> roots; const auto end = solve(derivation, roots.begin()); for (auto root = roots.begin(); root != end; ++root) if (*root >= 0.0f && *root <= delta) max = std::max ({ max, evaluate(std::get<2>(segment), *root) }); const box_t box ( point_t(-max, std::get<0>(segment), -max), point_t(+max, std::get<1>(segment), +max) ); derivations.emplace_back(derivation); rtree.insert(value_t(box, i)); } /* const box_t box = transform ( description.transformation, box_t// TODO: puke => ( vector_t { geo::get<X>(rtree.bounds().min_corner()), geo::get<Y>(rtree.bounds().min_corner()), geo::get<Z>(rtree.bounds().min_corner()) }, vector_t { geo::get<X>(rtree.bounds().max_corner()), geo::get<Y>(rtree.bounds().max_corner()), geo::get<Z>(rtree.bounds().max_corner()) } ) ); BOOST_LOG_TRIVIAL(trace) << "Box: min = " << box.min_corner() << ", max = " << box.max_corner() << std::endl; const box_t box// TODO: puke => ( vector_t { geo::get<X>(rtree.bounds().min_corner()), geo::get<Y>(rtree.bounds().min_corner()), geo::get<Z>(rtree.bounds().min_corner()) }, vector_t { geo::get<X>(rtree.bounds().max_corner()), geo::get<Y>(rtree.bounds().max_corner()), geo::get<Z>(rtree.bounds().max_corner()) } ); BOOST_LOG_TRIVIAL(trace) << "Box: min = " << box.min_corner() << ", max = " << box.max_corner() << std::endl; */ model_t model ( std::move(spline), std::move(derivations), std::move(rtree), points.front()[X], points.back()[X], points.front()[Y], points.back()[Y] // box ); return std::make_shared<instance_impl_t<model_t>>(description.transformation, std::move(model)); // return boost::make_tuple // ( // primitive::make<model> // ( // description.transformation, // std::move(spline), // std::move(derivations), // std::move(rtree), // points.front()[X], // points.back()[X], // points.front()[Y], // points.back()[Y] // ), // box, // 3 * spline.size() + 2 // ); }
void belief_propagation<F>::operator()() { // Generate edge potentials edge_potential_generation_time.start(); bp_pcpu::current_step = step_gen_edge_potential; x_lib::do_stream<belief_propagation<F>, init_edge_wrapper<F>, belief_edge_wrapper> (graph_storage, 0, init_stream, updates0_stream, NULL); graph_storage->close_stream(init_stream); edge_potential_generation_time.stop(); // Supersteps unsigned long PHASE = 0; unsigned long iters = 0; graph_storage->rewind_stream(updates0_stream); while ((iters++) < niters) { unsigned long updates_in_stream; unsigned long updates_out_stream; updates_in_stream = (PHASE == 0 ? updates1_stream : updates0_stream); updates_out_stream = (PHASE == 0 ? updates0_stream : updates1_stream); for (unsigned long i = 0; i < graph_storage->get_config()->super_partitions; i++) { if (graph_storage->get_config()->super_partitions > 1) { if (bp_pcpu::bsp_phase > 0) { graph_storage->state_load(vertex_stream, i); } graph_storage->state_prepare(i); } else if (bp_pcpu::bsp_phase == 0) { graph_storage->state_prepare(0); } x_lib::do_state_iter<belief_propagation<F> >(graph_storage, i); bp_pcpu::current_step = step_absorb; x_lib::do_stream<belief_propagation<F>, belief_edge_wrapper, belief_edge_wrapper> (graph_storage, i, updates_in_stream, ULONG_MAX, NULL); // need to replay the stream to determine updates graph_storage->rewind_stream(updates_in_stream); bp_pcpu::current_step = step_emit; x_lib::do_stream<belief_propagation<F>, belief_edge_wrapper, belief_edge_wrapper> (graph_storage, i, updates_in_stream, updates_out_stream, NULL); graph_storage->reset_stream(updates_in_stream, i); if (graph_storage->get_config()->super_partitions > 1) { graph_storage->state_store(vertex_stream, i); } } graph_storage->rewind_stream(updates_out_stream); if (graph_storage->get_config()->super_partitions > 1) { graph_storage->rewind_stream(vertex_stream); } PHASE = 1 - PHASE; bp_pcpu::bsp_phase++; if (heartbeat) { BOOST_LOG_TRIVIAL(info) << clock::timestamp() << " Completed phase " << bp_pcpu::bsp_phase; } } if (graph_storage->get_config()->super_partitions == 1) { graph_storage->state_store(vertex_stream, 0); } bp_pcpu::current_step = step_terminate; x_lib::do_cpu<belief_propagation<F> >(graph_storage, ULONG_MAX); setup_time.start(); graph_storage->terminate(); setup_time.stop(); wall_clock.stop(); BOOST_LOG_TRIVIAL(info) << "CORE::PHASES " << bp_pcpu::bsp_phase; setup_time.print("CORE::TIME::SETUP"); edge_potential_generation_time.print("CORE::TIME::EDGE_POT_GEN"); wall_clock.print("CORE::TIME::WALL"); }
CommandExecutorObjectPtr CommandExecutorObject::Create(::bash::domain::detail::WebScriptsInterfacePtr scripts) { BOOST_LOG_TRIVIAL(debug) << "bash::web::CommandExecutorObject::Create: Function call"; return CommandExecutorObjectPtr(new CommandExecutorObject(scripts)); }
void FLTM::execute( ClustAlgoPtr clustAlgo, CardFuncPtr cardFunc, GraphPtr graph ) { auto lab2Idx = create_index_map(*graph); Local2GlobalPtr l2g = create_local_to_global_map(*graph); auto criteria = clustAlgo->get_criteria(); int verticesNb = boost::num_vertices(*graph); for ( int step = 0; step < params.nbrSteps; ++step) { if (step > 0) { criteria = create_current_criteria( *graph, *l2g, params.maxDist, step); clustAlgo->set_measure( graph, l2g, criteria ); } BOOST_LOG_TRIVIAL(trace) << "FLTM - step[" << step << "] over " << params.nbrSteps; BOOST_LOG_TRIVIAL(trace) << "running clustering " << clustAlgo->name() << " on " << l2g->size(); auto partition = clustAlgo->run(); auto clustering = partition.to_clustering(); auto SIZE = l2g->size(); int nonSingletons = number_non_singletons(clustering); BOOST_LOG_TRIVIAL(trace) << "to obtain " << clustering.size() << " clusters with " << nonSingletons << " non-singletons clusters" ; if ( nonSingletons == 0 ) { BOOST_LOG_TRIVIAL(trace) << "stop due to only singleton."; return; } std::vector<int> l2gTemp(*l2g); Local2Global().swap(*l2g); int nbrGoodClusters = 0; // loop without any parallelization // for ( auto &cluster: clustering ) { // if ( cluster.size() > 1 ) { // //numClust++; // RandVar var("latent-"+boost::lexical_cast<std::string>(boost::num_vertices(*graph)), // plIntegerType(0, cardFunc->compute(cluster) - 1 )); // Node latentNode = create_latent_node( graph, var, l2gTemp, lab2Idx, cluster); // MultiEM em(params.nbrRestarts); // em.run( *graph, latentNode, params.emThres); // if ( accept_latent_variable( *graph, latentNode, params.latentVarQualityThres) ) { // nbrGoodClusters++; // add_latent_node( *graph, latentNode ); // update_index_map( *l2g, l2gTemp, latentNode ); // lab2Idx[ latentNode.getLabel() ] = latentNode.index; // for ( auto item: cluster ) { // // l2g.push_back( currentL2G.at(item) ); // boost::add_edge( latentNode.index, l2gTemp.at(item), *graph); // } // } else { // update_index_map( *l2g, l2gTemp, cluster); // } // } else { // update_index_map( *l2g, l2gTemp, cluster); // } // } // loop with working parallelization #ifdef _OPENMP //sets the max number of threads we can use omp_set_num_threads(params.jobsNumber); #endif //the array of shared resources in which the differents threads write Node latentVector[nonSingletons]; //the parallelizable section #pragma omp parallel for schedule(dynamic) for ( int i = 0 ; i < clustering.size() ; ++i) { if ( clustering[i].size() > 1 ) { RandVar var("latent-"+std::to_string(verticesNb + i), plIntegerType(0, cardFunc->compute(clustering[i]) - 1 )); latentVector[i] = create_latent_node( graph, var, l2gTemp, lab2Idx, clustering[i]); MultiEM em(params.nbrRestarts); em.run( *graph, latentVector[i], params.emThres); } } //the non parallelizable section for ( int i = 0 ; i < clustering.size() ; ++i) { if (clustering[i].size() > 1 && accept_latent_variable( *graph, latentVector[i], params.latentVarQualityThres)) { nbrGoodClusters++; add_latent_node( *graph, latentVector[i] ); update_index_map( *l2g, l2gTemp, latentVector[i] ); lab2Idx[ latentVector[i].getLabel() ] = latentVector[i].index; for ( auto item: clustering[i] ) { boost::add_edge( latentVector[i].index, l2gTemp.at(item), *graph); } } else { update_index_map( *l2g, l2gTemp, clustering[i]); } } verticesNb += nonSingletons ; // loop with parallelization slower than over // #pragma omp parallel for schedule(static) // for ( auto cluster = clustering.begin(); cluster < clustering.end() ; ++cluster) { // //for ( auto &cluster: clustering ) { // if ( cluster->size() > 1 ) { // RandVar var("latent-"+boost::lexical_cast<std::string>(boost::num_vertices(*graph)), // plIntegerType(0, cardFunc->compute(*cluster) - 1 )); // Node latentNode = create_latent_node( graph, var, l2gTemp, lab2Idx, *cluster); // MultiEM em(params.nbrRestarts); // em.run( *graph, latentNode, params.emThres); // if ( accept_latent_variable( *graph, latentNode, params.latentVarQualityThres) ) { // #pragma omp critical // { // nbrGoodClusters++; // add_latent_node( *graph, latentNode ); // update_index_map( *l2g, l2gTemp, latentNode ); // lab2Idx[ latentNode.getLabel() ] = latentNode.index; // for ( auto item: *cluster ) { // // l2g.push_back( currentL2G.at(item) ); // boost::add_edge( latentNode.index, l2gTemp.at(item), *graph); // } // } // } else { // #pragma omp critical // { // update_index_map( *l2g, l2gTemp, *cluster); // } // } // } else { // #pragma omp critical // { // update_index_map( *l2g, l2gTemp, *cluster); // } // } // } BOOST_LOG_TRIVIAL(trace) << "nbrGoodClusters: " << nbrGoodClusters; if ( nbrGoodClusters == 0 ) { BOOST_LOG_TRIVIAL(trace) << "stop due to zero good clusters."; return; } if (l2g->size() <= 1) { BOOST_LOG_TRIVIAL(trace) << "stop due to zero or only one cluster."; return; } BOOST_LOG_TRIVIAL(trace) << std::endl << std::endl; } }
bool GroupNodeImpl::spin_once() { // read a new event from the zyre node, interrupt if (zsys_interrupted || !ok() || stopped_) { BOOST_LOG_TRIVIAL(debug) << "GroupNode::spin_once(): zsysi " << (int)zsys_interrupted << " ok " << (int)!ok() << " stopped " << (int)stopped_ << std::endl; return false; } BOOST_LOG_TRIVIAL(debug) << "waiting for event" << std::endl; ScopedEvent e(zyre_event_new(node_)); // apparently, blocks until event occurs. // will be destroyed at the end of the function if (e.valid() && ok()) { BOOST_LOG_TRIVIAL(debug) << "got event" << std::endl; zyre_event_type_t t = e.type(); switch (t) { case ZYRE_EVENT_WHISPER: { std::string name = e.peer_name(); BOOST_LOG_TRIVIAL(debug) << name << " whispers -> " << node_name_ << std::endl; std::string peer_uuid = e.peer_uuid(); BOOST_LOG_TRIVIAL(debug) << " peer id " << peer_uuid << std::endl; zmsg_t* msg = e.message(); handle_whisper(peer_uuid, msg); } break; case ZYRE_EVENT_SHOUT: { std::string group_id = e.group(); BOOST_LOG_TRIVIAL(debug) << e.peer_name() << " " << group_id << " shouts ->" << node_name_ << std::endl; std::string peer_uuid = e.peer_uuid(); BOOST_LOG_TRIVIAL(debug) << " peer id " << peer_uuid << std::endl; zmsg_t* msg = e.message(); handle_shout(group_id, peer_uuid, msg); } break; case ZYRE_EVENT_ENTER: { std::string name = e.peer_name(); BOOST_LOG_TRIVIAL(debug) << name << " enters | " << node_name_ << std::endl; } break; case ZYRE_EVENT_JOIN: { std::string group_id = e.group(); BOOST_LOG_TRIVIAL(debug) << e.peer_name() << " joins " << group_id << " | " << node_name_ << std::endl; { basic_lock lk(join_mutex_); joins_[group_id]++; } join_cond_.notify_all(); } break; case ZYRE_EVENT_LEAVE: { std::string group_id = e.group(); BOOST_LOG_TRIVIAL(debug) << e.peer_name() << " leaves " << group_id << " | " << node_name_ << std::endl; { basic_lock lk(join_mutex_); joins_[group_id]--; }} break; case ZYRE_EVENT_EXIT: { if (e.peer_name() == node_name_) { stopped_ = true; } BOOST_LOG_TRIVIAL(debug) << e.peer_name() << " exits | " << node_name_ << std::endl; } break; case ZYRE_EVENT_STOP: { if (e.peer_name() == node_name_) { stopped_ = true; } BOOST_LOG_TRIVIAL(debug) << e.peer_name() << " stops | " << node_name_ << std::endl; } return false; default: BOOST_LOG_TRIVIAL(debug) << "got an unexpected event" << std::endl; } } else { BOOST_LOG_TRIVIAL(debug) << "No event" << std::endl; join_cond_.notify_all(); return false; } return true; }
ProwlGateway::ProwlGateway() : apiKey(), url(), application(), event(), priority() { BOOST_LOG_TRIVIAL(info) << "Create Prowl gateway"; InitializeFromConfig(); }
btTransform Utils::GL::getOrtho(float left, float right, float bottom, float top, float znear, float zfar) { btTransform ret; float matrix[16]; float temp, temp2, temp3, temp4; temp = 2.0f * znear; temp2 = right - left; temp3 = top - bottom; temp4 = zfar - znear; matrix[0] = 2.0f / temp2; matrix[1] = 0.0f; matrix[2] = 0.0f; matrix[3] = 0.0f; matrix[4] = 0.0f; matrix[5] = 2.0f / temp3; matrix[6] = 0.0f; matrix[7] = 0.0f; matrix[8] = 0.0f; matrix[9] = 0.0f; matrix[10] = -2.0f / temp4; matrix[11] = 0.0f; matrix[12] = - (right + left) / temp2; matrix[13] = - (top + bottom) / temp3; matrix[14] = - (zfar + znear) / temp4; matrix[15] = 1.0f; ret.setFromOpenGLMatrix(matrix); //std::cout << "X" << ret.getBasis().getRow(0).x; //std::cout << "Y" << ret.getBasis().getRow(0).y; //std::cout << "Z" <<ret.getBasis().getRow(0).z; BOOST_LOG_TRIVIAL(info) << "X" << ret.getBasis().getRow(0).x(); BOOST_LOG_TRIVIAL(info) << "Y" << ret.getBasis().getRow(0).y(); BOOST_LOG_TRIVIAL(info) << "Z" << ret.getBasis().getRow(0).z(); BOOST_LOG_TRIVIAL(info) << "W" << ret.getBasis().getRow(0).w(); BOOST_LOG_TRIVIAL(info) << "X" << ret.getBasis().getRow(1).x(); BOOST_LOG_TRIVIAL(info) << "Y" << ret.getBasis().getRow(1).y(); BOOST_LOG_TRIVIAL(info) << "Z" << ret.getBasis().getRow(1).z(); BOOST_LOG_TRIVIAL(info) << "W" << ret.getBasis().getRow(1).w(); BOOST_LOG_TRIVIAL(info) << "X" << ret.getBasis().getRow(2).x(); BOOST_LOG_TRIVIAL(info) << "Y" << ret.getBasis().getRow(2).y(); BOOST_LOG_TRIVIAL(info) << "Z" << ret.getBasis().getRow(2).z(); BOOST_LOG_TRIVIAL(info) << "W" << ret.getBasis().getRow(2).w(); ret.getOpenGLMatrix(matrix); for (int i = 0; i < 16; i++) { BOOST_LOG_TRIVIAL(info) << "A" << matrix[i]; } return ret; }
int main (int argc, char * argv[]) { // SET UP ARGUMENTS po::options_description desc("Options"); desc.add_options() ("input", po::value<std::string>()->required(), "Input hypergraph file") ("output", po::value<std::string>()->default_value("out.dat"), "Output transversals file") ("verbosity,v", po::value<int>()->default_value(0)->implicit_value(1), "Write verbose debugging output (-v2 for trace output)") ("algorithm,a", po::value<std::string>()->default_value("pmmcs"), "Algorithm to use (pmmcs, prs, fka, berge, bm)") ("num-threads,t", po::value<int>()->default_value(1), "Number of threads to run in parallel") ("cutoff-size,c", po::value<int>()->default_value(0), "Maximum size set to return (0: no limit)"); po::positional_options_description p; p.add("input", 1); p.add("output", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); if (vm.count("help") or argc == 1) { std::cout << desc << std::endl; return 1; }; const size_t num_threads = (vm["num-threads"].as<int>()); const size_t cutoff_size = (vm["cutoff-size"].as<int>()); po::notify(vm); // Process input file BOOST_LOG_TRIVIAL(debug) << "Loading hypergraph from file."; std::string input_file(vm["input"].as<std::string>()); agdmhs::Hypergraph H (input_file); BOOST_LOG_TRIVIAL(debug) << "Loading complete."; // Process logging-related options int verbosity = vm["verbosity"].as<int>(); switch (verbosity) { case 1: boost::log::core::get()->set_filter (boost::log::trivial::severity >= boost::log::trivial::debug); break; case 2: boost::log::core::get()->set_filter (boost::log::trivial::severity >= boost::log::trivial::trace); break; default: boost::log::core::get()->set_filter (boost::log::trivial::severity >= boost::log::trivial::warning); break; } // Print input information std::cout << "Input has " << H.num_verts() << " vertices and " << H.num_edges() << " edges." << std::endl; // Run chosen algorithm std::string algname = vm["algorithm"].as<std::string>(); std::unique_ptr<agdmhs::MHSAlgorithm> mhs_algorithm; if (algname == "berge") { mhs_algorithm = std::unique_ptr<agdmhs::MHSAlgorithm> (new agdmhs::BergeAlgorithm(cutoff_size)); } else if (algname == "bm") { mhs_algorithm = std::unique_ptr<agdmhs::MHSAlgorithm> (new agdmhs::ParBMAlgorithm (num_threads)); } else if (algname == "fka") { mhs_algorithm = std::unique_ptr<agdmhs::MHSAlgorithm> (new agdmhs::FKAlgorithmA()); } else if (algname == "mmcs" or algname == "pmmcs") { mhs_algorithm = std::unique_ptr<agdmhs::MHSAlgorithm> (new agdmhs::MMCSAlgorithm(num_threads, cutoff_size)); } else if (algname == "rs" or algname == "prs") { mhs_algorithm = std::unique_ptr<agdmhs::MHSAlgorithm> (new agdmhs::RSAlgorithm(num_threads, cutoff_size)); } else { std::stringstream error_message; error_message << "Did not recognize requested algorithm " << algname << "."; throw po::invalid_option_value(error_message.str()); } BOOST_LOG_TRIVIAL(debug) << "Running algorithm " << algname; agdmhs::Hypergraph Htrans = mhs_algorithm->transversal(H); std::cout << "Found " << Htrans.num_edges() << " hitting sets." << std::endl; BOOST_LOG_TRIVIAL(debug) << "Algorithm complete."; // Print results BOOST_LOG_TRIVIAL(debug) << "Writing result file."; std::string output_file(vm["output"].as<std::string>()); Htrans.write_to_file(output_file); BOOST_LOG_TRIVIAL(debug) << "Writing complete."; return 0; }
void belief_propagation<F>::partition_callback (x_lib::stream_callback_state *callback) { bp_pcpu *pcpu = static_cast<bp_pcpu *>(callback->cpu_state); switch (bp_pcpu::current_step) { case step_gen_edge_potential: { unsigned long tmp = callback->bytes_in; while (callback->bytes_in) { if ((callback->bytes_out + 2 * sizeof(struct belief_propagation_edge)) > callback->bytes_out_max) { break; } belief_propagation_edge *e_fwd = (belief_propagation_edge *) (callback->bufout + callback->bytes_out); belief_propagation_edge *e_rev = (belief_propagation_edge *) (callback->bufout + callback->bytes_out + sizeof(struct belief_propagation_edge)); generate_initial_belief(callback->bufin, e_fwd, e_rev); callback->bytes_out += 2 * sizeof(struct belief_propagation_edge); callback->bufin += F::split_size_bytes(); callback->bytes_in -= F::split_size_bytes(); } pcpu->edge_bytes_streamed += (tmp - callback->bytes_in); break; } case step_absorb: { pcpu->update_bytes_in += callback->bytes_in; while (callback->bytes_in) { belief_propagation_edge *u = (belief_propagation_edge *) (callback->bufin); belief_propagation_vertex *v = ((belief_propagation_vertex *) (callback->state)) + x_lib::configuration::map_offset(u->dst); for (unsigned long i = 0; i < BP_STATES; i++) { v->product[i] *= u->belief[i]; } callback->bufin += sizeof(struct belief_propagation_edge); callback->bytes_in -= sizeof(struct belief_propagation_edge); } break; } case step_emit: { while (callback->bytes_in) { if ((callback->bytes_out + sizeof(belief_propagation_edge)) > callback->bytes_out_max) { break; } BOOST_ASSERT_MSG(callback->bytes_out < callback->bytes_out_max, "Update buffer overflow !!!"); belief_propagation_edge *ein = (belief_propagation_edge *) (callback->bufin); belief_propagation_edge *eout = (belief_propagation_edge *) (callback->bufout); belief_propagation_vertex *v = ((belief_propagation_vertex *) (callback->state)) + x_lib::configuration::map_offset(ein->dst); eout->src = ein->dst; eout->dst = ein->src; weight_t sum = 0.0; for (unsigned long i = 0; i < BP_STATES; i++) { eout->belief[i] = 0; for (unsigned long j = 0; j < BP_STATES; j++) { eout->potential_up[i][j] = ein->potential_up[i][j]; eout->potential_down[i][j] = ein->potential_down[i][j]; if (eout->src < eout->dst) { eout->belief[i] += v->potentials[j] * eout->potential_up[i][j] * v->product[j] / ein->belief[j]; } else { eout->belief[i] += v->potentials[j] * eout->potential_down[i][j] * v->product[j] / ein->belief[j]; } } sum += eout->belief[i]; } if (sum > 0.0) { for (unsigned long i = 0; i < BP_STATES; i++) { eout->belief[i] /= sum; // Normalize } } callback->bufin += sizeof(struct belief_propagation_edge); callback->bufout += sizeof(struct belief_propagation_edge); callback->bytes_in -= sizeof(struct belief_propagation_edge); callback->bytes_out += sizeof(struct belief_propagation_edge); } pcpu->update_bytes_out += callback->bytes_out; break; } default: BOOST_LOG_TRIVIAL(fatal) << "Unknown operation in stream callback !"; exit(-1); } }
template<typename F>void triangle_counting<F>::operator() () { // Setup triangle_counting_per_processor_data::current_step = step_init_hstream; if(graph_storage->get_config()->super_partitions > 1) { x_lib::do_stream<triangle_counting<F>, init_edge_wrapper<F>, init_edge_wrapper<F> > (graph_storage, 0, init_stream, edge_stream, NULL); graph_storage->close_stream(init_stream); } graph_storage->rewind_stream(edge_stream); triangle_counting_per_processor_data::current_step = step_init_zstream; x_lib::do_stream<triangle_counting<F>, init_edge_wrapper<F>, tc_z_wrapper > (graph_storage, 0, edge_stream, z0_stream, NULL); // TC loop for(unsigned long iter=0;iter < niters;iter++) { graph_storage->rewind_stream(edge_stream); for(unsigned long i=0;i<graph_storage->get_config()->super_partitions;i++) { SP_PRE(i); triangle_counting_per_processor_data::current_step = step_compute_hash; x_lib::do_state_iter<triangle_counting<F> > (graph_storage, i); triangle_counting_per_processor_data::current_step = step_send_hash; x_lib::do_stream<triangle_counting<F>, init_edge_wrapper<F>, tc_hash_wrapper > (graph_storage, i, edge_stream, hash_stream, NULL, true); SP_POST(i); } graph_storage->rewind_stream(hash_stream); graph_storage->rewind_stream(z0_stream); for(unsigned long i=0;i<graph_storage->get_config()->super_partitions;i++) { SP_PRE(i); triangle_counting_per_processor_data::current_step = step_rcv_hash; x_lib::do_stream<triangle_counting<F>, tc_hash_wrapper, tc_hash_wrapper > (graph_storage, i, hash_stream, ULONG_MAX, NULL); graph_storage->reset_stream(hash_stream, i); triangle_counting_per_processor_data::current_step = step_zout; x_lib::do_stream<triangle_counting<F>, tc_z_wrapper, tc_z_wrapper > (graph_storage, i, z0_stream, z1_stream, NULL); graph_storage->reset_stream(z0_stream, i); SP_POST(i); } graph_storage->rewind_stream(z1_stream); for(unsigned long i=0;i<graph_storage->get_config()->super_partitions;i++) { SP_PRE(i); triangle_counting_per_processor_data::current_step = step_zin; x_lib::do_stream<triangle_counting<F>, tc_z_wrapper, tc_z_wrapper > (graph_storage, i, z1_stream, z0_stream, NULL); graph_storage->reset_stream(z1_stream, i); SP_POST(i); } if(heartbeat) { BOOST_LOG_TRIVIAL(info) << clock::timestamp() << " Completed phase " <<triangle_counting_per_processor_data::bsp_phase; } triangle_counting_per_processor_data::bsp_phase++; } graph_storage->rewind_stream(z0_stream); triangle_counting_per_processor_data::current_step = step_rollup; for(unsigned long i=0;i<graph_storage->get_config()->super_partitions;i++) { SP_PRE(i); x_lib::do_stream<triangle_counting<F>, tc_z_wrapper, tc_z_wrapper > (graph_storage, i, z0_stream, ULONG_MAX, NULL); graph_storage->reset_stream(z0_stream, i); x_lib::do_state_iter<triangle_counting<F> > (graph_storage, i); x_lib::do_cpu<triangle_counting>(graph_storage, i); SP_POST(i); } if(graph_storage->get_config()->super_partitions == 1) { graph_storage->state_store(vertex_stream, 0); } setup_time.start(); graph_storage->terminate(); setup_time.stop(); wall_clock.stop(); // Note div by 3.0 as each triangle is counted once at each incident // vertex BOOST_LOG_TRIVIAL(info) << "ALGORITHM::TRIANGLE_COUNTING::TRIANGLES " << triangle_counting_per_processor_data::total_triangles_global/3.0f; setup_time.print("CORE::TIME::SETUP"); wall_clock.print("CORE::TIME::WALL"); }
void Connection::activate() { BOOST_LOG_TRIVIAL(trace) << "activate"; startInRead(); }
// dtor ThreadCancellationPoint::~ThreadCancellationPoint() { BOOST_LOG_TRIVIAL(trace) << "ThreadCancellationPoint [" << this << "] being destructed."; }
Connection::Connection(boost::asio::io_service& service) : _inSocket(service) { BOOST_LOG_TRIVIAL(trace) << "Connection created"; }
Connection_Generator_Factory::~Connection_Generator_Factory() { BOOST_LOG_TRIVIAL(trace) << CLASS_LOG << ", Running Destructor."; }
Connection::~Connection() { BOOST_LOG_TRIVIAL(trace) << "Connection destroyed"; }
bool EDBLayer::isEmpty(const Literal &query, std::vector<uint8_t> *posToFilter, std::vector<Term_t> *valuesToFilter) { const Literal *literal = &query; PredId_t predid = literal->getPredicate().getId(); if (dbPredicates.count(predid)) { auto p = dbPredicates.find(predid); return p->second.manager->isEmpty(query, posToFilter, valuesToFilter); } else { IndexedTupleTable *rel = tmpRelations[predid]; assert(literal->getTupleSize() <= 2); std::unique_ptr<Literal> rewrittenLiteral; if (posToFilter != NULL) { //Create a new literal where the var are replaced by the constants VTuple t = literal->getTuple(); for (int i = 0; i < posToFilter->size(); ++i) { uint8_t pos = posToFilter->at(i); Term_t value = valuesToFilter->at(i); t.set(VTerm(0, value), pos); rewrittenLiteral = std::unique_ptr<Literal>(new Literal(literal->getPredicate(), t)); literal = rewrittenLiteral.get(); } } int diff = literal->getNUniqueVars() - literal->getTupleSize(); if (diff == 0) { return rel->getNTuples() == 0; } else if (diff == -1) { //The difference could be a duplicated variable or a constant bool foundConstant = false; uint8_t idxVar = 0; Term_t valConst = 0; for (uint8_t i = 0; i < literal->getTupleSize(); ++i) { if (!literal->getTermAtPos(i).isVariable()) { idxVar = i; valConst = literal->getTermAtPos(i).getValue(); foundConstant = true; } } if (foundConstant) { return !rel->exists(idxVar, valConst); } else { //Check all rows where two columns are equal for (std::vector<std::pair<Term_t, Term_t>>::iterator itr = rel->getTwoColumn1()->begin(); itr != rel->getTwoColumn1()->end(); ++itr) { if (itr->first == itr->second) { return false; } } return true; } } else { if (literal->getNUniqueVars() == 0) { //Need to check whether a particular row exists assert(literal->getTupleSize() == 2); if (std::binary_search(rel->getTwoColumn1()->begin(), rel->getTwoColumn1()->end(), std::make_pair((Term_t) literal->getTermAtPos(0).getValue(), (Term_t) literal->getTermAtPos(1).getValue()))) return false; else return true; } else { BOOST_LOG_TRIVIAL(error) << "Not supported"; throw 10; } } } }
// Here the perimeters are created cummulatively for all layer regions sharing the same parameters influencing the perimeters. // The perimeter paths and the thin fills (ExtrusionEntityCollection) are assigned to the first compatible layer region. // The resulting fill surface is split back among the originating regions. void Layer::make_perimeters() { BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id(); // keep track of regions whose perimeters we have already generated std::set<size_t> done; for (LayerRegionPtrs::iterator layerm = m_regions.begin(); layerm != m_regions.end(); ++ layerm) { size_t region_id = layerm - m_regions.begin(); if (done.find(region_id) != done.end()) continue; BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << ", region " << region_id; done.insert(region_id); const PrintRegionConfig &config = (*layerm)->region()->config(); // find compatible regions LayerRegionPtrs layerms; layerms.push_back(*layerm); for (LayerRegionPtrs::const_iterator it = layerm + 1; it != m_regions.end(); ++it) { LayerRegion* other_layerm = *it; const PrintRegionConfig &other_config = other_layerm->region()->config(); if (config.perimeter_extruder == other_config.perimeter_extruder && config.perimeters == other_config.perimeters && config.perimeter_speed == other_config.perimeter_speed && config.external_perimeter_speed == other_config.external_perimeter_speed && config.gap_fill_speed == other_config.gap_fill_speed && config.overhangs == other_config.overhangs && config.serialize("perimeter_extrusion_width").compare(other_config.serialize("perimeter_extrusion_width")) == 0 && config.thin_walls == other_config.thin_walls && config.external_perimeters_first == other_config.external_perimeters_first) { layerms.push_back(other_layerm); done.insert(it - m_regions.begin()); } } if (layerms.size() == 1) { // optimization (*layerm)->fill_surfaces.surfaces.clear(); (*layerm)->make_perimeters((*layerm)->slices, &(*layerm)->fill_surfaces); (*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces); } else { SurfaceCollection new_slices; { // group slices (surfaces) according to number of extra perimeters std::map<unsigned short,Surfaces> slices; // extra_perimeters => [ surface, surface... ] for (LayerRegionPtrs::iterator l = layerms.begin(); l != layerms.end(); ++l) { for (Surfaces::iterator s = (*l)->slices.surfaces.begin(); s != (*l)->slices.surfaces.end(); ++s) { slices[s->extra_perimeters].push_back(*s); } } // merge the surfaces assigned to each group for (std::map<unsigned short,Surfaces>::const_iterator it = slices.begin(); it != slices.end(); ++it) new_slices.append(union_ex(it->second, true), it->second.front()); } // make perimeters SurfaceCollection fill_surfaces; (*layerm)->make_perimeters(new_slices, &fill_surfaces); // assign fill_surfaces to each layer if (!fill_surfaces.surfaces.empty()) { for (LayerRegionPtrs::iterator l = layerms.begin(); l != layerms.end(); ++l) { // Separate the fill surfaces. ExPolygons expp = intersection_ex(to_polygons(fill_surfaces), (*l)->slices); (*l)->fill_expolygons = expp; (*l)->fill_surfaces.set(std::move(expp), fill_surfaces.surfaces.front()); } } } } BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << " - Done"; }
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ I_ModuleService::pModule_type ModuleService::load(const std::string& _moduleName) { boost::lock_guard<boost::mutex> guard(m_moduleMutex); ModuleNameIdx_type::iterator iter = m_moduleIdx.find(_moduleName); if(iter != m_moduleIdx.end()) { // Increment the reference count m_modules[iter->second]->incrementReferences(); // Return the return iter->second; } pModuleInfo_type pModuleInfo(new ModuleInfo); I_ModuleManager* pModuleManager = &I_ModuleManager::getSingleton(); boost::filesystem::path modulePath; if(!pModuleManager->findPath(_moduleName, modulePath)) { std::stringstream stream; stream << "Module " << _moduleName << " not found in defined module search paths."; BOOST_LOG_TRIVIAL(error) << stream.str(); throw std::exception(stream.str().c_str()); } pModuleInfo->setName(_moduleName); #ifdef _WIN32 I_ModuleInfo::ModuleHandle_type hModule = LoadLibraryA(modulePath.string().c_str()); #else BOOST_LOG_TRIVIAL(info) << "dlopen " << modulePath.string().c_str(); I_ModuleInfo::ModuleHandle_type hModule = dlopen(modulePath.string().c_str(), RTLD_NOW | RTLD_GLOBAL); #endif // _WIN32 if (hModule == NULL) { std::stringstream stream; stream << "Error loading module " << modulePath.string() #ifndef _WIN32 << dlerror() #else << ": The module is probably missing dependencies not on the path. Use depends.exe to figure it out." #endif ; BOOST_LOG_TRIVIAL(error) << stream.str(); throw std::exception(stream.str().c_str()); } pModuleInfo->setHandle(hModule); // Get the "getModule" procedure #if defined _WIN32 FARPROC proc = GetProcAddress(hModule, "getModule"); #else void* proc = dlsym(hModule, "getModule"); #endif // Check to make sure the procedure exists if (proc) { // Convert the procedure type to the assumed type #ifdef _WIN32 I_Module::proc_ptr_type pRealProc = (I_Module::proc_ptr_type)proc; #else I_Module::QUERY_MODULE_FUNCTION_PTR pRealProc = reinterpret_cast<I_Module::QUERY_MODULE_FUNCTION_PTR>(proc); #endif // Execute the procedure to get the I_Module for this module. pModule_type pModule = &(pRealProc()); // Set the reference count to 1 pModuleInfo->incrementReferences(); // Put it in the index m_moduleIdx[_moduleName] = pModule; // Put it in the cache m_modules[pModule] = pModuleInfo; // And return it. return pModule; } else { BOOST_LOG_TRIVIAL(error) << "Error getting procedure address in module " << modulePath.string(); // Not found, so return NULL return NULL; } }
/// check out sawConstraintController void updateKinematics(){ jointHandles_ = VrepRobotArmDriverP_->getJointHandles(); auto eigentestJacobian=::grl::vrep::getJacobian(*VrepRobotArmDriverP_); /// The row/column major order is swapped between cisst and VREP! this->currentKinematicsStateP_->Jacobian.SetSize(eigentestJacobian.cols(),eigentestJacobian.rows()); Eigen::Map<Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor> > mckp2(this->currentKinematicsStateP_->Jacobian.Pointer(),this->currentKinematicsStateP_->Jacobian.cols(),this->currentKinematicsStateP_->Jacobian.rows()); mckp2 = eigentestJacobian.cast<double>(); //Eigen::Map<Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor> > mf(eigentestJacobian,eigentestJacobian.cols(),eigentestJacobian.rows()); //Eigen::MatrixXf eigenJacobian = mf; Eigen::MatrixXf eigenJacobian = eigentestJacobian; /////////////////////////////////////////////////////////// // Copy Joint Interval, the range of motion for each joint // lower limits auto & llim = std::get<vrep::VrepRobotArmDriver::JointLowerPositionLimit>(currentArmState_); std::vector<double> llimits(llim.begin(),llim.end()); jointPositionLimitsVFP_->LowerLimits = vctDoubleVec(llimits.size(),&llimits[0]); // upper limits auto & ulim = std::get<vrep::VrepRobotArmDriver::JointUpperPositionLimit>(currentArmState_); std::vector<double> ulimits(ulim.begin(),ulim.end()); jointPositionLimitsVFP_->UpperLimits = vctDoubleVec(ulimits.size(),&ulimits[0]); // current position auto & currentJointPos = std::get<vrep::VrepRobotArmDriver::JointPosition>(currentArmState_); std::vector<double> currentJointPosVec(currentJointPos.begin(),currentJointPos.end()); vctDoubleVec vctDoubleVecCurrentJoints(currentJointPosVec.size(),¤tJointPosVec[0]); // update limits /// @todo does this leak memory when called every time around? UpdateJointPosLimitsVF(positionLimitsName,jointPositionLimitsVFP_->UpperLimits,jointPositionLimitsVFP_->LowerLimits,vctDoubleVecCurrentJoints); const auto& handleParams = VrepRobotArmDriverP_->getVrepHandleParams(); Eigen::Affine3d currentEndEffectorPose = getObjectTransform( std::get<vrep::VrepRobotArmDriver::RobotTipName>(handleParams) ,std::get<vrep::VrepRobotArmDriver::RobotTargetBaseName>(handleParams) ); auto currentEigenT = currentEndEffectorPose.translation(); auto& currentCisstT = currentKinematicsStateP_->Frame.Translation(); currentCisstT[0] = currentEigenT(0); currentCisstT[1] = currentEigenT(1); currentCisstT[2] = currentEigenT(2); #ifndef IGNORE_ROTATION Eigen::Map<Eigen::Matrix<double,3,3,Eigen::ColMajor>> ccr(currentKinematicsStateP_->Frame.Rotation().Pointer()); ccr = currentEndEffectorPose.rotation(); #endif // IGNORE_ROTATION /// @todo set rotation component of current position Eigen::Affine3d desiredEndEffectorPose = getObjectTransform( std::get<vrep::VrepRobotArmDriver::RobotTargetName>(handleParams) ,std::get<vrep::VrepRobotArmDriver::RobotTargetBaseName>(handleParams) ); auto desiredEigenT = desiredEndEffectorPose.translation(); auto& desiredCisstT = desiredKinematicsStateP_->Frame.Translation(); desiredCisstT[0] = desiredEigenT(0); desiredCisstT[1] = desiredEigenT(1); desiredCisstT[2] = desiredEigenT(2); #ifndef IGNORE_ROTATION Eigen::Map<Eigen::Matrix<double,3,3,Eigen::ColMajor>> dcr(desiredKinematicsStateP_->Frame.Rotation().Pointer()); dcr = desiredEndEffectorPose.rotation(); #endif // IGNORE_ROTATION /// @todo set rotation component of desired position // for debugging, the translation between the current and desired position in cartesian coordinates auto inputDesired_dx = desiredCisstT - currentCisstT; vct3 dx_translation, dx_rotation; // Rotation part vctAxAnRot3 dxRot; vct3 dxRotVec; dxRot.FromNormalized((currentKinematicsStateP_->Frame.Inverse() * desiredKinematicsStateP_->Frame).Rotation()); dxRotVec = dxRot.Axis() * dxRot.Angle(); dx_rotation[0] = dxRotVec[0]; dx_rotation[1] = dxRotVec[1]; dx_rotation[2] = dxRotVec[2]; //dx_rotation.SetAll(0.0); dx_rotation = currentKinematicsStateP_->Frame.Rotation() * dx_rotation; Eigen::AngleAxis<float> tipToTarget_cisstToEigen; Eigen::Matrix3f rotmat; double theta = std::sqrt(dx_rotation[0]*dx_rotation[0]+dx_rotation[1]*dx_rotation[1]+dx_rotation[2]*dx_rotation[2]); rotmat= Eigen::AngleAxisf(theta,Eigen::Vector3f(dx_rotation[0]/theta,dx_rotation[1]/theta,dx_rotation[2]/theta)); // std::cout << "\ntiptotarget \n" << tipToTarget.matrix() << "\n"; // std::cout << "\ntiptotargetcisst\n" << rotmat.matrix() << "\n"; //BOOST_LOG_TRIVIAL(trace) << "\n test desired dx: " << inputDesired_dx << " " << dx_rotation << "\noptimizer Calculated dx: " << optimizerCalculated_dx; SetKinematics(*currentKinematicsStateP_); // replaced by name of object // fill these out in the desiredKinematicsStateP_ //RotationType RotationMember; // vcRot3 //TranslationType TranslationMember; // vct3 SetKinematics(*desiredKinematicsStateP_); // replaced by name of object // call setKinematics with the new kinematics // sawconstraintcontroller has kinematicsState // set the jacobian here ////////////////////// /// @todo move code below here back under run_one updateKinematics() call /// @todo need to provide tick time in double seconds and get from vrep API call float simulationTimeStep = simGetSimulationTimeStep(); UpdateOptimizer(simulationTimeStep); vctDoubleVec jointAngles_dt; auto returncode = Solve(jointAngles_dt); /// @todo check the return code, if it doesn't have a result, use the VREP version as a fallback and report an error. if(returncode != nmrConstraintOptimizer::NMR_OK) BOOST_THROW_EXCEPTION(std::runtime_error("VrepInverseKinematicsController: constrained optimization error, please investigate")); /// @todo: rethink where/when/how to send command for the joint angles. Return to LUA? Set Directly? Distribute via vrep send message command? std::string str; // str = ""; for (std::size_t i=0 ; i < jointHandles_.size() ; i++) { float currentAngle; auto ret = simGetJointPosition(jointHandles_[i],¤tAngle); BOOST_VERIFY(ret!=-1); float futureAngle = currentAngle + jointAngles_dt[i]; //simSetJointTargetVelocity(jointHandles_[i],jointAngles_dt[i]/simulationTimeStep); //simSetJointTargetPosition(jointHandles_[i],jointAngles_dt[i]); //simSetJointTargetPosition(jointHandles_[i],futureAngle); simSetJointPosition(jointHandles_[i],futureAngle); str+=boost::lexical_cast<std::string>(jointAngles_dt[i]); if (i<jointHandles_.size()-1) str+=", "; } BOOST_LOG_TRIVIAL(trace) << "jointAngles_dt: "<< str; auto optimizerCalculated_dx = this->currentKinematicsStateP_->Jacobian * jointAngles_dt; BOOST_LOG_TRIVIAL(trace) << "\n desired dx: " << inputDesired_dx << " " << dx_rotation << "\noptimizer Calculated dx: " << optimizerCalculated_dx; }
/** vertex file: see SINGLE format. * distribution file: see above. */ void BayesGraphSave::operator()( const Graph& graph, const std::string vertexFileName, const std::string distFileName ) const { std::ofstream distFile(distFileName.c_str()), vertexFile(vertexFileName.c_str()); vertex_iterator vi, vi_end; Label2Index label2Index; vertexFile << ID << GRAPH_SEPARATOR << LATENT << GRAPH_SEPARATOR << LEVEL << GRAPH_SEPARATOR << CARDINALITY << GRAPH_SEPARATOR << "label" << "\n"; // writes header BOOST_LOG_TRIVIAL(trace) << "saving vertices...\n"; for ( boost::tie(vi, vi_end) = boost::vertices(graph); vi != vi_end; ++vi ) { int vertex = *vi; vertexFile << graph[vertex].index << GRAPH_SEPARATOR << !(graph[vertex].is_leaf()) << GRAPH_SEPARATOR << graph[vertex].level << GRAPH_SEPARATOR << graph[vertex].variable.cardinality() << GRAPH_SEPARATOR << graph[vertex].getLabel() << std::endl; label2Index[graph[vertex].getLabel()] = graph[vertex].index; } vertexFile.close(); BOOST_LOG_TRIVIAL(trace) << "saving joint distribution...\n"; for ( boost::tie(vi, vi_end) = boost::vertices(graph); vi != vi_end; ++vi ) { const Node& node = graph[*vi]; if ( !node.is_leaf() ) { auto latentVar = node.variable; // plJointDistribution distribution = node.jointDistribution; // plVariablesConjunction all_variables = distribution.get_variables(); // all variables (latent variable and its children) plVariablesConjunction childVars = node.get_children_variables(); // child childVars // for (size_t i = 1; i < all_variables.size(); ++i) // childVars ^= all_variables[i]; // initializes child conjunction. // plSymbol latentVar = all_variables[0]; // latent variable distFile << node.index << GRAPH_SEPARATOR << childVars.size() << std::endl; // plComputableObjectList objLists = distribution.get_computable_object_list(); // plComputableObject probTableZ = objLists.get_distribution_over(latentVar); // distribution table for the latent variable auto probTableZ = node.marginalDist; int val; for ( val = 0; val < latentVar.cardinality() - 1 ; ++val ) { distFile << std::fixed << std::setprecision(30) << probTableZ->compute( plValues().add(latentVar, val) ) << GRAPH_SEPARATOR; // P(latentVar = val) } distFile << std::fixed << std::setprecision(15) << probTableZ->compute( plValues().add(latentVar, val) ) << std::endl; // writes last probability value for ( size_t i = 0; i < childVars.size(); ++i ) { plSymbol varX = childVars[ i ]; // retrieves the child variable distFile << label2Index[varX.name()] << std::endl; // writes child variable's id. auto distTableXZ = node.cndChildrenDists.at(i); //objLists.get_distribution_over(varX); // conditional distribution P(X_i | Z) // plDistributionTable& distTableXZ = // static_cast<plDistributionTable&>( compTableXZ ); // casting P(X_i | Z) to derived class for ( val = 0; val < latentVar.cardinality(); ++val ) { int childVal; for ( childVal = 0; childVal < varX.cardinality() - 1; ++childVal ) { // for each value x of the child variable distFile << std::fixed << std::setprecision(15) << distTableXZ->compute( plValues().add(latentVar, val).add(varX, childVal) ) << GRAPH_SEPARATOR; // p(X_i = childVal | Z = val) } distFile << std::fixed << std::setprecision(15) << distTableXZ->compute( plValues().add(latentVar, val).add(varX, childVal) ) << std::endl; } } distFile << std::endl; // breaks the line, moves to the next latent variable. } } distFile.close(); }
int main(int argc, char** argv) { #ifdef TLS_OVER_TCP_LINK using Client = ssf::SSFClient<ssf::SSLPolicy, ssf::NullLinkAuthenticationPolicy, ssf::BounceProtocolPolicy, ssf::TransportProtocolPolicy>; #elif TCP_ONLY_LINK using Client = ssf::SSFClient<ssf::TCPPolicy, ssf::NullLinkAuthenticationPolicy, ssf::BounceProtocolPolicy, ssf::TransportProtocolPolicy>; #endif using demux = Client::demux; using BaseUserServicePtr = ssf::services::BaseUserService<demux>::BaseUserServicePtr; using BounceParser = ssf::parser::BounceParser; Init(); // Register user services supported ssf::services::Socks<demux>::RegisterToServiceOptionFactory(); ssf::services::RemoteSocks<demux>::RegisterToServiceOptionFactory(); ssf::services::PortForwading<demux>::RegisterToServiceOptionFactory(); ssf::services::RemotePortForwading<demux>::RegisterToServiceOptionFactory(); ssf::services::UdpPortForwading<demux>::RegisterToServiceOptionFactory(); ssf::services::UdpRemotePortForwading< demux>::RegisterToServiceOptionFactory(); boost::program_options::options_description options = ssf::ServiceOptionFactory<demux>::GetOptionDescriptions(); // Parse the command line ssf::command_line::standard::CommandLine cmd; std::vector<BaseUserServicePtr> user_services; boost::system::error_code ec; auto parameters = cmd.parse(argc, argv, options, ec); if (ec) { BOOST_LOG_TRIVIAL(error) << "client: wrong command line arguments"; return 1; } // Initialize requested user services (socks, port forwarding) for (const auto& parameter : parameters) { for (const auto& single_parameter : parameter.second) { boost::system::error_code ec; auto p_service_options = ssf::ServiceOptionFactory<demux>::ParseServiceLine( parameter.first, single_parameter, ec); if (!ec) { user_services.push_back(p_service_options); } else { BOOST_LOG_TRIVIAL(error) << "client: wrong parameter " << parameter.first << " : " << single_parameter << " : " << ec.message(); } } } if (!cmd.IsAddrSet()) { BOOST_LOG_TRIVIAL(error) << "client: no hostname provided -- Exiting"; return 1; } if (!cmd.IsPortSet()) { BOOST_LOG_TRIVIAL(error) << "client: no host port provided -- Exiting"; return 1; } // Load SSF config if any boost::system::error_code ec_config; ssf::Config ssf_config = ssf::LoadConfig(cmd.config_file(), ec_config); if (ec_config) { BOOST_LOG_TRIVIAL(error) << "client: invalid config file format" << std::endl; return 0; } // Initialize the asynchronous engine boost::asio::io_service io_service; boost::asio::io_service::work worker(io_service); boost::thread_group threads; for (uint8_t i = 0; i < boost::thread::hardware_concurrency(); ++i) { auto lambda = [&]() { boost::system::error_code ec; try { io_service.run(ec); } catch (std::exception e) { BOOST_LOG_TRIVIAL(error) << "client: exception in io_service run " << e.what(); } }; threads.create_thread(lambda); } auto callback = [](ssf::services::initialisation::type, BaseUserServicePtr, const boost::system::error_code&) {}; // Initiate and start client Client client(io_service, cmd.addr(), std::to_string(cmd.port()), ssf_config, user_services, callback); std::map<std::string, std::string> params; std::list<std::string> bouncers = BounceParser::ParseBounceFile(cmd.bounce_file()); if (bouncers.size()) { auto first = bouncers.front(); bouncers.pop_front(); params["remote_addr"] = BounceParser::GetRemoteAddress(first); params["remote_port"] = BounceParser::GetRemotePort(first); bouncers.push_back(cmd.addr() + ":" + std::to_string(cmd.port())); } else { params["remote_addr"] = cmd.addr(); params["remote_port"] = std::to_string(cmd.port()); } std::ostringstream ostrs; boost::archive::text_oarchive ar(ostrs); ar << BOOST_SERIALIZATION_NVP(bouncers); params["bouncing_nodes"] = ostrs.str(); client.run(params); getchar(); client.stop(); threads.join_all(); io_service.stop(); return 0; }
Capabilities::ptr_t Capabilities::Parse_WMS_1_3_0( const std::string& contents, Status& status ) { // Create the PugiXML Document pugi::xml_document xmldoc; pugi::xml_parse_result result = xmldoc.load_string( contents.c_str() ); // check for loading errors if( result == false ) { status = Status( StatusCode::INVALID_FORMAT, "Unable to parse WMS Capabilities data."); return nullptr; } // XML Queries const std::string ROOT_NODE_QUERY = "WMS_Capabilities"; //version="1.3.0" xmlns="http://www.opengis.net/wms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wms http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd"> // Create Capabilities Object Capabilities::ptr_t cap = std::make_shared<Capabilities>( OGC_Service::WMS, "1.3.0"); Status temp_status; try { // Get the Root Node pugi::xml_node root_node = xmldoc.child(ROOT_NODE_QUERY.c_str()); if( root_node == pugi::xml_node() ) { throw std::runtime_error("No Root Node Found."); } // Start Iterating Over Nodes pugi::xml_node_iterator nit = root_node.begin(); for( ; nit != root_node.end(); nit++ ) { // Process the Service node if( std::string(nit->name()) == "Service" ) { Parse_WMS_1_3_0_Service_Node( cap, (*nit), temp_status ); if( temp_status.Get_Code() != StatusCode::SUCCESS ) { throw std::runtime_error("Unable to Parse Service Node. Details: " + temp_status.ToString()); } } // Process the Capability Node else if( std::string(nit->name()) == "Capability" ) { Parse_WMS_1_3_0_Capability_Node( cap, (*nit), temp_status ); if( temp_status.Get_Code() != StatusCode::SUCCESS ) { throw std::runtime_error("Unable to Parse Capability Node. Details: " + temp_status.ToString()); } } // Otherwise, error else { BOOST_LOG_TRIVIAL(warning) << "Unknown Node: " << nit->name(); } } } catch( std::exception& e ) { status = Status(StatusCode::INVALID_FORMAT, "WMS Get Capabilities has invalid structure. " + std::string(e.what())); return nullptr; } catch(...) { status = Status(StatusCode::INVALID_FORMAT, "WMS Get Capabilities has invalid structure."); return nullptr; } // Return Success status = Status( StatusCode::SUCCESS ); return cap; }
std::shared_ptr<gameplay::Model> OBJWriter::readModel(const boost::filesystem::path& path, const std::shared_ptr<gameplay::ShaderProgram>& shaderProgram, const glm::vec3& ambientColor) const { Assimp::Importer importer; const aiScene* scene = importer.ReadFile((m_basePath / path).string(), aiProcess_JoinIdenticalVertices | aiProcess_Triangulate | aiProcess_ValidateDataStructure | aiProcess_FlipUVs); BOOST_ASSERT(scene != nullptr); auto renderModel = std::make_shared<gameplay::Model>(); for( unsigned int mi = 0; mi < scene->mNumMeshes; ++mi ) { BOOST_LOG_TRIVIAL(info) << "Converting mesh " << mi + 1 << " of " << scene->mNumMeshes << " from " << m_basePath / path; const aiMesh* mesh = scene->mMeshes[mi]; if( mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE ) BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not consist of triangles only")); if( !mesh->HasTextureCoords(0) ) BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have UV coordinates")); if( mesh->mNumUVComponents[0] != 2 ) BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have a 2D UV channel")); if( !mesh->HasFaces() ) BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have faces")); if( !mesh->HasPositions() ) BOOST_THROW_EXCEPTION(std::runtime_error("Mesh does not have positions")); std::shared_ptr<gameplay::Mesh> renderMesh; if( mesh->HasNormals() ) { std::vector<VDataNormal> vbuf(mesh->mNumVertices); for( unsigned int i = 0; i < mesh->mNumVertices; ++i ) { vbuf[i].position = glm::vec3{mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z} * static_cast<float>(SectorSize); vbuf[i].normal = glm::vec3{mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z}; vbuf[i].uv = glm::vec2{mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; if( mesh->HasVertexColors(0) ) vbuf[i].color = glm::vec4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, mesh->mColors[0][i].a); else vbuf[i].color = glm::vec4(ambientColor, 1); } renderMesh = std::make_shared<gameplay::Mesh>(VDataNormal::getFormat(), mesh->mNumVertices, false); renderMesh->rebuild(reinterpret_cast<const float*>(vbuf.data()), mesh->mNumVertices); } else { std::vector<VData> vbuf(mesh->mNumVertices); for( unsigned int i = 0; i < mesh->mNumVertices; ++i ) { vbuf[i].position = glm::vec3{mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z} * static_cast<float>(SectorSize); vbuf[i].uv = glm::vec2{mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; if( mesh->HasVertexColors(0) ) vbuf[i].color = glm::vec4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, mesh->mColors[0][i].a); else vbuf[i].color = glm::vec4(ambientColor, 1); } renderMesh = std::make_shared<gameplay::Mesh>(VData::getFormat(), mesh->mNumVertices, false); renderMesh->rebuild(reinterpret_cast<const float*>(vbuf.data()), mesh->mNumVertices); } std::vector<uint32_t> faces; for( const aiFace& face : gsl::span<aiFace>(mesh->mFaces, mesh->mNumFaces) ) { BOOST_ASSERT(face.mNumIndices == 3); faces.push_back(face.mIndices[0]); faces.push_back(face.mIndices[1]); faces.push_back(face.mIndices[2]); } auto part = renderMesh->addPart(gameplay::Mesh::TRIANGLES, gameplay::Mesh::INDEX32, mesh->mNumFaces * 3, false); part->setIndexData(faces.data(), 0, faces.size()); const aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; aiString textureName; if( material->GetTexture(aiTextureType_DIFFUSE, 0, &textureName) != aiReturn_SUCCESS ) BOOST_THROW_EXCEPTION(std::runtime_error("Failed to get diffuse texture path from mesh")); part->setMaterial(readMaterial(textureName.C_Str(), shaderProgram)); renderModel->addMesh(renderMesh); } return renderModel; }