diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index fa6dce2ed..29f0f22dd 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -26,6 +26,11 @@ #include #include +namespace osrm +{ +namespace contractor +{ + class Contractor { @@ -65,12 +70,12 @@ class Contractor ContractorHeapData(short h, bool t) : hop(h), target(t) {} }; - using ContractorGraph = DynamicGraph; - // using ContractorHeap = BinaryHeap; + // using ContractorHeap = util::BinaryHeap // >; using ContractorHeap = - BinaryHeap>; + util::BinaryHeap>; using ContractorEdge = ContractorGraph::InputEdge; struct ContractorThreadData @@ -151,7 +156,7 @@ class Contractor #ifndef NDEBUG if (static_cast(std::max(diter->weight, 1)) > 24 * 60 * 60 * 10) { - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "Edge weight large -> " << static_cast(std::max(diter->weight, 1)) << " : " << static_cast(diter->source) << " -> " @@ -253,11 +258,11 @@ class Contractor // } // } // - // SimpleLogger().Write() << "edges at node with id " << highestNode << " has degree + // util::SimpleLogger().Write() << "edges at node with id " << highestNode << " has degree // " << maxdegree; // for(unsigned i = contractor_graph->BeginEdges(highestNode); i < // contractor_graph->EndEdges(highestNode); ++i) { - // SimpleLogger().Write() << " ->(" << highestNode << "," << + // util::SimpleLogger().Write() << " ->(" << highestNode << "," << // contractor_graph->GetTarget(i) // << "); via: " << contractor_graph->GetEdgeData(i).via; // } @@ -281,7 +286,7 @@ class Contractor constexpr size_t DeleteGrainSize = 1; const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); - Percent p(number_of_nodes); + util::Percent p(number_of_nodes); ThreadDataContainer thread_data_list(number_of_nodes); @@ -340,7 +345,7 @@ class Contractor if (!flushed_contractor && (number_of_contracted_nodes > static_cast(number_of_nodes * 0.65 * core_factor))) { - DeallocatingVector new_edge_set; // this one is not explicitely + util::DeallocatingVector new_edge_set; // this one is not explicitely // cleared since it goes out of // scope anywa std::cout << " [flush " << number_of_contracted_nodes << " nodes] " << std::flush; @@ -357,7 +362,7 @@ class Contractor // remaining graph std::vector new_node_id_from_orig_id_map(number_of_nodes, UINT_MAX); - for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) { auto &node = remaining_nodes[new_node_id]; BOOST_ASSERT(node_priorities.size() > node.id); @@ -365,7 +370,7 @@ class Contractor } // build forward and backward renumbering map and remap ids in remaining_nodes - for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) { auto &node = remaining_nodes[new_node_id]; // create renumbering maps in both directions @@ -375,7 +380,7 @@ class Contractor } // walk over all nodes for (const auto source : - osrm::irange(0, contractor_graph->GetNumberOfNodes())) + util::irange(0, contractor_graph->GetNumberOfNodes())) { for (auto current_edge : contractor_graph->GetAdjacentEdgeRange(source)) { @@ -389,7 +394,7 @@ class Contractor else { // node is not yet contracted. - // add (renumbered) outgoing edges to new DynamicGraph. + // add (renumbered) outgoing edges to new util::DynamicGraph. ContractorEdge new_edge = {new_node_id_from_orig_id_map[source], new_node_id_from_orig_id_map[target], data}; @@ -590,7 +595,7 @@ class Contractor // avgdegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // quaddegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // - // SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", max: " + // util::SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", max: " // << maxdegree << ", min: " << mindegree << ", avg: " << avgdegree << ", // quad: " << quaddegree; @@ -633,7 +638,7 @@ class Contractor is_core_node.clear(); } - SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " + util::SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " << contractor_graph->GetNumberOfEdges() << " edges." << std::endl; thread_data_list.data.clear(); @@ -649,15 +654,15 @@ class Contractor out_node_levels.swap(node_levels); } - template inline void GetEdges(DeallocatingVector &edges) + template inline void GetEdges(util::DeallocatingVector &edges) { - Percent p(contractor_graph->GetNumberOfNodes()); - SimpleLogger().Write() << "Getting edges of minimized graph"; + util::Percent p(contractor_graph->GetNumberOfNodes()); + util::SimpleLogger().Write() << "Getting edges of minimized graph"; const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); if (contractor_graph->GetNumberOfNodes()) { Edge new_edge; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : util::irange(0u, number_of_nodes)) { p.printStatus(node); for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) @@ -940,7 +945,7 @@ class Contractor std::sort(neighbours.begin(), neighbours.end()); neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); - for (const auto i : osrm::irange(0, neighbours.size())) + for (const auto i : util::irange(0, neighbours.size())) { contractor_graph->DeleteEdgesTo(neighbours[i], node); } @@ -1060,7 +1065,10 @@ class Contractor std::vector orig_node_id_from_new_node_id_map; std::vector node_levels; std::vector is_core_node; - XORFastHash fast_hash; + util::XORFastHash fast_hash; }; +} +} + #endif // CONTRACTOR_HPP diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index c64681fa9..cb29d82f3 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace contractor +{ + enum class return_code : unsigned { ok, @@ -51,4 +56,7 @@ struct ContractorOptions static void GenerateOutputFilesNames(ContractorConfig &extractor_config); }; +} +} + #endif // EXTRACTOR_OPTIONS_HPP diff --git a/include/contractor/crc32_processor.hpp b/include/contractor/crc32_processor.hpp index df9fa9686..827cdda0a 100644 --- a/include/contractor/crc32_processor.hpp +++ b/include/contractor/crc32_processor.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace contractor +{ + class IteratorbasedCRC32 { public: @@ -115,4 +120,7 @@ struct RangebasedCRC32 IteratorbasedCRC32 crc32; }; +} +} + #endif /* ITERATOR_BASED_CRC32_H */ diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index 5c0713fde..d1bc08e24 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -8,14 +8,22 @@ #include "util/deallocating_vector.hpp" #include "util/node_based_graph.hpp" -struct SpeedProfileProperties; -struct EdgeBasedNode; -struct lua_State; - #include #include +struct lua_State; + +namespace osrm +{ +namespace extractor +{ +struct SpeedProfileProperties; +struct EdgeBasedNode; +} +namespace contractor +{ + /** \brief class of 'prepare' utility. */ @@ -32,26 +40,29 @@ class Prepare protected: void ContractGraph(const unsigned max_edge_id, - DeallocatingVector &edge_based_edge_list, - DeallocatingVector &contracted_edge_list, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, std::vector &is_core_node, std::vector &node_levels) const; void WriteCoreNodeMarker(std::vector &&is_core_node) const; void WriteNodeLevels(std::vector &&node_levels) const; void ReadNodeLevels(std::vector &contraction_order) const; std::size_t WriteContractedGraph(unsigned number_of_edge_based_nodes, - const DeallocatingVector &contracted_edge_list); + const util::DeallocatingVector &contracted_edge_list); void FindComponents(unsigned max_edge_id, - const DeallocatingVector &edges, - std::vector &nodes) const; + const util::DeallocatingVector &edges, + std::vector &nodes) const; private: ContractorConfig config; std::size_t LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, - DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &edge_based_edge_list, const std::string &edge_segment_lookup_path, const std::string &edge_penalty_path, const std::string &segment_speed_path); }; +} +} + #endif // PROCESSING_CHAIN_HPP diff --git a/include/contractor/query_edge.hpp b/include/contractor/query_edge.hpp index ec7e89b68..75949c4dd 100644 --- a/include/contractor/query_edge.hpp +++ b/include/contractor/query_edge.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace contractor +{ + struct QueryEdge { NodeID source; @@ -49,4 +54,7 @@ struct QueryEdge } }; +} +} + #endif // QUERYEDGE_HPP diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index ba72581d8..37ae802c4 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -24,6 +24,11 @@ #include #include +namespace osrm +{ +namespace datastore +{ + struct OSRMLockFile { boost::filesystem::path operator()() @@ -58,10 +63,10 @@ class SharedMemory { if (m_initialized) { - SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; + util::SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; if (!boost::interprocess::xsi_shared_memory::remove(m_shmid)) { - SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; + util::SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; } } } @@ -103,14 +108,14 @@ class SharedMemory { if (ENOMEM == errno) { - SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM"; + util::SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM"; } } #endif region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(shm.get_shmid()); - SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; } } @@ -157,7 +162,7 @@ class SharedMemory bool ret = false; try { - SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; + util::SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; boost::interprocess::xsi_shared_memory xsi(boost::interprocess::open_only, key); ret = boost::interprocess::xsi_shared_memory::remove(xsi.get_shmid()); } @@ -202,10 +207,10 @@ class SharedMemory { if (m_initialized) { - SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; + util::SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; if (!boost::interprocess::shared_memory_object::remove(m_shmid)) { - SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; + util::SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; } } } @@ -242,7 +247,7 @@ class SharedMemory region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(key); - SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; } } @@ -292,7 +297,7 @@ class SharedMemory bool ret = false; try { - SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; + util::SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; ret = boost::interprocess::shared_memory_object::remove(key); } catch (const boost::interprocess::interprocess_exception &e) @@ -328,7 +333,7 @@ template class SharedMemoryFactory_tmpl { if (0 == size) { - throw osrm::exception("lock file does not exist, exiting"); + throw util::exception("lock file does not exist, exiting"); } else { @@ -340,9 +345,9 @@ template class SharedMemoryFactory_tmpl } catch (const boost::interprocess::interprocess_exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " << e.get_error_code(); - throw osrm::exception(e.what()); + throw util::exception(e.what()); } } @@ -352,4 +357,7 @@ template class SharedMemoryFactory_tmpl using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; +} +} + #endif // SHARED_MEMORY_FACTORY_HPP diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index d70eae3f8..02dbf70f0 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -57,7 +57,7 @@ template class ApiResponseGenerator // The output is tailored to the viaroute plugin. void DescribeRoute(const RouteParameters &config, const InternalRouteResult &raw_route, - osrm::json::Object &json_result); + util::json::Object &json_result); // The following functions allow access to the different parts of the Describe Route // functionality. @@ -65,20 +65,20 @@ template class ApiResponseGenerator // In the normal situation, Describe Route is the desired usecase. // generate an overview of a raw route - osrm::json::Object SummarizeRoute(const InternalRouteResult &raw_route, + util::json::Object SummarizeRoute(const InternalRouteResult &raw_route, const Segments &segment_list) const; // create an array containing all via-points/-indices used in the query - osrm::json::Array ListViaPoints(const InternalRouteResult &raw_route) const; - osrm::json::Array ListViaIndices(const Segments &segment_list) const; + util::json::Array ListViaPoints(const InternalRouteResult &raw_route) const; + util::json::Array ListViaIndices(const Segments &segment_list) const; - osrm::json::Value GetGeometry(const bool return_encoded, const Segments &segments) const; + util::json::Value GetGeometry(const bool return_encoded, const Segments &segments) const; // TODO this dedicated creation seems unnecessary? Only used for route names std::vector BuildRouteSegments(const Segments &segment_list) const; // adds checksum and locations - osrm::json::Object BuildHintData(const InternalRouteResult &raw_route) const; + util::json::Object BuildHintData(const InternalRouteResult &raw_route) const; private: // data access to translate ids back into names @@ -94,7 +94,7 @@ ApiResponseGenerator::ApiResponseGenerator(DataFacadeT *facade_) template void ApiResponseGenerator::DescribeRoute(const RouteParameters &config, const InternalRouteResult &raw_route, - osrm::json::Object &json_result) + util::json::Object &json_result) { if( not raw_route.is_valid() ){ return; @@ -129,7 +129,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con // Alternative Route Summaries are stored in an array to (down the line) allow multiple // alternatives - osrm::json::Array json_alternate_route_summary_array; + util::json::Array json_alternate_route_summary_array; json_alternate_route_summary_array.values.emplace_back( SummarizeRoute(raw_route, alternate_segment_list)); json_result.values["alternative_summaries"] = json_alternate_route_summary_array; @@ -139,14 +139,14 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con { auto alternate_geometry_string = GetGeometry(config.compression, alternate_segment_list); - osrm::json::Array json_alternate_geometries_array; + util::json::Array json_alternate_geometries_array; json_alternate_geometries_array.values.emplace_back(std::move(alternate_geometry_string)); json_result.values["alternative_geometries"] = json_alternate_geometries_array; } if (config.print_instructions) { - osrm::json::Array json_alternate_annotations_array; + util::json::Array json_alternate_annotations_array; json_alternate_annotations_array.values.emplace_back( guidance::AnnotateRoute(alternate_segment_list.Get(), facade)); json_result.values["alternative_instructions"] = json_alternate_annotations_array; @@ -157,24 +157,24 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con auto alternate_segments = BuildRouteSegments(alternate_segment_list); route_names = generate_route_names(path_segments, alternate_segments, facade); - osrm::json::Array json_alternate_names_array; - osrm::json::Array json_alternate_names; + util::json::Array json_alternate_names_array; + util::json::Array json_alternate_names; json_alternate_names.values.push_back(route_names.alternative_path_name_1); json_alternate_names.values.push_back(route_names.alternative_path_name_2); json_alternate_names_array.values.emplace_back(std::move(json_alternate_names)); json_result.values["alternative_names"] = json_alternate_names_array; - json_result.values["found_alternative"] = osrm::json::True(); + json_result.values["found_alternative"] = util::json::True(); } else { - json_result.values["found_alternative"] = osrm::json::False(); + json_result.values["found_alternative"] = util::json::False(); // generate names for the main route on its own auto path_segments = BuildRouteSegments(segment_list); std::vector alternate_segments; route_names = generate_route_names(path_segments, alternate_segments, facade); } - osrm::json::Array json_route_names; + util::json::Array json_route_names; json_route_names.values.push_back(route_names.shortest_path_name_1); json_route_names.values.push_back(route_names.shortest_path_name_2); json_result.values["route_name"] = json_route_names; @@ -183,11 +183,11 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con } template -osrm::json::Object +util::json::Object ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw_route, const Segments &segment_list) const { - osrm::json::Object json_route_summary; + util::json::Object json_route_summary; if (not raw_route.segment_end_coordinates.empty()) { const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id; @@ -201,11 +201,11 @@ ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw } template -osrm::json::Array +util::json::Array ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_route) const { - osrm::json::Array json_via_points_array; - osrm::json::Array json_first_coordinate; + util::json::Array json_via_points_array; + util::json::Array json_first_coordinate; json_first_coordinate.values.emplace_back( raw_route.segment_end_coordinates.front().source_phantom.location.lat / COORDINATE_PRECISION); @@ -216,7 +216,7 @@ ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_ for (const PhantomNodes &nodes : raw_route.segment_end_coordinates) { std::string tmp; - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.emplace_back(nodes.target_phantom.location.lat / COORDINATE_PRECISION); json_coordinate.values.emplace_back(nodes.target_phantom.location.lon / COORDINATE_PRECISION); json_via_points_array.values.emplace_back(std::move(json_coordinate)); @@ -225,17 +225,17 @@ ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_ } template -osrm::json::Array +util::json::Array ApiResponseGenerator::ListViaIndices(const Segments &segment_list) const { - osrm::json::Array via_indices; + util::json::Array via_indices; via_indices.values.insert(via_indices.values.end(), segment_list.GetViaIndices().begin(), segment_list.GetViaIndices().end()); return via_indices; } template -osrm::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const +util::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const { if (return_encoded) return PolylineFormatter().printEncodedString(segments.Get()); @@ -251,8 +251,8 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li for (const auto &segment : segment_list.Get()) { const auto current_turn = segment.turn_instruction; - if (TurnInstructionsClass::TurnIsNecessary(current_turn) and - (TurnInstruction::EnterRoundAbout != current_turn)) + if (extractor::TurnInstructionsClass::TurnIsNecessary(current_turn) and + (extractor::TurnInstruction::EnterRoundAbout != current_turn)) { detail::Segment seg = {segment.name_id, static_cast(segment.length), @@ -264,14 +264,14 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li } template -osrm::json::Object +util::json::Object ApiResponseGenerator::BuildHintData(const InternalRouteResult &raw_route) const { - osrm::json::Object json_hint_object; + util::json::Object json_hint_object; json_hint_object.values["checksum"] = facade->GetCheckSum(); - osrm::json::Array json_location_hint_array; + util::json::Array json_location_hint_array; std::string hint; - for (const auto i : osrm::irange(0, raw_route.segment_end_coordinates.size())) + for (const auto i : util::irange(0, raw_route.segment_end_coordinates.size())) { ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); json_location_hint_array.values.push_back(hint); diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index 1653309b7..ab419bf19 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -17,12 +17,19 @@ #include #include -using EdgeRange = osrm::range; +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + +using EdgeRange = util::range; template class BaseDataFacade { public: - using RTreeLeaf = EdgeBasedNode; + using RTreeLeaf = extractor::EdgeBasedNode; using EdgeData = EdgeDataT; BaseDataFacade() {} virtual ~BaseDataFacade() {} @@ -53,7 +60,7 @@ template class BaseDataFacade FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const = 0; // node and edge information access - virtual FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const = 0; + virtual util::FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const = 0; virtual bool EdgeIsCompressed(const unsigned id) const = 0; @@ -62,24 +69,24 @@ template class BaseDataFacade virtual void GetUncompressedGeometry(const unsigned id, std::vector &result_nodes) const = 0; - virtual TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const = 0; + virtual extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const = 0; - virtual TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; + virtual extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; virtual std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) = 0; @@ -96,4 +103,8 @@ template class BaseDataFacade virtual std::string GetTimestamp() const = 0; }; +} +} +} + #endif // DATAFACADE_BASE_HPP diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index 35f2e223b..ba43513da 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -22,15 +22,22 @@ #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + template class InternalDataFacade final : public BaseDataFacade { private: using super = BaseDataFacade; - using QueryGraph = StaticGraph; + using QueryGraph = util::StaticGraph; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using InternalRTree = StaticRTree::vector, false>; + using InternalRTree = util::StaticRTree::vector, false>; using InternalGeospatialQuery = GeospatialQuery; InternalDataFacade() {} @@ -40,32 +47,32 @@ template class InternalDataFacade final : public BaseDataFacad std::unique_ptr m_query_graph; std::string m_timestamp; - std::shared_ptr::vector> m_coordinate_list; - ShM::vector m_via_node_list; - ShM::vector m_name_ID_list; - ShM::vector m_turn_instruction_list; - ShM::vector m_travel_mode_list; - ShM::vector m_names_char_list; - ShM::vector m_edge_is_compressed; - ShM::vector m_geometry_indices; - ShM::vector m_geometry_list; - ShM::vector m_is_core_node; + std::shared_ptr::vector> m_coordinate_list; + util::ShM::vector m_via_node_list; + util::ShM::vector m_name_ID_list; + util::ShM::vector m_turn_instruction_list; + util::ShM::vector m_travel_mode_list; + util::ShM::vector m_names_char_list; + util::ShM::vector m_edge_is_compressed; + util::ShM::vector m_geometry_indices; + util::ShM::vector m_geometry_list; + util::ShM::vector m_is_core_node; boost::thread_specific_ptr m_static_rtree; boost::thread_specific_ptr m_geospatial_query; boost::filesystem::path ram_index_path; boost::filesystem::path file_index_path; - RangeTable<16, false> m_name_table; + util::RangeTable<16, false> m_name_table; void LoadTimestamp(const boost::filesystem::path ×tamp_path) { if (boost::filesystem::exists(timestamp_path)) { - SimpleLogger().Write() << "Loading Timestamp"; + util::SimpleLogger().Write() << "Loading Timestamp"; boost::filesystem::ifstream timestamp_stream(timestamp_path); if (!timestamp_stream) { - SimpleLogger().Write(logWARNING) << timestamp_path << " not found"; + util::SimpleLogger().Write(logWARNING) << timestamp_path << " not found"; } getline(timestamp_stream, m_timestamp); timestamp_stream.close(); @@ -82,22 +89,22 @@ template class InternalDataFacade final : public BaseDataFacad void LoadGraph(const boost::filesystem::path &hsgr_path) { - typename ShM::vector node_list; - typename ShM::vector edge_list; + typename util::ShM::vector node_list; + typename util::ShM::vector edge_list; - SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); + util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); // BOOST_ASSERT_MSG(0 != edge_list.size(), "edge list empty"); - SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() + util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() << " edges"; m_query_graph = std::unique_ptr(new QueryGraph(node_list, edge_list)); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - SimpleLogger().Write() << "Data checksum is " << m_check_sum; + util::SimpleLogger().Write() << "Data checksum is " << m_check_sum; } void LoadNodeAndEdgeInformation(const boost::filesystem::path &nodes_file, @@ -105,15 +112,15 @@ template class InternalDataFacade final : public BaseDataFacad { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); - QueryNode current_node; + extractor::QueryNode current_node; unsigned number_of_coordinates = 0; nodes_input_stream.read((char *)&number_of_coordinates, sizeof(unsigned)); m_coordinate_list = - std::make_shared>(number_of_coordinates); + std::make_shared>(number_of_coordinates); for (unsigned i = 0; i < number_of_coordinates; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); - m_coordinate_list->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); + m_coordinate_list->at(i) = util::FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lon) >> 30) == 0); } @@ -130,10 +137,10 @@ template class InternalDataFacade final : public BaseDataFacad unsigned compressed = 0; - OriginalEdgeData current_edge_data; + extractor::OriginalEdgeData current_edge_data; for (unsigned i = 0; i < number_of_edges; ++i) { - edges_input_stream.read((char *)&(current_edge_data), sizeof(OriginalEdgeData)); + edges_input_stream.read((char *)&(current_edge_data), sizeof(extractor::OriginalEdgeData)); m_via_node_list[i] = current_edge_data.via_node; m_name_ID_list[i] = current_edge_data.name_id; m_turn_instruction_list[i] = current_edge_data.turn_instruction; @@ -220,7 +227,7 @@ template class InternalDataFacade final : public BaseDataFacad name_stream.read((char *)&m_names_char_list[0], number_of_chars * sizeof(char)); if (0 == m_names_char_list.size()) { - SimpleLogger().Write(logWARNING) << "list of street names is empty"; + util::SimpleLogger().Write(logWARNING) << "list of street names is empty"; } name_stream.close(); } @@ -242,29 +249,29 @@ template class InternalDataFacade final : public BaseDataFacad { const auto it = server_paths.find(path); if (it == end_it || !boost::filesystem::is_regular_file(it->second)) - throw osrm::exception("no valid " + path + " file given in ini file"); + throw util::exception("no valid " + path + " file given in ini file"); return it->second; }; ram_index_path = file_for("ramindex"); file_index_path = file_for("fileindex"); - SimpleLogger().Write() << "loading graph data"; + util::SimpleLogger().Write() << "loading graph data"; LoadGraph(file_for("hsgrdata")); - SimpleLogger().Write() << "loading edge information"; + util::SimpleLogger().Write() << "loading edge information"; LoadNodeAndEdgeInformation(file_for("nodesdata"), file_for("edgesdata")); - SimpleLogger().Write() << "loading core information"; + util::SimpleLogger().Write() << "loading core information"; LoadCoreInformation(file_for("coredata")); - SimpleLogger().Write() << "loading geometries"; + util::SimpleLogger().Write() << "loading geometries"; LoadGeometries(file_for("geometries")); - SimpleLogger().Write() << "loading timestamp"; + util::SimpleLogger().Write() << "loading timestamp"; LoadTimestamp(file_for("timestamp")); - SimpleLogger().Write() << "loading street names"; + util::SimpleLogger().Write() << "loading street names"; LoadStreetNames(file_for("namesdata")); } @@ -312,7 +319,7 @@ template class InternalDataFacade final : public BaseDataFacad } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const override final + util::FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const override final { return m_coordinate_list->at(id); }; @@ -322,18 +329,18 @@ template class InternalDataFacade final : public BaseDataFacad return m_edge_is_compressed.at(id); } - TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final + extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final { return m_turn_instruction_list.at(id); } - TravelMode GetTravelModeForEdgeID(const unsigned id) const override final + extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const override final { return m_travel_mode_list.at(id); } std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -349,7 +356,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -365,7 +372,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { @@ -438,4 +445,8 @@ template class InternalDataFacade final : public BaseDataFacad std::string GetTimestamp() const override final { return m_timestamp; } }; +} +} +} + #endif // INTERNAL_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_barriers.hpp b/include/engine/datafacade/shared_barriers.hpp index 3825580bc..4eb7d5371 100644 --- a/include/engine/datafacade/shared_barriers.hpp +++ b/include/engine/datafacade/shared_barriers.hpp @@ -4,6 +4,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + struct SharedBarriers { @@ -30,4 +37,8 @@ struct SharedBarriers int number_of_queries; }; +} +} +} + #endif // SHARED_BARRIERS_HPP diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 91d917f96..536cc230e 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -19,19 +19,26 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + template class SharedDataFacade final : public BaseDataFacade { private: using EdgeData = EdgeDataT; using super = BaseDataFacade; - using QueryGraph = StaticGraph; - using GraphNode = typename StaticGraph::NodeArrayEntry; - using GraphEdge = typename StaticGraph::EdgeArrayEntry; - using NameIndexBlock = typename RangeTable<16, true>::BlockT; + using QueryGraph = util::StaticGraph; + using GraphNode = typename QueryGraph::NodeArrayEntry; + using GraphEdge = typename QueryGraph::EdgeArrayEntry; + using NameIndexBlock = typename util::RangeTable<16, true>::BlockT; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using SharedRTree = StaticRTree::vector, true>; + using SharedRTree = util::StaticRTree::vector, true>; using SharedGeospatialQuery = GeospatialQuery; using TimeStampedRTreePair = std::pair>; using RTreeNode = typename SharedRTree::TreeNode; @@ -46,33 +53,33 @@ template class SharedDataFacade final : public BaseDataFacade< unsigned m_check_sum; std::unique_ptr m_query_graph; - std::unique_ptr m_layout_memory; - std::unique_ptr m_large_memory; + std::unique_ptr m_layout_memory; + std::unique_ptr m_large_memory; std::string m_timestamp; - std::shared_ptr::vector> m_coordinate_list; - ShM::vector m_via_node_list; - ShM::vector m_name_ID_list; - ShM::vector m_turn_instruction_list; - ShM::vector m_travel_mode_list; - ShM::vector m_names_char_list; - ShM::vector m_name_begin_indices; - ShM::vector m_edge_is_compressed; - ShM::vector m_geometry_indices; - ShM::vector m_geometry_list; - ShM::vector m_is_core_node; + std::shared_ptr::vector> m_coordinate_list; + util::ShM::vector m_via_node_list; + util::ShM::vector m_name_ID_list; + util::ShM::vector m_turn_instruction_list; + util::ShM::vector m_travel_mode_list; + util::ShM::vector m_names_char_list; + util::ShM::vector m_name_begin_indices; + util::ShM::vector m_edge_is_compressed; + util::ShM::vector m_geometry_indices; + util::ShM::vector m_geometry_list; + util::ShM::vector m_is_core_node; boost::thread_specific_ptr>> m_static_rtree; boost::thread_specific_ptr m_geospatial_query; boost::filesystem::path file_index_path; - std::shared_ptr> m_name_table; + std::shared_ptr> m_name_table; void LoadChecksum() { m_check_sum = *data_layout->GetBlockPtr(shared_memory, SharedDataLayout::HSGR_CHECKSUM); - SimpleLogger().Write() << "set checksum: " << m_check_sum; + util::SimpleLogger().Write() << "set checksum: " << m_check_sum; } void LoadTimestamp() @@ -93,7 +100,7 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->GetBlockPtr(shared_memory, SharedDataLayout::R_SEARCH_TREE); m_static_rtree.reset(new TimeStampedRTreePair( CURRENT_TIMESTAMP, - osrm::make_unique( + util::make_unique( tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE], file_index_path, m_coordinate_list))); m_geospatial_query.reset( @@ -108,9 +115,9 @@ template class SharedDataFacade final : public BaseDataFacade< GraphEdge *graph_edges_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GRAPH_EDGE_LIST); - typename ShM::vector node_list( + typename util::ShM::vector node_list( graph_nodes_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_NODE_LIST]); - typename ShM::vector edge_list( + typename util::ShM::vector edge_list( graph_edges_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_EDGE_LIST]); m_query_graph.reset(new QueryGraph(node_list, edge_list)); } @@ -118,27 +125,27 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr( + util::FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::COORDINATE_LIST); - m_coordinate_list = osrm::make_unique::vector>( + m_coordinate_list = util::make_unique::vector>( coordinate_list_ptr, data_layout->num_entries[SharedDataLayout::COORDINATE_LIST]); - TravelMode *travel_mode_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TRAVEL_MODE); - typename ShM::vector travel_mode_list( + extractor::TravelMode *travel_mode_list_ptr = + data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TRAVEL_MODE); + typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); - TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( + extractor::TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::TURN_INSTRUCTION); - typename ShM::vector turn_instruction_list( + typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, data_layout->num_entries[SharedDataLayout::TURN_INSTRUCTION]); m_turn_instruction_list.swap(turn_instruction_list); unsigned *name_id_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_ID_LIST); - typename ShM::vector name_id_list( + typename util::ShM::vector name_id_list( name_id_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_ID_LIST]); m_name_ID_list.swap(name_id_list); } @@ -147,7 +154,7 @@ template class SharedDataFacade final : public BaseDataFacade< { NodeID *via_node_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::VIA_NODE_LIST); - typename ShM::vector via_node_list( + typename util::ShM::vector via_node_list( via_node_list_ptr, data_layout->num_entries[SharedDataLayout::VIA_NODE_LIST]); m_via_node_list.swap(via_node_list); } @@ -158,16 +165,16 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_OFFSETS); NameIndexBlock *blocks_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_BLOCKS); - typename ShM::vector name_offsets( + typename util::ShM::vector name_offsets( offsets_ptr, data_layout->num_entries[SharedDataLayout::NAME_OFFSETS]); - typename ShM::vector name_blocks( + typename util::ShM::vector name_blocks( blocks_ptr, data_layout->num_entries[SharedDataLayout::NAME_BLOCKS]); char *names_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_CHAR_LIST); - typename ShM::vector names_char_list( + typename util::ShM::vector names_char_list( names_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_CHAR_LIST]); - m_name_table = osrm::make_unique>( + m_name_table = util::make_unique>( name_offsets, name_blocks, static_cast(names_char_list.size())); m_names_char_list.swap(names_char_list); @@ -182,7 +189,7 @@ template class SharedDataFacade final : public BaseDataFacade< unsigned *core_marker_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::CORE_MARKER); - typename ShM::vector is_core_node( + typename util::ShM::vector is_core_node( core_marker_ptr, data_layout->num_entries[SharedDataLayout::CORE_MARKER]); m_is_core_node.swap(is_core_node); } @@ -191,20 +198,20 @@ template class SharedDataFacade final : public BaseDataFacade< { unsigned *geometries_compressed_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::GEOMETRIES_INDICATORS); - typename ShM::vector edge_is_compressed( + typename util::ShM::vector edge_is_compressed( geometries_compressed_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDICATORS]); m_edge_is_compressed.swap(edge_is_compressed); unsigned *geometries_index_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_INDEX); - typename ShM::vector geometry_begin_indices( + typename util::ShM::vector geometry_begin_indices( geometries_index_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDEX]); m_geometry_indices.swap(geometry_begin_indices); unsigned *geometries_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_LIST); - typename ShM::vector geometry_list( + typename util::ShM::vector geometry_list( geometries_list_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_LIST]); m_geometry_list.swap(geometry_list); } @@ -214,7 +221,7 @@ template class SharedDataFacade final : public BaseDataFacade< SharedDataFacade() { - data_timestamp_ptr = (SharedDataTimestamp *)SharedMemoryFactory::Get( + data_timestamp_ptr = (SharedDataTimestamp *)datastore::SharedMemoryFactory::Get( CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false) ->Ptr(); CURRENT_LAYOUT = LAYOUT_NONE; @@ -232,18 +239,18 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) { // release the previous shared memory segments - SharedMemory::Remove(CURRENT_LAYOUT); - SharedMemory::Remove(CURRENT_DATA); + datastore::SharedMemory::Remove(CURRENT_LAYOUT); + datastore::SharedMemory::Remove(CURRENT_DATA); CURRENT_LAYOUT = data_timestamp_ptr->layout; CURRENT_DATA = data_timestamp_ptr->data; CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; - m_layout_memory.reset(SharedMemoryFactory::Get(CURRENT_LAYOUT)); + m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); data_layout = (SharedDataLayout *)(m_layout_memory->Ptr()); - m_large_memory.reset(SharedMemoryFactory::Get(CURRENT_DATA)); + m_large_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_DATA)); shared_memory = (char *)(m_large_memory->Ptr()); const char *file_index_ptr = @@ -251,8 +258,8 @@ template class SharedDataFacade final : public BaseDataFacade< file_index_path = boost::filesystem::path(file_index_ptr); if (!boost::filesystem::exists(file_index_path)) { - SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string(); - throw osrm::exception("Could not load leaf index file. " + util::SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string(); + throw util::exception("Could not load leaf index file. " "Is any data loaded into shared memory?"); } @@ -267,12 +274,12 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->PrintInformation(); - SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); + util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { if (!GetCoordinateOfNode(i).IsValid()) { - SimpleLogger().Write() << "coordinate " << i << " not valid"; + util::SimpleLogger().Write() << "coordinate " << i << " not valid"; } } } @@ -322,7 +329,7 @@ template class SharedDataFacade final : public BaseDataFacade< } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const override final + util::FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const override final { return m_coordinate_list->at(id); }; @@ -348,18 +355,18 @@ template class SharedDataFacade final : public BaseDataFacade< return m_via_node_list.at(id); } - TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final + extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final { return m_turn_instruction_list.at(id); } - TravelMode GetTravelModeForEdgeID(const unsigned id) const override final + extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const override final { return m_travel_mode_list.at(id); } std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -375,7 +382,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -391,7 +398,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { @@ -446,4 +453,8 @@ template class SharedDataFacade final : public BaseDataFacade< std::string GetTimestamp() const override final { return m_timestamp; } }; +} +} +} + #endif // SHARED_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index 187d9b6cb..b576008cc 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -8,6 +8,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + namespace { // Added at the start and end of each block as sanity check @@ -46,41 +53,41 @@ struct SharedDataLayout void PrintInformation() const { - SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " + util::SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " << ": " << GetBlockSize(NAME_OFFSETS); - SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " + util::SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " << ": " << GetBlockSize(NAME_BLOCKS); - SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " + util::SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " << ": " << GetBlockSize(NAME_CHAR_LIST); - SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " + util::SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " << ": " << GetBlockSize(NAME_ID_LIST); - SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " + util::SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " << ": " << GetBlockSize(VIA_NODE_LIST); - SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " + util::SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " << ": " << GetBlockSize(GRAPH_NODE_LIST); - SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " + util::SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " << ": " << GetBlockSize(GRAPH_EDGE_LIST); - SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " + util::SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " << ": " << GetBlockSize(COORDINATE_LIST); - SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " + util::SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " << ": " << GetBlockSize(TURN_INSTRUCTION); - SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " + util::SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " << ": " << GetBlockSize(TRAVEL_MODE); - SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " + util::SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " << ": " << GetBlockSize(R_SEARCH_TREE); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " << ": " << GetBlockSize(GEOMETRIES_INDEX); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " << ": " << GetBlockSize(GEOMETRIES_LIST); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" << ": " << GetBlockSize(GEOMETRIES_INDICATORS); - SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " + util::SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " << ": " << GetBlockSize(HSGR_CHECKSUM); - SimpleLogger().Write(logDEBUG) << "TIMESTAMP " + util::SimpleLogger().Write(logDEBUG) << "TIMESTAMP " << ": " << GetBlockSize(TIMESTAMP); - SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " + util::SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " << ": " << GetBlockSize(FILE_INDEX_PATH); - SimpleLogger().Write(logDEBUG) << "CORE_MARKER " + util::SimpleLogger().Write(logDEBUG) << "CORE_MARKER " << ": " << GetBlockSize(CORE_MARKER); } @@ -135,11 +142,11 @@ struct SharedDataLayout bool end_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), end_canary_ptr); if (!start_canary_alive) { - throw osrm::exception("Start canary of block corrupted."); + throw util::exception("Start canary of block corrupted."); } if (!end_canary_alive) { - throw osrm::exception("End canary of block corrupted."); + throw util::exception("End canary of block corrupted."); } } @@ -165,4 +172,8 @@ struct SharedDataTimestamp unsigned timestamp; }; +} +} +} + #endif /* SHARED_DATA_TYPE_HPP */ diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index dda4ca1b7..c7e8dd0b2 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + /* This class object computes the bitvector of indicating generalized input * points according to the (Ramer-)Douglas-Peucker algorithm. * @@ -51,4 +56,7 @@ class DouglasPeucker void Run(std::vector &input_geometry, const unsigned zoom_level); }; +} +} + #endif /* DOUGLAS_PEUCKER_HPP_ */ diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index b572b8f79..efd8c2603 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + // Implements complex queries on top of an RTree and builds PhantomNodes from it. // // Only holds a weak reference on the RTree! @@ -30,7 +35,7 @@ template class GeospatialQuery // Returns nearest PhantomNodes in the given bearing range within max_distance. // Does not filter by small/big component! std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const double max_distance, const int bearing = 0, const int bearing_range = 180) @@ -52,7 +57,7 @@ template class GeospatialQuery // Returns max_results nearest PhantomNodes in the given bearing range. // Does not filter by small/big component! std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) @@ -73,7 +78,7 @@ template class GeospatialQuery // Returns the nearest phantom node. If this phantom node is not from a big component // a second phantom node is return that is the nearest coordinate in a big component. std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) { @@ -117,7 +122,7 @@ template class GeospatialQuery private: std::vector - MakePhantomNodes(const FixedPointCoordinate &input_coordinate, + MakePhantomNodes(const util::FixedPointCoordinate &input_coordinate, const std::vector &results) const { std::vector distance_and_phantoms(results.size()); @@ -129,12 +134,12 @@ template class GeospatialQuery return distance_and_phantoms; } - PhantomNodeWithDistance MakePhantomNode(const FixedPointCoordinate &input_coordinate, + PhantomNodeWithDistance MakePhantomNode(const util::FixedPointCoordinate &input_coordinate, const EdgeData &data) const { - FixedPointCoordinate point_on_segment; + util::FixedPointCoordinate point_on_segment; double ratio; - const auto current_perpendicular_distance = coordinate_calculation::perpendicularDistance( + const auto current_perpendicular_distance = util::coordinate_calculation::perpendicularDistance( coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, ratio); @@ -159,18 +164,18 @@ template class GeospatialQuery const int filter_bearing_range) { const double forward_edge_bearing = - coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); + util::coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); const double backward_edge_bearing = (forward_edge_bearing + 180) > 360 ? (forward_edge_bearing - 180) : (forward_edge_bearing + 180); const bool forward_bearing_valid = - bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, + util::bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, filter_bearing_range) && segment.forward_edge_based_node_id != SPECIAL_NODEID; const bool backward_bearing_valid = - bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, + util::bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, filter_bearing_range) && segment.reverse_edge_based_node_id != SPECIAL_NODEID; return std::make_pair(forward_bearing_valid, backward_bearing_valid); @@ -180,4 +185,7 @@ template class GeospatialQuery const std::shared_ptr coordinates; }; +} +} + #endif diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index d034df6ee..ff42b77e6 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -9,6 +9,7 @@ #include "engine/segment_information.hpp" #include "util/integer_range.hpp" #include "util/coordinate_calculation.hpp" +#include "util/container.hpp" #include "extractor/turn_instructions.hpp" #include @@ -124,7 +125,7 @@ void SegmentList::InitRoute(const PhantomNode &node, const bool tra const auto travel_mode = (traversed_in_reverse ? node.backward_travel_mode : node.forward_travel_mode); - AppendSegment(node.location, PathData(0, node.name_id, TurnInstruction::HeadOn, + AppendSegment(node.location, PathData(0, node.name_id, extractor::TurnInstruction::HeadOn, segment_duration, travel_mode)); } @@ -142,10 +143,10 @@ void SegmentList::AddLeg(const std::vector &leg_data, const EdgeWeight segment_duration = (traversed_in_reverse ? target_node.reverse_weight : target_node.forward_weight); - const TravelMode travel_mode = + const extractor::TravelMode travel_mode = (traversed_in_reverse ? target_node.backward_travel_mode : target_node.forward_travel_mode); segments.emplace_back(target_node.location, target_node.name_id, segment_duration, 0.f, - is_via_leg ? TurnInstruction::ReachViaLocation : TurnInstruction::NoTurn, + is_via_leg ? extractor::TurnInstruction::ReachViaLocation : extractor::TurnInstruction::NoTurn, true, true, travel_mode); } @@ -187,12 +188,12 @@ void SegmentList::AppendSegment(const FixedPointCoordinate &coordin } // make sure mode changes are announced, even when there otherwise is no turn - const auto getTurn = [](const PathData &path_point, const TravelMode previous_mode) + const auto getTurn = [](const PathData &path_point, const extractor::TravelMode previous_mode) { - if (TurnInstruction::NoTurn == path_point.turn_instruction and + if (extractor::TurnInstruction::NoTurn == path_point.turn_instruction and previous_mode != path_point.travel_mode and path_point.segment_duration > 0) { - return TurnInstruction::GoStraight; + return extractor::TurnInstruction::GoStraight; } return path_point.turn_instruction; }; @@ -215,11 +216,11 @@ void SegmentList::Finalize(const bool extract_alternative, return; segments[0].length = 0.f; - for (const auto i : osrm::irange(1, segments.size())) + for (const auto i : util::irange(1, segments.size())) { // move down names by one, q&d hack segments[i - 1].name_id = segments[i].name_id; - segments[i].length = coordinate_calculation::greatCircleDistance(segments[i - 1].location, + segments[i].length = util::coordinate_calculation::greatCircleDistance(segments[i - 1].location, segments[i].location); } @@ -229,7 +230,7 @@ void SegmentList::Finalize(const bool extract_alternative, double path_length = 0; - for (const auto i : osrm::irange(1, segments.size())) + for (const auto i : util::irange(1, segments.size())) { path_length += segments[i].length; segment_length += segments[i].length; @@ -237,7 +238,7 @@ void SegmentList::Finalize(const bool extract_alternative, segments[segment_start_index].length = segment_length; segments[segment_start_index].duration = segment_duration; - if (TurnInstruction::NoTurn != segments[i].turn_instruction) + if (extractor::TurnInstruction::NoTurn != segments[i].turn_instruction) { BOOST_ASSERT(segments[i].necessary); segment_length = 0; @@ -257,14 +258,14 @@ void SegmentList::Finalize(const bool extract_alternative, { segments.pop_back(); segments.back().necessary = true; - segments.back().turn_instruction = TurnInstruction::NoTurn; + segments.back().turn_instruction = extractor::TurnInstruction::NoTurn; } if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.front().length && !(segments.begin() + 1)->is_via_location) { segments.erase(segments.begin()); - segments.front().turn_instruction = TurnInstruction::HeadOn; + segments.front().turn_instruction = extractor::TurnInstruction::HeadOn; segments.front().necessary = true; } @@ -287,9 +288,9 @@ void SegmentList::Finalize(const bool extract_alternative, via_indices.push_back(necessary_segments); const double post_turn_bearing = - coordinate_calculation::bearing(first.location, second.location); + util::coordinate_calculation::bearing(first.location, second.location); const double pre_turn_bearing = - coordinate_calculation::bearing(second.location, first.location); + util::coordinate_calculation::bearing(second.location, first.location); first.post_turn_bearing = static_cast(post_turn_bearing * 10); first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); @@ -297,7 +298,7 @@ void SegmentList::Finalize(const bool extract_alternative, }; // calculate which segments are necessary and update segments for bearings - osrm::for_each_pair(segments, markNecessarySegments); + util::for_each_pair(segments, markNecessarySegments); via_indices.push_back(necessary_segments); BOOST_ASSERT(via_indices.size() >= 2); diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index 97329a8e9..5a13428ba 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -22,10 +22,10 @@ namespace engine namespace guidance { template< typename DataFacadeT > -inline osrm::json::Array +inline util::json::Array AnnotateRoute(const std::vector &route_segments, DataFacadeT* facade) { - osrm::json::Array json_instruction_array; + util::json::Array json_instruction_array; if( route_segments.empty() ) return json_instruction_array; // Segment information has following format: @@ -45,11 +45,11 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT //Generate annotations for every segment for (const SegmentInformation &segment : route_segments) { - osrm::json::Array json_instruction_row; - TurnInstruction current_instruction = segment.turn_instruction; - if (TurnInstructionsClass::TurnIsNecessary(current_instruction)) + util::json::Array json_instruction_row; + extractor::TurnInstruction current_instruction = segment.turn_instruction; + if (extractor::TurnInstructionsClass::TurnIsNecessary(current_instruction)) { - if (TurnInstruction::EnterRoundAbout == current_instruction) + if (extractor::TurnInstruction::EnterRoundAbout == current_instruction) { round_about.name_id = segment.name_id; round_about.start_index = necessary_segments_running_index; @@ -57,10 +57,10 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT else { std::string current_turn_instruction; - if (TurnInstruction::LeaveRoundAbout == current_instruction) + if (extractor::TurnInstruction::LeaveRoundAbout == current_instruction) { temp_instruction = - std::to_string(cast::enum_to_underlying(TurnInstruction::EnterRoundAbout)); + std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::EnterRoundAbout)); current_turn_instruction += temp_instruction; current_turn_instruction += "-"; temp_instruction = std::to_string(round_about.leave_at_exit + 1); @@ -70,7 +70,7 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT else { temp_instruction = - std::to_string(cast::enum_to_underlying(current_instruction)); + std::to_string(util::cast::enum_to_underlying(current_instruction)); current_turn_instruction += temp_instruction; } json_instruction_row.values.emplace_back(std::move(current_turn_instruction)); @@ -84,7 +84,7 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT // post turn bearing const double post_turn_bearing_value = (segment.post_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(post_turn_bearing_value)); + json_instruction_row.values.push_back(util::bearing::get(post_turn_bearing_value)); json_instruction_row.values.push_back( static_cast(std::round(post_turn_bearing_value))); @@ -92,14 +92,14 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT // pre turn bearing const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(pre_turn_bearing_value)); + json_instruction_row.values.push_back(util::bearing::get(pre_turn_bearing_value)); json_instruction_row.values.push_back( static_cast(std::round(pre_turn_bearing_value))); json_instruction_array.values.push_back(json_instruction_row); } } - else if (TurnInstruction::StayOnRoundAbout == current_instruction) + else if (extractor::TurnInstruction::StayOnRoundAbout == current_instruction) { ++round_about.leave_at_exit; } @@ -109,18 +109,18 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT } } - osrm::json::Array json_last_instruction_row; + util::json::Array json_last_instruction_row; temp_instruction = - std::to_string(cast::enum_to_underlying(TurnInstruction::ReachedYourDestination)); + std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::ReachedYourDestination)); json_last_instruction_row.values.emplace_back( std::move(temp_instruction)); json_last_instruction_row.values.push_back(""); json_last_instruction_row.values.push_back(0); json_last_instruction_row.values.push_back(necessary_segments_running_index - 1); json_last_instruction_row.values.push_back(0); json_last_instruction_row.values.push_back("0m"); - json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); - json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); json_instruction_array.values.emplace_back(std::move(json_last_instruction_row)); diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index 0ff802fe8..d4536b405 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -10,19 +10,24 @@ #include +namespace osrm +{ +namespace engine +{ + struct PathData { PathData() : node(SPECIAL_NODEID), name_id(INVALID_EDGE_WEIGHT), segment_duration(INVALID_EDGE_WEIGHT), - turn_instruction(TurnInstruction::NoTurn), travel_mode(TRAVEL_MODE_INACCESSIBLE) + turn_instruction(extractor::TurnInstruction::NoTurn), travel_mode(TRAVEL_MODE_INACCESSIBLE) { } PathData(NodeID node, unsigned name_id, - TurnInstruction turn_instruction, + extractor::TurnInstruction turn_instruction, EdgeWeight segment_duration, - TravelMode travel_mode) + extractor::TravelMode travel_mode) : node(node), name_id(name_id), segment_duration(segment_duration), turn_instruction(turn_instruction), travel_mode(travel_mode) { @@ -30,8 +35,8 @@ struct PathData NodeID node; unsigned name_id; EdgeWeight segment_duration; - TurnInstruction turn_instruction; - TravelMode travel_mode : 4; + extractor::TurnInstruction turn_instruction; + extractor::TravelMode travel_mode : 4; }; struct InternalRouteResult @@ -61,4 +66,7 @@ struct InternalRouteResult } }; +} +} + #endif // RAW_ROUTE_DATA_H diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index 3fe0e5a8d..af2c60b29 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -6,6 +6,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace map_matching +{ + struct NormalDistribution { NormalDistribution(const double mean, const double standard_deviation) @@ -88,4 +95,8 @@ class BayesClassifier double negative_apriori_probability; }; +} +} +} + #endif // BAYES_CLASSIFIER_HPP diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index ef91fca09..f7528d61a 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -12,14 +12,15 @@ namespace osrm { -namespace matching +namespace engine { +namespace map_matching +{ + static const double log_2_pi = std::log(2. * M_PI); static const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits::infinity(); static const double MINIMAL_LOG_PROB = std::numeric_limits::lowest(); static const std::size_t INVALID_STATE = std::numeric_limits::max(); -} // namespace matching -} // namespace osrm // closures to precompute log -> only simple floating point operations struct EmissionLogProbability @@ -33,7 +34,7 @@ struct EmissionLogProbability double operator()(const double distance) const { - return -0.5 * (osrm::matching::log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - + return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - log_sigma_z; } }; @@ -70,7 +71,7 @@ template struct HiddenMarkovModel suspicious.resize(candidates_list.size()); pruned.resize(candidates_list.size()); breakage.resize(candidates_list.size()); - for (const auto i : osrm::irange(0u, candidates_list.size())) + for (const auto i : util::irange(0u, candidates_list.size())) { const auto &num_candidates = candidates_list[i].size(); // add empty vectors @@ -92,9 +93,9 @@ template struct HiddenMarkovModel BOOST_ASSERT(viterbi.size() == parents.size() && parents.size() == path_lengths.size() && path_lengths.size() == pruned.size() && pruned.size() == breakage.size()); - for (const auto t : osrm::irange(initial_timestamp, viterbi.size())) + for (const auto t : util::irange(initial_timestamp, viterbi.size())) { - std::fill(viterbi[t].begin(), viterbi[t].end(), osrm::matching::IMPOSSIBLE_LOG_PROB); + std::fill(viterbi[t].begin(), viterbi[t].end(), IMPOSSIBLE_LOG_PROB); std::fill(parents[t].begin(), parents[t].end(), std::make_pair(0u, 0u)); std::fill(path_lengths[t].begin(), path_lengths[t].end(), 0); std::fill(suspicious[t].begin(), suspicious[t].end(), true); @@ -110,13 +111,13 @@ template struct HiddenMarkovModel { BOOST_ASSERT(initial_timestamp < num_points); - for (const auto s : osrm::irange(0u, viterbi[initial_timestamp].size())) + for (const auto s : util::irange(0u, viterbi[initial_timestamp].size())) { viterbi[initial_timestamp][s] = emission_log_probability(candidates_list[initial_timestamp][s].distance); parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s); pruned[initial_timestamp][s] = - viterbi[initial_timestamp][s] < osrm::matching::MINIMAL_LOG_PROB; + viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB; suspicious[initial_timestamp][s] = false; breakage[initial_timestamp] = @@ -128,7 +129,7 @@ template struct HiddenMarkovModel if (initial_timestamp >= num_points) { - return osrm::matching::INVALID_STATE; + return INVALID_STATE; } BOOST_ASSERT(initial_timestamp > 0); @@ -140,4 +141,8 @@ template struct HiddenMarkovModel } }; +} +} +} + #endif // HIDDEN_MARKOV_MODEL diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index 546d21003..b97dbc509 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct ObjectEncoder { using base64_t = boost::archive::iterators::base64_from_binary< @@ -59,4 +64,7 @@ struct ObjectEncoder } }; +} +} + #endif /* OBJECT_ENCODER_HPP */ diff --git a/include/engine/osrm_impl.hpp b/include/engine/osrm_impl.hpp index 20301efff..c37135102 100644 --- a/include/engine/osrm_impl.hpp +++ b/include/engine/osrm_impl.hpp @@ -1,9 +1,6 @@ #ifndef OSRM_IMPL_HPP #define OSRM_IMPL_HPP -class BasePlugin; -struct RouteParameters; - #include "contractor/query_edge.hpp" #include "osrm/json_container.hpp" @@ -14,31 +11,55 @@ struct RouteParameters; #include #include +namespace osrm +{ + +namespace util +{ +namespace json +{ +struct Object; +} +} + +namespace engine +{ +struct RouteParameters; +namespace plugins +{ +class BasePlugin; +} + +namespace datafacade +{ struct SharedBarriers; template class BaseDataFacade; +} class OSRM::OSRM_impl final { private: - using PluginMap = std::unordered_map>; + using PluginMap = std::unordered_map>; public: OSRM_impl(LibOSRMConfig &lib_config); OSRM_impl(const OSRM_impl &) = delete; - int RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result); + int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); private: - void RegisterPlugin(BasePlugin *plugin); + void RegisterPlugin(plugins::BasePlugin *plugin); PluginMap plugin_map; // will only be initialized if shared memory is used - std::unique_ptr barrier; + std::unique_ptr barrier; // base class pointer to the objects - BaseDataFacade *query_data_facade; + datafacade::BaseDataFacade *query_data_facade; // decrease number of concurrent queries void decrease_concurrent_query_count(); // increase number of concurrent queries void increase_concurrent_query_count(); }; +} +} #endif // OSRM_IMPL_HPP diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 17dd6d19a..585d2edcd 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct PhantomNode { PhantomNode(NodeID forward_node_id, @@ -22,14 +27,14 @@ struct PhantomNode unsigned packed_geometry_id, bool is_tiny_component, unsigned component_id, - FixedPointCoordinate &location, + util::FixedPointCoordinate &location, unsigned short fwd_segment_position, - TravelMode forward_travel_mode, - TravelMode backward_travel_mode); + extractor::TravelMode forward_travel_mode, + extractor::TravelMode backward_travel_mode); PhantomNode(); - template PhantomNode(const OtherT &other, const FixedPointCoordinate &foot_point) + template PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) { forward_node_id = other.forward_edge_based_node_id; reverse_node_id = other.reverse_edge_based_node_id; @@ -70,12 +75,12 @@ struct PhantomNode #ifndef _MSC_VER static_assert(sizeof(ComponentType) == 4, "ComponentType needs to 4 bytes big"); #endif - FixedPointCoordinate location; + util::FixedPointCoordinate location; unsigned short fwd_segment_position; // note 4 bits would suffice for each, // but the saved byte would be padding anyway - TravelMode forward_travel_mode; - TravelMode backward_travel_mode; + extractor::TravelMode forward_travel_mode; + extractor::TravelMode backward_travel_mode; int GetForwardWeightPlusOffset() const; @@ -133,4 +138,7 @@ inline std::ostream &operator<<(std::ostream &out, const PhantomNode &pn) return out; } +} +} + #endif // PHANTOM_NODES_H diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 11151ae4c..d72253909 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -16,6 +16,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class DistanceTablePlugin final : public BasePlugin { private: @@ -27,7 +34,7 @@ template class DistanceTablePlugin final : public BasePlugin : max_locations_distance_table(max_locations_distance_table), descriptor_string("table"), facade(facade) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } virtual ~DistanceTablePlugin() {} @@ -35,7 +42,7 @@ template class DistanceTablePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (!check_all_coordinates(route_parameters.coordinates)) { @@ -82,7 +89,7 @@ template class DistanceTablePlugin final : public BasePlugin std::vector phantom_node_target_vector(number_of_destination); auto phantom_node_source_out_iter = phantom_node_source_vector.begin(); auto phantom_node_target_out_iter = phantom_node_target_vector.begin(); - for (const auto i : osrm::irange(0u, route_parameters.coordinates.size())) + for (const auto i : util::irange(0u, route_parameters.coordinates.size())) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) @@ -176,10 +183,10 @@ template class DistanceTablePlugin final : public BasePlugin return Status::EmptyResult; } - osrm::json::Array matrix_json_array; - for (const auto row : osrm::irange(0, number_of_sources)) + util::json::Array matrix_json_array; + for (const auto row : util::irange(0, number_of_sources)) { - osrm::json::Array json_row; + util::json::Array json_row; auto row_begin_iterator = result_table->begin() + (row * number_of_destination); auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_destination); json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator); @@ -187,19 +194,19 @@ template class DistanceTablePlugin final : public BasePlugin } json_result.values["distance_table"] = matrix_json_array; - osrm::json::Array target_coord_json_array; + util::json::Array target_coord_json_array; for (const auto &phantom : snapped_target_phantoms) { - osrm::json::Array json_coord; + util::json::Array json_coord; json_coord.values.push_back(phantom.location.lat / COORDINATE_PRECISION); json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); target_coord_json_array.values.push_back(json_coord); } json_result.values["destination_coordinates"] = target_coord_json_array; - osrm::json::Array source_coord_json_array; + util::json::Array source_coord_json_array; for (const auto &phantom : snapped_source_phantoms) { - osrm::json::Array json_coord; + util::json::Array json_coord; json_coord.values.push_back(phantom.location.lat / COORDINATE_PRECISION); json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); source_coord_json_array.values.push_back(json_coord); @@ -213,4 +220,8 @@ template class DistanceTablePlugin final : public BasePlugin DataFacadeT *facade; }; +} +} +} + #endif // DISTANCE_TABLE_HPP diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 3208b9b91..38a62b37c 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -7,6 +7,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + class HelloWorldPlugin final : public BasePlugin { private: @@ -18,7 +25,7 @@ class HelloWorldPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &routeParameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { std::string temp_string; json_result.values["title"] = "Hello World"; @@ -41,12 +48,12 @@ class HelloWorldPlugin final : public BasePlugin temp_string = std::to_string(routeParameters.coordinates.size()); json_result.values["location_count"] = temp_string; - osrm::json::Array json_locations; + util::json::Array json_locations; unsigned counter = 0; - for (const FixedPointCoordinate &coordinate : routeParameters.coordinates) + for (const util::FixedPointCoordinate &coordinate : routeParameters.coordinates) { - osrm::json::Object json_location; - osrm::json::Array json_coordinates; + util::json::Object json_location; + util::json::Array json_coordinates; json_coordinates.values.push_back( static_cast(coordinate.lat / COORDINATE_PRECISION)); @@ -59,7 +66,7 @@ class HelloWorldPlugin final : public BasePlugin json_result.values["locations"] = json_locations; json_result.values["hint_count"] = routeParameters.hints.size(); - osrm::json::Array json_hints; + util::json::Array json_hints; counter = 0; for (const std::string ¤t_hint : routeParameters.hints) { @@ -74,4 +81,8 @@ class HelloWorldPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif // HELLO_WORLD_HPP diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 54819e88f..9df0aa2af 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -23,11 +23,21 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class MapMatchingPlugin : public BasePlugin { std::shared_ptr> search_engine_ptr; - using ClassifierT = BayesClassifier; + using SubMatching = routing_algorithms::SubMatching; + using SubMatchingList = routing_algorithms::SubMatchingList; + using CandidateLists = routing_algorithms::CandidateLists; + using ClassifierT = map_matching::BayesClassifier; using TraceClassification = ClassifierT::ClassificationT; public: @@ -36,8 +46,8 @@ template class MapMatchingPlugin : public BasePlugin max_locations_map_matching(max_locations_map_matching), // the values where derived from fitting a laplace distribution // to the values of manually classified traces - classifier(LaplaceDistribution(0.005986, 0.016646), - LaplaceDistribution(0.054385, 0.458432), + classifier(map_matching::LaplaceDistribution(0.005986, 0.016646), + map_matching::LaplaceDistribution(0.054385, 0.458432), 0.696774) // valid apriori probability { search_engine_ptr = std::make_shared>(facade); @@ -65,28 +75,28 @@ template class MapMatchingPlugin : public BasePlugin return label_with_confidence; } - osrm::matching::CandidateLists getCandidates( - const std::vector &input_coords, + CandidateLists getCandidates( + const std::vector &input_coords, const std::vector>> &input_bearings, const double gps_precision, std::vector &sub_trace_lengths) { - osrm::matching::CandidateLists candidates_lists; + CandidateLists candidates_lists; // assuming the gps_precision is the standart-diviation of normal distribution that models // GPS noise (in this model) this should give us the correct candidate with >0.95 double query_radius = 3 * gps_precision; double last_distance = - coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); + util::coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); sub_trace_lengths.resize(input_coords.size()); sub_trace_lengths[0] = 0; - for (const auto current_coordinate : osrm::irange(0, input_coords.size())) + for (const auto current_coordinate : util::irange(0, input_coords.size())) { bool allow_uturn = false; if (0 < current_coordinate) { - last_distance = coordinate_calculation::haversineDistance( + last_distance = util::coordinate_calculation::haversineDistance( input_coords[current_coordinate - 1], input_coords[current_coordinate]); sub_trace_lengths[current_coordinate] += @@ -95,7 +105,7 @@ template class MapMatchingPlugin : public BasePlugin if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate) { - double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( + double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( input_coords[current_coordinate - 1], input_coords[current_coordinate], input_coords[current_coordinate + 1]); @@ -146,7 +156,7 @@ template class MapMatchingPlugin : public BasePlugin if (!allow_uturn) { const auto compact_size = candidates.size(); - for (const auto i : osrm::irange(0, compact_size)) + for (const auto i : util::irange(0, compact_size)) { // Split edge if it is bidirectional and append reverse direction to end of list if (candidates[i].phantom_node.forward_node_id != SPECIAL_NODEID && @@ -175,24 +185,24 @@ template class MapMatchingPlugin : public BasePlugin return candidates_lists; } - osrm::json::Object submatchingToJSON(const osrm::matching::SubMatching &sub, + util::json::Object submatchingToJSON(const SubMatching &sub, const RouteParameters &route_parameters, const InternalRouteResult &raw_route) { - osrm::json::Object subtrace; + util::json::Object subtrace; if (route_parameters.classify) { subtrace.values["confidence"] = sub.confidence; } - auto response_generator = osrm::engine::MakeApiResponseGenerator(facade); + auto response_generator = MakeApiResponseGenerator(facade); subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route); if (route_parameters.geometry || route_parameters.print_instructions) { - using SegmentList = osrm::engine::guidance::SegmentList; + using SegmentList = guidance::SegmentList; //Passing false to extract_alternative extracts the route. const constexpr bool EXTRACT_ROUTE = false; // by passing false to segment_list, we skip the douglas peucker simplification @@ -210,28 +220,28 @@ template class MapMatchingPlugin : public BasePlugin if (route_parameters.print_instructions) { subtrace.values["instructions"] = - osrm::engine::guidance::AnnotateRoute( + guidance::AnnotateRoute( segment_list.Get(), facade); } - osrm::json::Object json_route_summary; + util::json::Object json_route_summary; json_route_summary.values["total_distance"] = segment_list.GetDistance(); json_route_summary.values["total_time"] = segment_list.GetDuration(); subtrace.values["route_summary"] = json_route_summary; } - subtrace.values["indices"] = osrm::json::make_array(sub.indices); + subtrace.values["indices"] = util::json::make_array(sub.indices); - osrm::json::Array points; + util::json::Array points; for (const auto &node : sub.nodes) { points.values.emplace_back( - osrm::json::make_array(node.location.lat / COORDINATE_PRECISION, + util::json::make_array(node.location.lat / COORDINATE_PRECISION, node.location.lon / COORDINATE_PRECISION)); } subtrace.values["matched_points"] = points; - osrm::json::Array names; + util::json::Array names; for (const auto &node : sub.nodes) { names.values.emplace_back(facade->get_name_for_id(node.name_id)); @@ -242,7 +252,7 @@ template class MapMatchingPlugin : public BasePlugin } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) final override + util::json::Object &json_result) final override { // enforce maximum number of locations for performance reasons if (max_locations_map_matching > 0 && @@ -296,16 +306,16 @@ template class MapMatchingPlugin : public BasePlugin } // setup logging if enabled - if (osrm::json::Logger::get()) - osrm::json::Logger::get()->initialize("matching"); + if (util::json::Logger::get()) + util::json::Logger::get()->initialize("matching"); // call the actual map matching - osrm::matching::SubMatchingList sub_matchings; + SubMatchingList sub_matchings; search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps, route_parameters.matching_beta, route_parameters.gps_precision, sub_matchings); - osrm::json::Array matchings; + util::json::Array matchings; for (auto &sub : sub_matchings) { // classify result @@ -349,8 +359,8 @@ template class MapMatchingPlugin : public BasePlugin matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route)); } - if (osrm::json::Logger::get()) - osrm::json::Logger::get()->render("matching", json_result); + if (util::json::Logger::get()) + util::json::Logger::get()->render("matching", json_result); json_result.values["matchings"] = matchings; if (sub_matchings.empty()) @@ -370,4 +380,8 @@ template class MapMatchingPlugin : public BasePlugin ClassifierT classifier; }; +} +} +} + #endif // MATCH_HPP diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 28443dcf1..03604b1dc 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -8,6 +8,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + /* * This Plugin locates the nearest point on a street in the road network for a given coordinate. */ @@ -20,7 +27,7 @@ template class NearestPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { // check number of parameters if (route_parameters.coordinates.empty() || @@ -58,15 +65,15 @@ template class NearestPlugin final : public BasePlugin json_result.values["status_message"] = "Found nearest edge"; if (number_of_results > 1) { - osrm::json::Array results; + util::json::Array results; auto vector_length = phantom_node_vector.size(); for (const auto i : - osrm::irange(0, std::min(number_of_results, vector_length))) + util::irange(0, std::min(number_of_results, vector_length))) { const auto &node = phantom_node_vector[i].phantom_node; - osrm::json::Array json_coordinate; - osrm::json::Object result; + util::json::Array json_coordinate; + util::json::Object result; json_coordinate.values.push_back(node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back(node.location.lon / COORDINATE_PRECISION); result.values["mapped coordinate"] = json_coordinate; @@ -77,7 +84,7 @@ template class NearestPlugin final : public BasePlugin } else { - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.push_back( phantom_node_vector.front().phantom_node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back( @@ -95,4 +102,8 @@ template class NearestPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif /* NEAREST_HPP */ diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index 5dffedd01..a2c7eba8c 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -11,6 +11,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + class BasePlugin { public: @@ -26,12 +33,12 @@ class BasePlugin // Maybe someone can explain the pure virtual destructor thing to me (dennis) virtual ~BasePlugin() {} virtual const std::string GetDescriptor() const = 0; - virtual Status HandleRequest(const RouteParameters &, osrm::json::Object &) = 0; - virtual bool check_all_coordinates(const std::vector &coordinates, + virtual Status HandleRequest(const RouteParameters &, util::json::Object &) = 0; + virtual bool check_all_coordinates(const std::vector &coordinates, const unsigned min = 2) const final { if (min > coordinates.size() || std::any_of(std::begin(coordinates), std::end(coordinates), - [](const FixedPointCoordinate &coordinate) + [](const util::FixedPointCoordinate &coordinate) { return !coordinate.IsValid(); })) @@ -106,4 +113,8 @@ class BasePlugin } }; +} +} +} + #endif /* BASE_PLUGIN_HPP */ diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index b479f01fc..1ec3d0a62 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -7,6 +7,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class TimestampPlugin final : public BasePlugin { public: @@ -16,7 +23,7 @@ template class TimestampPlugin final : public BasePlugin } const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { (void)route_parameters; // unused @@ -30,4 +37,8 @@ template class TimestampPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif /* TIMESTAMP_PLUGIN_H */ diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 9ef2909bc..54632fdcd 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -25,6 +25,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class RoundTripPlugin final : public BasePlugin { private: @@ -37,7 +44,7 @@ template class RoundTripPlugin final : public BasePlugin explicit RoundTripPlugin(DataFacadeT *facade, int max_locations_trip) : descriptor_string("trip"), facade(facade), max_locations_trip(max_locations_trip) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } const std::string GetDescriptor() const override final { return descriptor_string; } @@ -51,7 +58,7 @@ template class RoundTripPlugin final : public BasePlugin phantom_node_list.reserve(route_parameters.coordinates.size()); // find phantom nodes for all input coords - for (const auto i : osrm::irange(0, route_parameters.coordinates.size())) + for (const auto i : util::irange(0, route_parameters.coordinates.size())) { // if client hints are helpful, encode hints if (checksum_OK && i < route_parameters.hints.size() && @@ -129,7 +136,7 @@ template class RoundTripPlugin final : public BasePlugin // identifies and splits the graph in its strongly connected components (scc) // and returns an SCC_Component SCC_Component SplitUnaccessibleLocations(const std::size_t number_of_locations, - const DistTableWrapper &result_table) + const util::DistTableWrapper &result_table) { if (std::find(std::begin(result_table), std::end(result_table), INVALID_EDGE_WEIGHT) == @@ -142,9 +149,9 @@ template class RoundTripPlugin final : public BasePlugin } // Run TarjanSCC - auto wrapper = std::make_shared>(result_table.GetTable(), + auto wrapper = std::make_shared>(result_table.GetTable(), number_of_locations); - auto scc = TarjanSCC>(wrapper); + auto scc = extractor::TarjanSCC>(wrapper); scc.run(); const auto number_of_components = scc.get_number_of_components(); @@ -174,9 +181,9 @@ template class RoundTripPlugin final : public BasePlugin } void SetLocPermutationOutput(const std::vector &permutation, - osrm::json::Object &json_result) + util::json::Object &json_result) { - osrm::json::Array json_permutation; + util::json::Array json_permutation; json_permutation.values.insert(std::end(json_permutation.values), std::begin(permutation), std::end(permutation)); json_result.values["permutation"] = json_permutation; @@ -218,7 +225,7 @@ template class RoundTripPlugin final : public BasePlugin } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (max_locations_trip > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_trip)) @@ -259,7 +266,7 @@ template class RoundTripPlugin final : public BasePlugin const auto number_of_locations = phantom_node_list.size(); // compute the distance table of all phantom nodes - const auto result_table = DistTableWrapper( + const auto result_table = util::DistTableWrapper( *search_engine_ptr->distance_table(phantom_node_list, phantom_node_list), number_of_locations); @@ -295,16 +302,16 @@ template class RoundTripPlugin final : public BasePlugin if (component_size < BF_MAX_FEASABLE) { scc_route = - osrm::trip::BruteForceTrip(start, end, number_of_locations, result_table); + trip::BruteForceTrip(start, end, number_of_locations, result_table); } else { - scc_route = osrm::trip::FarthestInsertionTrip(start, end, number_of_locations, + scc_route = trip::FarthestInsertionTrip(start, end, number_of_locations, result_table); } // use this output if debugging of route is needed: - // SimpleLogger().Write() << "Route #" << k << ": " << [&scc_route]() + // util::SimpleLogger().Write() << "Route #" << k << ": " << [&scc_route]() // { // std::string s = ""; // for (auto x : scc_route) @@ -333,13 +340,13 @@ template class RoundTripPlugin final : public BasePlugin // prepare JSON output // create a json object for every trip - osrm::json::Array trip; + util::json::Array trip; for (std::size_t i = 0; i < route_result.size(); ++i) { - osrm::json::Object scc_trip; + util::json::Object scc_trip; // annotate comp_route[i] as a json trip - auto generator = osrm::engine::MakeApiResponseGenerator(facade); + auto generator = MakeApiResponseGenerator(facade); generator.DescribeRoute(route_parameters, comp_route[i], scc_trip); // set permutation output @@ -360,4 +367,8 @@ template class RoundTripPlugin final : public BasePlugin } }; +} +} +} + #endif // TRIP_HPP diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 6b432e55d..8e58c00f9 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -20,6 +20,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class ViaRoutePlugin final : public BasePlugin { private: @@ -33,7 +40,7 @@ template class ViaRoutePlugin final : public BasePlugin : descriptor_string("viaroute"), facade(facade), max_locations_viaroute(max_locations_viaroute) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } virtual ~ViaRoutePlugin() {} @@ -41,7 +48,7 @@ template class ViaRoutePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (max_locations_viaroute > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_viaroute)) @@ -70,7 +77,7 @@ template class ViaRoutePlugin final : public BasePlugin std::vector phantom_node_pair_list(route_parameters.coordinates.size()); const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum()); - for (const auto i : osrm::irange(0, route_parameters.coordinates.size())) + for (const auto i : util::irange(0, route_parameters.coordinates.size())) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) @@ -108,7 +115,7 @@ template class ViaRoutePlugin final : public BasePlugin { raw_route.segment_end_coordinates.push_back(PhantomNodes{first_node, second_node}); }; - osrm::for_each_pair(snapped_phantoms, build_phantom_pairs); + util::for_each_pair(snapped_phantoms, build_phantom_pairs); if (1 == raw_route.segment_end_coordinates.size()) { @@ -131,7 +138,7 @@ template class ViaRoutePlugin final : public BasePlugin bool no_route = INVALID_EDGE_WEIGHT == raw_route.shortest_path_length; - auto generator = osrm::engine::MakeApiResponseGenerator(facade); + auto generator = MakeApiResponseGenerator(facade); generator.DescribeRoute(route_parameters, raw_route, json_result); // we can only know this after the fact, different SCC ids still @@ -160,4 +167,8 @@ template class ViaRoutePlugin final : public BasePlugin } }; +} +} +} + #endif // VIA_ROUTE_HPP diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index 7d04b1d10..5d26a14fa 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -1,13 +1,18 @@ #ifndef POLYLINECOMPRESSOR_H_ #define POLYLINECOMPRESSOR_H_ -struct SegmentInformation; - #include "osrm/coordinate.hpp" #include #include +namespace osrm +{ +namespace engine +{ + +struct SegmentInformation; + class PolylineCompressor { private: @@ -18,7 +23,10 @@ class PolylineCompressor public: std::string get_encoded_string(const std::vector &polyline) const; - std::vector decode_string(const std::string &geometry_string) const; + std::vector decode_string(const std::string &geometry_string) const; }; +} +} + #endif /* POLYLINECOMPRESSOR_H_ */ diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index b71035ae4..861fec01f 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -1,18 +1,26 @@ #ifndef POLYLINE_FORMATTER_HPP #define POLYLINE_FORMATTER_HPP -struct SegmentInformation; - #include "osrm/json_container.hpp" #include #include +namespace osrm +{ +namespace engine +{ + +struct SegmentInformation; + struct PolylineFormatter { - osrm::json::String printEncodedString(const std::vector &polyline) const; + util::json::String printEncodedString(const std::vector &polyline) const; - osrm::json::Array printUnencodedString(const std::vector &polyline) const; + util::json::Array printUnencodedString(const std::vector &polyline) const; }; +} +} + #endif /* POLYLINE_FORMATTER_HPP */ diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index 97e1919bb..df6a8ac89 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct RouteNames { std::string shortest_path_name_1; @@ -135,4 +140,7 @@ template struct ExtractRouteNames } }; +} +} + #endif // EXTRACT_ROUTE_NAMES_H diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 37b6ced19..ec82818f8 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -13,6 +13,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + const double VIAPATH_ALPHA = 0.10; const double VIAPATH_EPSILON = 0.15; // alternative at most 15% longer const double VIAPATH_GAMMA = 0.75; // alternative shares at most 75% with the shortest. @@ -81,7 +88,7 @@ class AlternativeRouting final if (phantom_node_pair.source_phantom.forward_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "fwd-a insert: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd-a insert: " << // phantom_node_pair.source_phantom.forward_node_id << ", w: " << // -phantom_node_pair.source_phantom.GetForwardWeightPlusOffset(); forward_heap1.Insert(phantom_node_pair.source_phantom.forward_node_id, @@ -90,7 +97,7 @@ class AlternativeRouting final } if (phantom_node_pair.source_phantom.reverse_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "fwd-b insert: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd-b insert: " << // phantom_node_pair.source_phantom.reverse_node_id << ", w: " << // -phantom_node_pair.source_phantom.GetReverseWeightPlusOffset(); forward_heap1.Insert(phantom_node_pair.source_phantom.reverse_node_id, @@ -100,7 +107,7 @@ class AlternativeRouting final if (phantom_node_pair.target_phantom.forward_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "rev-a insert: " << + // util::SimpleLogger().Write(logDEBUG) << "rev-a insert: " << // phantom_node_pair.target_phantom.forward_node_id << ", w: " << // phantom_node_pair.target_phantom.GetForwardWeightPlusOffset(); reverse_heap1.Insert(phantom_node_pair.target_phantom.forward_node_id, @@ -109,7 +116,7 @@ class AlternativeRouting final } if (phantom_node_pair.target_phantom.reverse_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "rev-b insert: " << + // util::SimpleLogger().Write(logDEBUG) << "rev-b insert: " << // phantom_node_pair.target_phantom.reverse_node_id << ", w: " << // phantom_node_pair.target_phantom.GetReverseWeightPlusOffset(); reverse_heap1.Insert(phantom_node_pair.target_phantom.reverse_node_id, @@ -141,7 +148,7 @@ class AlternativeRouting final return; } - osrm::sort_unique_resize(via_node_candidate_list); + util::sort_unique_resize(via_node_candidate_list); std::vector packed_forward_path; std::vector packed_reverse_path; @@ -204,10 +211,10 @@ class AlternativeRouting final } } - // SimpleLogger().Write(logDEBUG) << "fwd_search_space size: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd_search_space size: " << // forward_search_space.size() << ", marked " << approximated_forward_sharing.size() << " // nodes"; - // SimpleLogger().Write(logDEBUG) << "rev_search_space size: " << + // util::SimpleLogger().Write(logDEBUG) << "rev_search_space size: " << // reverse_search_space.size() << ", marked " << approximated_reverse_sharing.size() << " // nodes"; @@ -403,7 +410,7 @@ class AlternativeRouting final // First partially unpack s-->v until paths deviate, note length of common path. const int64_t s_v_min_path_size = static_cast(std::min(packed_s_v_path.size(), packed_shortest_path.size())) - 1; - for (const int64_t current_node : osrm::irange(0, s_v_min_path_size)) + for (const int64_t current_node : util::irange(0, s_v_min_path_size)) { if (packed_s_v_path[current_node] == packed_shortest_path[current_node] && packed_s_v_path[current_node + 1] == packed_shortest_path[current_node + 1]) @@ -519,7 +526,7 @@ class AlternativeRouting final // //compute forward sharing // while( (packed_alternate_path[aindex] == packed_shortest_path[aindex]) && // (packed_alternate_path[aindex+1] == packed_shortest_path[aindex+1]) ) { - // // SimpleLogger().Write() << "retrieving edge (" << + // // util::SimpleLogger().Write() << "retrieving edge (" << // packed_alternate_path[aindex] << "," << packed_alternate_path[aindex+1] << ")"; // EdgeID edgeID = facade->FindEdgeInEitherDirection(packed_alternate_path[aindex], // packed_alternate_path[aindex+1]); @@ -557,7 +564,7 @@ class AlternativeRouting final const NodeID node = forward_heap.DeleteMin(); const int distance = forward_heap.GetKey(node); // const NodeID parentnode = forward_heap.GetData(node).parent; - // SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled edge (" + // util::SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled edge (" // << parentnode << "," << node << "), dist: " << distance; const int scaled_distance = @@ -581,10 +588,10 @@ class AlternativeRouting final { *middle_node = node; *upper_bound_to_shortest_path_distance = new_distance; - // SimpleLogger().Write() << "accepted middle_node " << *middle_node << " at + // util::SimpleLogger().Write() << "accepted middle_node " << *middle_node << " at // distance " << new_distance; // } else { - // SimpleLogger().Write() << "discarded middle_node " << *middle_node << " + // util::SimpleLogger().Write() << "discarded middle_node " << *middle_node << " // at distance " << new_distance; } } @@ -840,4 +847,8 @@ class AlternativeRouting final } }; +} +} +} + #endif /* ALTERNATIVE_PATH_ROUTING_HPP */ diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 42bc357ff..7c935928c 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -10,6 +10,13 @@ #include "util/timing_util.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + /// This is a striped down version of the general shortest path algorithm. /// The general algorithm always computes two queries for each leg. This is only /// necessary in case of vias, where the directions of the start node is constrainted @@ -125,4 +132,8 @@ class DirectShortestPathRouting final } }; +} +} +} + #endif /* DIRECT_SHORTEST_PATH_HPP */ diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index fb6981892..c8311783f 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -12,6 +12,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + template class ManyToManyRouting final : public BasicRoutingInterface> @@ -226,4 +233,8 @@ class ManyToManyRouting final return false; } }; +} +} +} + #endif diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 905dc611a..23edcedb5 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -19,7 +19,9 @@ namespace osrm { -namespace matching +namespace engine +{ +namespace routing_algorithms { struct SubMatching @@ -32,15 +34,12 @@ struct SubMatching using CandidateList = std::vector; using CandidateLists = std::vector; -using HMM = HiddenMarkovModel; +using HMM = map_matching::HiddenMarkovModel; using SubMatchingList = std::vector; constexpr static const unsigned MAX_BROKEN_STATES = 10; - constexpr static const double MAX_SPEED = 180 / 3.6; // 180km -> m/s constexpr static const unsigned SUSPICIOUS_DISTANCE_DELTA = 100; -} -} // implements a hidden markov model map matching algorithm template @@ -71,12 +70,12 @@ class MapMatching final : public BasicRoutingInterface &trace_coordinates, + void operator()(const CandidateLists &candidates_list, + const std::vector &trace_coordinates, const std::vector &trace_timestamps, const double matching_beta, const double gps_precision, - osrm::matching::SubMatchingList &sub_matchings) const + SubMatchingList &sub_matchings) const { BOOST_ASSERT(candidates_list.size() == trace_coordinates.size()); BOOST_ASSERT(candidates_list.size() > 1); @@ -94,12 +93,12 @@ class MapMatching final : public BasicRoutingInterface split_points; std::vector prev_unbroken_timestamps; prev_unbroken_timestamps.reserve(candidates_list.size()); @@ -149,16 +148,16 @@ class MapMatching final : public BasicRoutingInterface - osrm::matching::MAX_BROKEN_STATES); + MAX_BROKEN_STATES); } if (trace_split) { std::size_t split_index = t; - if (breakage_begin != osrm::matching::INVALID_STATE) + if (breakage_begin != map_matching::INVALID_STATE) { split_index = breakage_begin; - breakage_begin = osrm::matching::INVALID_STATE; + breakage_begin = map_matching::INVALID_STATE; } split_points.push_back(split_index); @@ -166,7 +165,7 @@ class MapMatching final : public BasicRoutingInterface stop viterbi calculation - if (new_start == osrm::matching::INVALID_STATE) + if (new_start == map_matching::INVALID_STATE) { break; } @@ -196,17 +195,17 @@ class MapMatching final : public BasicRoutingInterface(0u, prev_viterbi.size())) + for (const auto s : util::irange(0u, prev_viterbi.size())) { if (prev_pruned[s]) { continue; } - for (const auto s_prime : osrm::irange(0u, current_viterbi.size())) + for (const auto s_prime : util::irange(0u, current_viterbi.size())) { // how likely is candidate s_prime at time t to be emitted? // FIXME this can be pre-computed @@ -248,7 +247,7 @@ class MapMatching final : public BasicRoutingInterface osrm::matching::SUSPICIOUS_DISTANCE_DELTA; + d_t > SUSPICIOUS_DISTANCE_DELTA; model.breakage[t] = false; } } @@ -282,7 +281,7 @@ class MapMatching final : public BasicRoutingInterface= sub_matching_begin && @@ -338,7 +337,7 @@ class MapMatching final : public BasicRoutingInterface(0u, reconstructed_indices.size())) + for (const auto i : util::irange(0u, reconstructed_indices.size())) { const auto timestamp_index = reconstructed_indices[i].first; const auto location_index = reconstructed_indices[i].second; @@ -357,6 +356,10 @@ class MapMatching final : public BasicRoutingInterface +namespace osrm +{ +namespace engine +{ + SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_1; SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_1; SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_2; @@ -17,6 +22,10 @@ SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_2; SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_3; SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_3; +namespace routing_algorithms +{ + + template class BasicRoutingInterface { private: @@ -222,8 +231,8 @@ template class BasicRoutingInterface { BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut"); unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id); - const TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); - const TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); + const extractor::TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); + const extractor::TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); if (!facade->EdgeIsCompressed(ed.id)) { @@ -251,7 +260,7 @@ template class BasicRoutingInterface for (std::size_t i = start_index; i < end_index; ++i) { unpacked_path.emplace_back(id_vector[i], name_index, - TurnInstruction::NoTurn, 0, travel_mode); + extractor::TurnInstruction::NoTurn, 0, travel_mode); } unpacked_path.back().turn_instruction = turn_instruction; unpacked_path.back().segment_duration = ed.distance; @@ -296,7 +305,7 @@ template class BasicRoutingInterface BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); unpacked_path.emplace_back(PathData{ - id_vector[i], phantom_node_pair.target_phantom.name_id, TurnInstruction::NoTurn, + id_vector[i], phantom_node_pair.target_phantom.name_id, extractor::TurnInstruction::NoTurn, 0, phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -642,21 +651,25 @@ template class BasicRoutingInterface nodes.target_phantom = target_phantom; UnpackPath(packed_leg.begin(), packed_leg.end(), nodes, unpacked_path); - FixedPointCoordinate previous_coordinate = source_phantom.location; - FixedPointCoordinate current_coordinate; + util::FixedPointCoordinate previous_coordinate = source_phantom.location; + util::FixedPointCoordinate current_coordinate; distance = 0; for (const auto &p : unpacked_path) { current_coordinate = facade->GetCoordinateOfNode(p.node); - distance += coordinate_calculation::haversineDistance(previous_coordinate, + distance += util::coordinate_calculation::haversineDistance(previous_coordinate, current_coordinate); previous_coordinate = current_coordinate; } - distance += coordinate_calculation::haversineDistance(previous_coordinate, + distance += util::coordinate_calculation::haversineDistance(previous_coordinate, target_phantom.location); } return distance; } }; +} +} +} + #endif // ROUTING_BASE_HPP diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index a9b50afe4..8a057d42d 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -10,6 +10,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + template class ShortestPathRouting final : public BasicRoutingInterface> @@ -262,7 +269,7 @@ class ShortestPathRouting final raw_route_data.shortest_path_length = shortest_path_length; - for (const auto current_leg : osrm::irange(0, packed_leg_begin.size() - 1)) + for (const auto current_leg : util::irange(0, packed_leg_begin.size() - 1)) { auto leg_begin = total_packed_path.begin() + packed_leg_begin[current_leg]; auto leg_end = total_packed_path.begin() + packed_leg_begin[current_leg + 1]; @@ -515,4 +522,8 @@ class ShortestPathRouting final } }; +} +} +} + #endif /* SHORTEST_PATH_HPP */ diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index aec2a735a..fefc90368 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -10,6 +10,11 @@ #include +namespace osrm +{ +namespace engine +{ + template class SearchEngine { private: @@ -17,11 +22,11 @@ template class SearchEngine SearchEngineData engine_working_data; public: - ShortestPathRouting shortest_path; - DirectShortestPathRouting direct_shortest_path; - AlternativeRouting alternative_path; - ManyToManyRouting distance_table; - MapMatching map_matching; + routing_algorithms::ShortestPathRouting shortest_path; + routing_algorithms::DirectShortestPathRouting direct_shortest_path; + routing_algorithms::AlternativeRouting alternative_path; + routing_algorithms::ManyToManyRouting distance_table; + routing_algorithms::MapMatching map_matching; explicit SearchEngine(DataFacadeT *facade) : facade(facade), shortest_path(facade, engine_working_data), @@ -37,4 +42,7 @@ template class SearchEngine ~SearchEngine() {} }; +} +} + #endif // SEARCH_ENGINE_HPP diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 87e76604e..2e5b59da5 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -6,6 +6,11 @@ #include "util/typedefs.hpp" #include "util/binary_heap.hpp" +namespace osrm +{ +namespace engine +{ + struct HeapData { NodeID parent; @@ -14,7 +19,7 @@ struct HeapData struct SearchEngineData { - using QueryHeap = BinaryHeap>; + using QueryHeap = util::BinaryHeap>; using SearchEngineHeapPtr = boost::thread_specific_ptr; static SearchEngineHeapPtr forward_heap_1; @@ -31,4 +36,7 @@ struct SearchEngineData void InitializeOrClearThirdThreadLocalStorage(const unsigned number_of_nodes); }; +} +} + #endif // SEARCH_ENGINE_DATA_HPP diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index eaedec78d..527726f92 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -2,53 +2,60 @@ #define SEGMENT_INFORMATION_HPP #include "extractor/turn_instructions.hpp" - #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" #include "osrm/coordinate.hpp" #include +namespace osrm +{ +namespace engine +{ + // Struct fits everything in one cache line struct SegmentInformation { - FixedPointCoordinate location; + util::FixedPointCoordinate location; NodeID name_id; EdgeWeight duration; float length; short pre_turn_bearing; // more than enough [0..3600] fits into 12 bits short post_turn_bearing; - TurnInstruction turn_instruction; - TravelMode travel_mode; + extractor::TurnInstruction turn_instruction; + extractor::TravelMode travel_mode; bool necessary; bool is_via_location; - explicit SegmentInformation(FixedPointCoordinate location, + explicit SegmentInformation(util::FixedPointCoordinate location, const NodeID name_id, const EdgeWeight duration, const float length, - const TurnInstruction turn_instruction, + const extractor::TurnInstruction turn_instruction, const bool necessary, const bool is_via_location, - const TravelMode travel_mode) + const extractor::TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), travel_mode(travel_mode), necessary(necessary), is_via_location(is_via_location) { } - explicit SegmentInformation(FixedPointCoordinate location, + explicit SegmentInformation(util::FixedPointCoordinate location, const NodeID name_id, const EdgeWeight duration, const float length, - const TurnInstruction turn_instruction, - const TravelMode travel_mode) + const extractor::TurnInstruction turn_instruction, + const extractor::TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), - travel_mode(travel_mode), necessary(turn_instruction != TurnInstruction::NoTurn), + travel_mode(travel_mode), necessary(turn_instruction != extractor::TurnInstruction::NoTurn), is_via_location(false) { } }; +} +} + #endif /* SEGMENT_INFORMATION_HPP */ diff --git a/include/engine/trip/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp index d45643059..5cecabcac 100644 --- a/include/engine/trip/trip_brute_force.hpp +++ b/include/engine/trip/trip_brute_force.hpp @@ -16,11 +16,13 @@ namespace osrm { +namespace engine +{ namespace trip { // computes the distance of a given permutation -EdgeWeight ReturnDistance(const DistTableWrapper &dist_table, +EdgeWeight ReturnDistance(const util::DistTableWrapper &dist_table, const std::vector &location_order, const EdgeWeight min_route_dist, const std::size_t component_size) @@ -44,7 +46,7 @@ template std::vector BruteForceTrip(const NodeIDIterator start, const NodeIDIterator end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { (void)number_of_locations; // unused @@ -76,6 +78,8 @@ std::vector BruteForceTrip(const NodeIDIterator start, return route; } -} // end namespace trip -} // end namespace osrm +} +} +} + #endif // TRIP_BRUTE_FORCE_HPP diff --git a/include/engine/trip/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp index aa94b1fb0..2e3b401a4 100644 --- a/include/engine/trip/trip_farthest_insertion.hpp +++ b/include/engine/trip/trip_farthest_insertion.hpp @@ -15,6 +15,8 @@ namespace osrm { +namespace engine +{ namespace trip { @@ -23,7 +25,7 @@ namespace trip using NodeIDIter = std::vector::iterator; std::pair GetShortestRoundTrip(const NodeID new_loc, - const DistTableWrapper &dist_table, + const util::DistTableWrapper &dist_table, const std::size_t number_of_locations, std::vector &route) { @@ -76,7 +78,7 @@ std::vector FindRoute(const std::size_t &number_of_locations, const std::size_t &component_size, const NodeIDIterator &start, const NodeIDIterator &end, - const DistTableWrapper &dist_table, + const util::DistTableWrapper &dist_table, const NodeID &start1, const NodeID &start2) { @@ -138,7 +140,7 @@ template std::vector FarthestInsertionTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START FARTHEST INSERTION HERE @@ -189,7 +191,8 @@ std::vector FarthestInsertionTrip(const NodeIDIterator &start, return FindRoute(number_of_locations, component_size, start, end, dist_table, max_from, max_to); } -} // end namespace trip -} // end namespace osrm +} +} +} #endif // TRIP_FARTHEST_INSERTION_HPP diff --git a/include/engine/trip/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp index c66e611d6..a7a5baeb3 100644 --- a/include/engine/trip/trip_nearest_neighbour.hpp +++ b/include/engine/trip/trip_nearest_neighbour.hpp @@ -15,13 +15,16 @@ namespace osrm { +namespace engine +{ namespace trip { + template std::vector NearestNeighbourTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START GREEDY NEAREST NEIGHBOUR HERE @@ -90,6 +93,8 @@ std::vector NearestNeighbourTrip(const NodeIDIterator &start, return route; } -} // end namespace trip -} // end namespace osrm -#endif // TRIP_NEAREST_NEIGHBOUR_HPP \ No newline at end of file +} +} +} + +#endif // TRIP_NEAREST_NEIGHBOUR_HPP diff --git a/include/engine/trip/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp index 1eb5b6a44..d92763616 100644 --- a/include/engine/trip/trip_tabu_search.hpp +++ b/include/engine/trip/trip_tabu_search.hpp @@ -14,6 +14,8 @@ namespace osrm { +namespace engine +{ namespace trip { @@ -32,6 +34,9 @@ void TabuSearchTrip(const PhantomNodeArray &phantom_node_vector, std::vector &min_loc_permutation) { } + } } -#endif // TRIP_BRUTE_FORCE_HPP \ No newline at end of file +} + +#endif // TRIP_BRUTE_FORCE_HPP diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index cfac68eff..47146162c 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + class CompressedEdgeContainer { public: @@ -39,4 +44,7 @@ class CompressedEdgeContainer std::unordered_map m_edge_id_to_list_index_map; }; +} +} + #endif // GEOMETRY_COMPRESSOR_HPP_ diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 5a2b259f2..47aeecdcb 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -27,13 +27,18 @@ struct lua_State; +namespace osrm +{ +namespace extractor +{ + class EdgeBasedGraphFactory { public: EdgeBasedGraphFactory() = delete; EdgeBasedGraphFactory(const EdgeBasedGraphFactory &) = delete; - explicit EdgeBasedGraphFactory(std::shared_ptr node_based_graph, + explicit EdgeBasedGraphFactory(std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, @@ -56,7 +61,7 @@ class EdgeBasedGraphFactory const bool generate_edge_lookup); #endif - void GetEdgeBasedEdges(DeallocatingVector &edges); + void GetEdgeBasedEdges(util::DeallocatingVector &edges); void GetEdgeBasedNodes(std::vector &nodes); void GetStartPointMarkers(std::vector &node_is_startpoint); @@ -69,18 +74,18 @@ class EdgeBasedGraphFactory int GetTurnPenalty(double angle, lua_State *lua_state) const; private: - using EdgeData = NodeBasedDynamicGraph::EdgeData; + using EdgeData = util::NodeBasedDynamicGraph::EdgeData; //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the //! graph std::vector m_edge_based_node_is_startpoint; //! list of edge based nodes (compressed segments) std::vector m_edge_based_node_list; - DeallocatingVector m_edge_based_edge_list; + util::DeallocatingVector m_edge_based_edge_list; unsigned m_max_edge_id; const std::vector &m_node_info_list; - std::shared_ptr m_node_based_graph; + std::shared_ptr m_node_based_graph; std::shared_ptr m_restriction_map; const std::unordered_set &m_barrier_nodes; @@ -113,4 +118,7 @@ class EdgeBasedGraphFactory std::vector &original_edge_data_vector) const; }; +} +} + #endif /* EDGE_BASED_GRAPH_FACTORY_HPP_ */ diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index 3ea715a89..aee2d6a34 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -10,7 +10,12 @@ #include -/// This is what StaticRTree serialized and stores on disk +namespace osrm +{ +namespace extractor +{ + +/// This is what util::StaticRTree serialized and stores on disk /// It is generated in EdgeBasedGraphFactory. struct EdgeBasedNode { @@ -53,10 +58,10 @@ struct EdgeBasedNode (reverse_edge_based_node_id != SPECIAL_NODEID)); } - static inline FixedPointCoordinate Centroid(const FixedPointCoordinate &a, - const FixedPointCoordinate &b) + static inline util::FixedPointCoordinate Centroid(const util::FixedPointCoordinate &a, + const util::FixedPointCoordinate &b) { - FixedPointCoordinate centroid; + util::FixedPointCoordinate centroid; // The coordinates of the midpoint are given by: centroid.lat = (a.lat + b.lat) / 2; centroid.lon = (a.lon + b.lon) / 2; @@ -85,4 +90,7 @@ struct EdgeBasedNode TravelMode backward_travel_mode : 4; }; +} +} + #endif // EDGE_BASED_NODE_HPP diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index 8c2b7d194..544e59fdc 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -5,6 +5,11 @@ #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct ExternalMemoryNode : QueryNode { ExternalMemoryNode(int lat, int lon, OSMNodeID id, bool barrier, bool traffic_light); @@ -27,4 +32,7 @@ struct ExternalMemoryNodeSTXXLCompare value_type min_value(); }; +} +} + #endif /* EXTERNAL_MEMORY_NODE_HPP_ */ diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index 83a8978f5..53177e0d6 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * Uses external memory containers from stxxl to store all the data that * is collected by the extractor callbacks. @@ -61,4 +66,7 @@ class ExtractionContainers lua_State *segment_state); }; +} +} + #endif /* EXTRACTION_CONTAINERS_HPP */ diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index 6872812fc..82a493b77 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -12,6 +12,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + bool simple_duration_is_valid(const std::string &s) { boost::regex simple_format( @@ -29,8 +34,8 @@ bool simple_duration_is_valid(const std::string &s) bool iso_8601_duration_is_valid(const std::string &s) { - iso_8601_grammar iso_parser; - const bool result = qi::parse(s.begin(), s.end(), iso_parser); + util::iso_8601_grammar iso_parser; + const bool result = boost::spirit::qi::parse(s.begin(), s.end(), iso_parser); // check if the was an error with the request if (result && (0 != iso_parser.get_duration())) @@ -81,8 +86,8 @@ unsigned parseDuration(const std::string &s) } else if (iso_8601_duration_is_valid(s)) { - iso_8601_grammar iso_parser; - qi::parse(s.begin(), s.end(), iso_parser); + util::iso_8601_grammar iso_parser; + boost::spirit::qi::parse(s.begin(), s.end(), iso_parser); return iso_parser.get_duration(); } @@ -90,4 +95,7 @@ unsigned parseDuration(const std::string &s) return std::numeric_limits::max(); } +} +} + #endif // EXTRACTION_HELPER_FUNCTIONS_HPP diff --git a/include/extractor/extraction_node.hpp b/include/extractor/extraction_node.hpp index 46044eaf3..82826e717 100644 --- a/include/extractor/extraction_node.hpp +++ b/include/extractor/extraction_node.hpp @@ -1,6 +1,11 @@ #ifndef EXTRACTION_NODE_HPP #define EXTRACTION_NODE_HPP +namespace osrm +{ +namespace extractor +{ + struct ExtractionNode { ExtractionNode() : traffic_lights(false), barrier(false) {} @@ -8,4 +13,8 @@ struct ExtractionNode bool traffic_lights; bool barrier; }; + +} +} + #endif // EXTRACTION_NODE_HPP diff --git a/include/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp index 300518110..f54b5fe77 100644 --- a/include/extractor/extraction_way.hpp +++ b/include/extractor/extraction_way.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * This struct is the direct result of the call to ```way_function``` * in the lua based profile. @@ -99,4 +104,7 @@ struct ExtractionWay TravelMode backward_travel_mode : 4; }; +} +} + #endif // EXTRACTION_WAY_HPP diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index d7c49d656..c9faca9d5 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -5,6 +5,11 @@ #include "extractor/edge_based_graph_factory.hpp" #include "extractor/graph_compressor.hpp" +namespace osrm +{ +namespace extractor +{ + class extractor { public: @@ -18,22 +23,25 @@ class extractor BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, - DeallocatingVector &edge_based_edge_list); + util::DeallocatingVector &edge_based_edge_list); void WriteNodeMapping(const std::vector &internal_to_external_node_map); void FindComponents(unsigned max_edge_id, - const DeallocatingVector &edges, + const util::DeallocatingVector &edges, std::vector &nodes) const; void BuildRTree(std::vector node_based_edge_list, std::vector node_is_startpoint, const std::vector &internal_to_external_node_map); std::shared_ptr LoadRestrictionMap(); - std::shared_ptr + std::shared_ptr LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map); void WriteEdgeBasedGraph(std::string const &output_file_filename, size_t const max_edge_id, - DeallocatingVector const &edge_based_edge_list); + util::DeallocatingVector const &edge_based_edge_list); }; +} +} + #endif /* EXTRACTOR_HPP */ diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index 38fe76ec3..a862f936c 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -7,17 +7,22 @@ #include #include -struct ExternalMemoryNode; -class ExtractionContainers; -struct InputRestrictionContainer; -struct ExtractionNode; -struct ExtractionWay; namespace osmium { class Node; class Way; } +namespace osrm +{ +namespace extractor +{ + +class ExtractionContainers; +struct InputRestrictionContainer; +struct ExtractionNode; +struct ExtractionWay; + /** * This class is uses by the extractor with the results of the * osmium based parsing and the customization through the lua profile. @@ -47,4 +52,7 @@ class ExtractorCallbacks void ProcessWay(const osmium::Way ¤t_way, const ExtractionWay &result_way); }; +} +} + #endif /* EXTRACTOR_CALLBACKS_HPP */ diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 16593a0e9..05949f52f 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace extractor +{ + enum class return_code : unsigned { ok, @@ -48,4 +53,7 @@ struct ExtractorOptions static void GenerateOutputFilesNames(ExtractorConfig &extractor_config); }; +} +} + #endif // EXTRACTOR_OPTIONS_HPP diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index fa5b5b65c..d4ea8e457 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + struct FirstAndLastSegmentOfWay { OSMWayID way_id; @@ -49,4 +54,7 @@ struct FirstAndLastSegmentOfWayStxxlCompare value_type min_value() { return FirstAndLastSegmentOfWay::min_value(); } }; +} +} + #endif /* FIRST_AND_LAST_SEGMENT_OF_WAY_HPP */ diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 7b9cd5a73..56496aefd 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -9,12 +9,17 @@ #include #include +namespace osrm +{ +namespace extractor +{ + class CompressedEdgeContainer; class RestrictionMap; class GraphCompressor { - using EdgeData = NodeBasedDynamicGraph::EdgeData; + using EdgeData = util::NodeBasedDynamicGraph::EdgeData; public: GraphCompressor(SpeedProfileProperties speed_profile); @@ -22,15 +27,18 @@ class GraphCompressor void Compress(const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, RestrictionMap &restriction_map, - NodeBasedDynamicGraph &graph, + util::NodeBasedDynamicGraph &graph, CompressedEdgeContainer &geometry_compressor); private: void PrintStatistics(unsigned original_number_of_nodes, unsigned original_number_of_edges, - const NodeBasedDynamicGraph &graph) const; + const util::NodeBasedDynamicGraph &graph) const; SpeedProfileProperties speed_profile; }; +} +} + #endif diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index 9fe4a8b50..095c9f95a 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -4,6 +4,11 @@ #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct NodeBasedEdge { bool operator<(const NodeBasedEdge &e) const; @@ -90,4 +95,7 @@ struct EdgeBasedEdge bool backward : 1; }; +} +} + #endif /* IMPORT_EDGE_HPP */ diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index b5c8e031a..2d3447fda 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -10,6 +10,11 @@ #include "osrm/coordinate.hpp" #include +namespace osrm +{ +namespace extractor +{ + struct InternalExtractorEdge { // specify the type of the weight data @@ -80,7 +85,7 @@ struct InternalExtractorEdge // intermediate edge weight WeightData weight_data; // coordinate of the source node - FixedPointCoordinate source_coordinate; + util::FixedPointCoordinate source_coordinate; // necessary static util functions for stxxl's sorting static InternalExtractorEdge min_osm_value() @@ -148,4 +153,7 @@ struct CmpEdgeByOSMTargetID value_type min_value() { return InternalExtractorEdge::min_osm_value(); } }; +} +} + #endif // INTERNAL_EXTRACTOR_EDGE_HPP diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp index 27de18a67..f27fd656c 100644 --- a/include/extractor/node_id.hpp +++ b/include/extractor/node_id.hpp @@ -3,6 +3,11 @@ #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct Cmp { using value_type = OSMNodeID; @@ -11,4 +16,7 @@ struct Cmp value_type min_value() { return MIN_OSM_NODEID; } }; +} +} + #endif // NODE_ID_HPP diff --git a/include/extractor/original_edge_data.hpp b/include/extractor/original_edge_data.hpp index 77a3bb550..dd9273bb9 100644 --- a/include/extractor/original_edge_data.hpp +++ b/include/extractor/original_edge_data.hpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct OriginalEdgeData { explicit OriginalEdgeData(NodeID via_node, @@ -33,4 +38,7 @@ struct OriginalEdgeData TravelMode travel_mode; }; +} +} + #endif // ORIGINAL_EDGE_DATA_HPP diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index b32d92d64..512aeaca3 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct QueryNode { using key_type = OSMNodeID; // type of NodeID @@ -55,4 +60,7 @@ struct QueryNode } }; +} +} + #endif // QUERY_NODE_HPP diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index f04574cc9..a4707253c 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** \brief Small wrapper around raster source queries to optionally provide results gracefully, depending on source bounds @@ -40,7 +45,7 @@ class RasterGrid boost::filesystem::ifstream stream(filepath); if (!stream) { - throw osrm::exception("Unable to open raster file."); + throw util::exception("Unable to open raster file."); } stream.seekg(0, std::ios_base::end); @@ -65,13 +70,13 @@ class RasterGrid } catch (std::exception const &ex) { - throw osrm::exception( + throw util::exception( std::string("Failed to read from raster source with exception: ") + ex.what()); } if (!r || itr != end) { - throw osrm::exception("Failed to parse raster source correctly."); + throw util::exception("Failed to parse raster source correctly."); } } @@ -145,4 +150,7 @@ class SourceContainer std::unordered_map LoadedSourcePaths; }; +} +} + #endif /* RASTER_SOURCE_HPP */ diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index 5b22691dd..690d92b2b 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct TurnRestriction { union WayOrNode @@ -104,4 +109,7 @@ struct CmpRestrictionContainerByTo value_type min_value() const { return InputRestrictionContainer::min_value(); } }; +} +} + #endif // RESTRICTION_HPP diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index 81c9d425a..e5a6a12ba 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -12,6 +12,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + struct RestrictionSource { NodeID start_node; @@ -37,26 +42,33 @@ struct RestrictionTarget return (lhs.target_node == rhs.target_node && lhs.is_only == rhs.is_only); } }; +} +} namespace std { -template <> struct hash +template <> struct hash { - size_t operator()(const RestrictionSource &r_source) const + size_t operator()(const osrm::extractor::RestrictionSource &r_source) const { return hash_val(r_source.start_node, r_source.via_node); } }; -template <> struct hash +template <> struct hash { - size_t operator()(const RestrictionTarget &r_target) const + size_t operator()(const osrm::extractor::RestrictionTarget &r_target) const { return hash_val(r_target.target_node, r_target.is_only); } }; } + +namespace osrm +{ +namespace extractor +{ /** \brief Efficent look up if an edge is the start + via node of a TurnRestriction EdgeBasedEdgeFactory decides by it if edges are inserted or geometry is compressed @@ -146,4 +158,7 @@ class RestrictionMap std::unordered_set m_no_turn_via_node_set; }; +} +} + #endif // RESTRICTION_MAP_HPP diff --git a/include/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp index ee73f57ce..2bbad8268 100644 --- a/include/extractor/restriction_parser.hpp +++ b/include/extractor/restriction_parser.hpp @@ -14,6 +14,12 @@ namespace osmium class Relation; } + +namespace osrm +{ +namespace extractor +{ + /** * Parses the relations that represents turn restrictions. * @@ -47,4 +53,7 @@ class RestrictionParser bool use_turn_restrictions; }; +} +} + #endif /* RESTRICTION_PARSER_HPP */ diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index 3b1ff785a..0f1342b62 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -8,6 +8,11 @@ struct lua_State; +namespace osrm +{ +namespace extractor +{ + /** * Creates a lua context and binds osmium way, node and relation objects and * ExtractionWay and ExtractionNode to lua objects. @@ -30,4 +35,7 @@ class ScriptingEnvironment tbb::enumerable_thread_specific> script_contexts; }; +} +} + #endif /* SCRIPTING_ENVIRONMENT_HPP */ diff --git a/include/extractor/speed_profile.hpp b/include/extractor/speed_profile.hpp index ec8ecd6d4..65c4141b5 100644 --- a/include/extractor/speed_profile.hpp +++ b/include/extractor/speed_profile.hpp @@ -1,6 +1,11 @@ #ifndef SPEED_PROFILE_PROPERTIES_HPP #define SPEED_PROFILE_PROPERTIES_HPP +namespace osrm +{ +namespace extractor +{ + struct SpeedProfileProperties { SpeedProfileProperties() @@ -13,4 +18,7 @@ struct SpeedProfileProperties bool has_turn_penalty_function; }; +} +} + #endif diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index e29d0fad8..a8b8eb6ba 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -22,6 +22,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + template class TarjanSCC { struct TarjanStackFrame @@ -66,7 +71,7 @@ template class TarjanSCC unsigned component_index = 0, size_of_current_component = 0; unsigned index = 0; std::vector processing_node_before_recursion(max_node_id, true); - for (const NodeID node : osrm::irange(0u, max_node_id)) + for (const NodeID node : util::irange(0u, max_node_id)) { if (SPECIAL_NODEID == components_index[node]) { @@ -141,7 +146,7 @@ template class TarjanSCC if (size_of_current_component > 1000) { - SimpleLogger().Write() << "large component [" << component_index + util::SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } @@ -153,7 +158,7 @@ template class TarjanSCC } TIMER_STOP(SCC_RUN); - SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; + util::SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) @@ -174,4 +179,7 @@ template class TarjanSCC unsigned get_component_id(const NodeID node) const { return components_index[node]; } }; +} +} + #endif /* TARJAN_SCC_HPP */ diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index 66a84bbde..62fc03b92 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -1,10 +1,18 @@ #ifndef TRAVEL_MODE_HPP #define TRAVEL_MODE_HPP -namespace +namespace osrm { +namespace extractor +{ + using TravelMode = unsigned char; -static const TravelMode TRAVEL_MODE_INACCESSIBLE = 0; -static const TravelMode TRAVEL_MODE_DEFAULT = 1; + +} +} + +namespace { +static const osrm::extractor::TravelMode TRAVEL_MODE_INACCESSIBLE = 0; +static const osrm::extractor::TravelMode TRAVEL_MODE_DEFAULT = 1; } #endif /* TRAVEL_MODE_HPP */ diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index 2075d2c9c..ca3623504 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -1,6 +1,11 @@ #ifndef TURN_INSTRUCTIONS_HPP #define TURN_INSTRUCTIONS_HPP +namespace osrm +{ +namespace extractor +{ + enum class TurnInstruction : unsigned char { NoTurn = 0, @@ -75,4 +80,7 @@ struct TurnInstructionsClass } }; +} +} + #endif /* TURN_INSTRUCTIONS_HPP */ diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index 2ff3705ae..b36d57ca6 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -32,10 +32,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -namespace +namespace osrm { + constexpr static const double COORDINATE_PRECISION = 1000000.0; -} + +namespace util +{ struct FixedPointCoordinate { @@ -61,5 +64,10 @@ struct FixedPointCoordinate }; std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); +} + +using util::FixedPointCoordinate; + +} #endif /* COORDINATE_HPP_ */ diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index d8c49b223..7c8377d32 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -40,6 +40,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace osrm { + +namespace util +{ + namespace json { @@ -92,5 +96,12 @@ struct Array }; } // namespace JSON +} // namespace util + +namespace json { + using namespace osrm::util::json; +} + } // namespace osrm + #endif // JSON_CONTAINER_HPP diff --git a/include/osrm/libosrm_config.hpp b/include/osrm/libosrm_config.hpp index bc150077d..4606e6003 100644 --- a/include/osrm/libosrm_config.hpp +++ b/include/osrm/libosrm_config.hpp @@ -33,6 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ + struct LibOSRMConfig { std::unordered_map server_paths; @@ -43,4 +46,6 @@ struct LibOSRMConfig bool use_shared_memory = true; }; +} + #endif // SERVER_CONFIG_HPP diff --git a/include/osrm/osrm.hpp b/include/osrm/osrm.hpp index 892463d61..695403d73 100644 --- a/include/osrm/osrm.hpp +++ b/include/osrm/osrm.hpp @@ -30,17 +30,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -struct LibOSRMConfig; -struct RouteParameters; - namespace osrm { + +struct LibOSRMConfig; + +namespace util +{ namespace json { struct Object; } } +namespace engine { +struct RouteParameters; class OSRM { private: @@ -50,7 +54,12 @@ class OSRM public: OSRM(LibOSRMConfig &lib_config); ~OSRM(); // needed because we need to define it with the implementation of OSRM_impl - int RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result); + int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); }; +} + +using engine::OSRM; + +} #endif // OSRM_HPP diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 66b03ea65..f7bc2a261 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -36,6 +36,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ +namespace engine +{ + struct RouteParameters { RouteParameters(); @@ -115,4 +120,10 @@ struct RouteParameters std::vector is_source; }; +} + +using engine::RouteParameters; + +} + #endif // ROUTE_PARAMETERS_HPP diff --git a/include/osrm/strong_typedef.hpp b/include/osrm/strong_typedef.hpp index 7acc78509..f4c80865e 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/osrm/strong_typedef.hpp @@ -31,6 +31,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ + /* Creates strongly typed wrappers around scalar types. * Useful for stopping accidental assignment of lats to lons, * etc. Also clarifies what this random "int" value is @@ -66,4 +69,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. }; \ } +} + #endif // OSRM_STRONG_TYPEDEF_HPP diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index f4d937c68..7a04d884b 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -5,6 +5,11 @@ #include #include +namespace osrm +{ +namespace server +{ + namespace qi = boost::spirit::qi; template struct APIGrammar : qi::grammar @@ -98,4 +103,7 @@ template struct APIGrammar : qi::grammar T *get_pointer(std::shared_ptr &p) { return p.get(); } #endif -class RequestHandler; - -namespace http +namespace osrm { +namespace server +{ + +class RequestHandler; /// Represents a single connection from a client. class Connection : public std::enable_shared_from_this @@ -51,18 +53,19 @@ class Connection : public std::enable_shared_from_this void handle_write(const boost::system::error_code &e); std::vector compress_buffers(const std::vector &uncompressed_data, - const compression_type compression_type); + const http::compression_type compression_type); boost::asio::io_service::strand strand; boost::asio::ip::tcp::socket TCP_socket; RequestHandler &request_handler; RequestParser request_parser; boost::array incoming_data_buffer; - request current_request; - reply current_reply; + http::request current_request; + http::reply current_reply; std::vector compressed_output; }; -} // namespace http +} +} #endif // CONNECTION_HPP diff --git a/include/server/http/compression_type.hpp b/include/server/http/compression_type.hpp index ef7e8d75b..2a71cfa54 100644 --- a/include/server/http/compression_type.hpp +++ b/include/server/http/compression_type.hpp @@ -1,6 +1,10 @@ #ifndef COMPRESSION_TYPE_HPP #define COMPRESSION_TYPE_HPP +namespace osrm +{ +namespace server +{ namespace http { @@ -10,6 +14,9 @@ enum compression_type gzip_rfc1952, deflate_rfc1951 }; + +} +} } #endif // COMPRESSION_TYPE_HPP diff --git a/include/server/http/header.hpp b/include/server/http/header.hpp index 256e0b187..da43412bb 100644 --- a/include/server/http/header.hpp +++ b/include/server/http/header.hpp @@ -4,8 +4,13 @@ #include #include +namespace osrm +{ +namespace server +{ namespace http { + struct header { // explicitly use default copy c'tor as adding move c'tor @@ -22,6 +27,9 @@ struct header std::string name; std::string value; }; + +} +} } #endif // HEADER_HPP diff --git a/include/server/http/reply.hpp b/include/server/http/reply.hpp index 64c6e67b7..15ca91a13 100644 --- a/include/server/http/reply.hpp +++ b/include/server/http/reply.hpp @@ -7,8 +7,13 @@ #include +namespace osrm +{ +namespace server +{ namespace http { + class reply { public: @@ -33,6 +38,9 @@ class reply std::string status_to_string(reply::status_type status); boost::asio::const_buffer status_to_buffer(reply::status_type status); }; + +} +} } #endif // REPLY_HPP diff --git a/include/server/http/request.hpp b/include/server/http/request.hpp index 8b1a00df1..0e6fb7d59 100644 --- a/include/server/http/request.hpp +++ b/include/server/http/request.hpp @@ -5,6 +5,10 @@ #include +namespace osrm +{ +namespace server +{ namespace http { @@ -16,6 +20,8 @@ struct request boost::asio::ip::address endpoint; }; -} // namespace http +} +} +} #endif // REQUEST_HPP diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index 16a87acb0..66d2cd2b1 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -3,9 +3,16 @@ #include -template struct APIGrammar; -struct RouteParameters; +namespace osrm +{ +namespace engine +{ class OSRM; +struct RouteParameters; +} +namespace server +{ +template struct APIGrammar; namespace http { @@ -17,16 +24,19 @@ class RequestHandler { public: - using APIGrammarParser = APIGrammar; + using APIGrammarParser = APIGrammar; RequestHandler(); RequestHandler(const RequestHandler &) = delete; void handle_request(const http::request ¤t_request, http::reply ¤t_reply); - void RegisterRoutingMachine(OSRM *osrm); + void RegisterRoutingMachine(engine::OSRM *osrm); private: - OSRM *routing_machine; + engine::OSRM *routing_machine; }; +} +} + #endif // REQUEST_HANDLER_HPP diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index b498add0a..b4df13162 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -7,21 +7,27 @@ #include -namespace http +namespace osrm +{ +namespace server { +namespace http +{ struct request; +} + class RequestParser { public: RequestParser(); - std::tuple - parse(request ¤t_request, char *begin, char *end); + std::tuple + parse(http::request ¤t_request, char *begin, char *end); private: - osrm::tribool consume(request ¤t_request, const char input); + util::tribool consume(http::request ¤t_request, const char input); bool is_char(const int character) const; @@ -60,12 +66,13 @@ class RequestParser post_request } state; - header current_header; - compression_type selected_compression; + http::header current_header; + http::compression_type selected_compression; bool is_post_header; int content_length; }; -} // namespace http +} +} #endif // REQUEST_PARSER_HPP diff --git a/include/server/server.hpp b/include/server/server.hpp index f64a9f3bf..2d40a45b8 100644 --- a/include/server/server.hpp +++ b/include/server/server.hpp @@ -18,6 +18,11 @@ #include #include +namespace osrm +{ +namespace server +{ + class Server { public: @@ -25,7 +30,7 @@ class Server static std::shared_ptr CreateServer(std::string &ip_address, int ip_port, unsigned requested_num_threads) { - SimpleLogger().Write() << "http 1.1 compression handled by zlib version " << zlibVersion(); + util::SimpleLogger().Write() << "http 1.1 compression handled by zlib version " << zlibVersion(); const unsigned hardware_threads = std::max(1u, std::thread::hardware_concurrency()); const unsigned real_num_threads = std::min(hardware_threads, requested_num_threads); return std::make_shared(ip_address, ip_port, real_num_threads); @@ -33,7 +38,7 @@ class Server explicit Server(const std::string &address, const int port, const unsigned thread_pool_size) : thread_pool_size(thread_pool_size), acceptor(io_service), - new_connection(std::make_shared(io_service, request_handler)) + new_connection(std::make_shared(io_service, request_handler)) { const auto port_string = std::to_string(port); @@ -75,7 +80,7 @@ class Server if (!e) { new_connection->start(); - new_connection = std::make_shared(io_service, request_handler); + new_connection = std::make_shared(io_service, request_handler); acceptor.async_accept( new_connection->socket(), boost::bind(&Server::HandleAccept, this, boost::asio::placeholders::error)); @@ -85,8 +90,11 @@ class Server unsigned thread_pool_size; boost::asio::io_service io_service; boost::asio::ip::tcp::acceptor acceptor; - std::shared_ptr new_connection; + std::shared_ptr new_connection; RequestHandler request_handler; }; +} +} + #endif // SERVER_HPP diff --git a/include/util/bearing.hpp b/include/util/bearing.hpp index d881b300b..190e97a08 100644 --- a/include/util/bearing.hpp +++ b/include/util/bearing.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace bearing { inline std::string get(const double heading) @@ -86,4 +91,7 @@ inline bool CheckInBounds(const int A, const int B, const int range) } } +} +} + #endif // BEARING_HPP diff --git a/include/util/binary_heap.hpp b/include/util/binary_heap.hpp index 4b2ba07a2..c7d57505f 100644 --- a/include/util/binary_heap.hpp +++ b/include/util/binary_heap.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class ArrayStorage { public: @@ -286,4 +291,7 @@ class BinaryHeap } }; +} +} + #endif // BINARY_HEAP_H diff --git a/include/util/cast.hpp b/include/util/cast.hpp index 94862d2ba..479eaa2a4 100644 --- a/include/util/cast.hpp +++ b/include/util/cast.hpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace cast { template @@ -39,4 +44,7 @@ template inline std::string to_string_with_preci } } +} +} + #endif // CAST_HPP diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index 48300e4f4..40f820d9e 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -1,6 +1,11 @@ #ifndef COMPUTE_ANGLE_HPP #define COMPUTE_ANGLE_HPP +namespace osrm +{ +namespace util +{ + struct FixedPointCoordinate; struct ComputeAngle @@ -12,4 +17,7 @@ struct ComputeAngle const FixedPointCoordinate &third) noexcept; }; +} +} + #endif // COMPUTE_ANGLE_HPP diff --git a/include/util/container.hpp b/include/util/container.hpp index fab0c2263..e901af90d 100644 --- a/include/util/container.hpp +++ b/include/util/container.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + namespace detail { // Culled by SFINAE if reserve does not exist or is not accessible @@ -81,4 +84,6 @@ void append_to_container(Container &&container, T value, Args &&... args) } } // namespace osrm +} + #endif /* CONTAINER_HPP */ diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 7faabdbc6..96548481b 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -1,11 +1,16 @@ #ifndef COORDINATE_CALCULATION #define COORDINATE_CALCULATION -struct FixedPointCoordinate; - #include #include +namespace osrm +{ +namespace util +{ + +struct FixedPointCoordinate; + namespace coordinate_calculation { double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2); @@ -49,4 +54,7 @@ double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); } +} +} + #endif // COORDINATE_CALCULATION diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index 8426fa13b..b467bb836 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // generate boost::program_options object for the routing part bool GenerateDataStoreOptions(const int argc, const char *argv[], @@ -199,59 +204,62 @@ bool GenerateDataStoreOptions(const int argc, if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .hsgr file must be specified"); + throw exception("valid .hsgr file must be specified"); } path_iterator = paths.find("nodesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .nodes file must be specified"); + throw exception("valid .nodes file must be specified"); } path_iterator = paths.find("edgesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .edges file must be specified"); + throw exception("valid .edges file must be specified"); } path_iterator = paths.find("geometry"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .geometry file must be specified"); + throw exception("valid .geometry file must be specified"); } path_iterator = paths.find("ramindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .ramindex file must be specified"); + throw exception("valid .ramindex file must be specified"); } path_iterator = paths.find("fileindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .fileindex file must be specified"); + throw exception("valid .fileindex file must be specified"); } path_iterator = paths.find("namesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .names file must be specified"); + throw exception("valid .names file must be specified"); } path_iterator = paths.find("timestamp"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .timestamp file must be specified"); + throw exception("valid .timestamp file must be specified"); } return true; } +} +} + #endif /* DATASTORE_OPTIONS_HPP */ diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index a486db371..aa9ec3ea2 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template struct ConstDeallocatingVectorIteratorState { ConstDeallocatingVectorIteratorState() @@ -302,7 +307,7 @@ class DeallocatingVector { // down-size const std::size_t number_of_necessary_buckets = 1 + (new_size / ELEMENTS_PER_BLOCK); for (const auto bucket_index : - osrm::irange(number_of_necessary_buckets, bucket_list.size())) + irange(number_of_necessary_buckets, bucket_list.size())) { if (nullptr != bucket_list[bucket_index]) { @@ -374,4 +379,7 @@ void swap(DeallocatingVector &lhs, DeallocatingVector &rhs) lhs.swap(rhs); } +} +} + #endif /* DEALLOCATING_VECTOR_HPP */ diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index d4cd06871..b06ed3dc6 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -6,7 +6,12 @@ #ifndef DEBUG_GEOMETRY -inline void DEBUG_GEOMETRY_START(ContractorConfig & /* config */) {} +namespace osrm +{ +namespace util +{ + +inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig & /* config */) {} inline void DEBUG_GEOMETRY_EDGE(int /* new_segment_weight */, double /* segment_length */, OSMNodeID /* previous_osm_node_id */, @@ -17,25 +22,28 @@ inline void DEBUG_GEOMETRY_STOP() {} inline void DEBUG_TURNS_START(const std::string & /* debug_turns_filename */) {} inline void DEBUG_TURN(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const FixedPointCoordinate & /* first_coordinate */, const int /* turn_angle */, const int /* turn_penalty */) { } inline void DEBUG_UTURN(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const int /* uturn_penalty */) { } inline void DEBUG_SIGNAL(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const int /* signal_penalty */) { } inline void DEBUG_TURNS_STOP() {} +} +} + #else // DEBUG_GEOMETRY #include @@ -47,6 +55,12 @@ inline void DEBUG_TURNS_STOP() {} #include "util/coordinate.hpp" #include "util/coordinate_calculation.hpp" +namespace osrm +{ +namespace util +{ + + boost::filesystem::ofstream debug_geometry_file; bool dg_output_debug_geometry = false; bool dg_first_debug_geometry = true; @@ -56,7 +70,7 @@ boost::filesystem::ofstream dg_debug_turns_file; bool dg_output_turn_debug = false; bool dg_first_turn_debug = true; -inline void DEBUG_GEOMETRY_START(const ContractorConfig &config) +inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig &config) { time_t raw_time; struct tm *timeinfo; @@ -118,12 +132,12 @@ inline void DEBUG_TURNS_START(const std::string &debug_turns_path) } inline void DEBUG_SIGNAL(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const int traffic_signal_penalty) { if (dg_output_turn_debug) { - const QueryNode &nodeinfo = m_node_info_list[node]; + const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; dg_debug_turns_file @@ -137,12 +151,12 @@ inline void DEBUG_SIGNAL(const NodeID node, } inline void DEBUG_UTURN(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const int traffic_signal_penalty) { if (dg_output_turn_debug) { - const QueryNode &nodeinfo = m_node_info_list[node]; + const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; dg_debug_turns_file @@ -156,14 +170,14 @@ inline void DEBUG_UTURN(const NodeID node, } inline void DEBUG_TURN(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const FixedPointCoordinate &first_coordinate, const int turn_angle, const int turn_penalty) { if (turn_penalty > 0 && dg_output_turn_debug) { - const QueryNode &v = m_node_info_list[node]; + const extractor::QueryNode &v = m_node_info_list[node]; const float bearing_uv = coordinate_calculation::bearing(first_coordinate, v); float uvw_normal = bearing_uv + turn_angle / 2; @@ -194,6 +208,9 @@ inline void DEBUG_TURNS_STOP() } } +} +} + #endif // DEBUG_GEOMETRY #endif // DEBUG_GEOMETRY_H diff --git a/include/util/dist_table_wrapper.hpp b/include/util/dist_table_wrapper.hpp index 516131393..3e23ce2ac 100644 --- a/include/util/dist_table_wrapper.hpp +++ b/include/util/dist_table_wrapper.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // This Wrapper provides an easier access to a distance table that is given as an linear vector template class DistTableWrapper @@ -58,4 +63,7 @@ template class DistTableWrapper const std::size_t number_of_nodes_; }; +} +} + #endif // DIST_TABLE_WRAPPER_H diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index 4dd2f0022..c4219cf28 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -15,13 +15,18 @@ #include #include +namespace osrm +{ +namespace util +{ + template class DynamicGraph { public: using EdgeData = EdgeDataT; using NodeIterator = unsigned; using EdgeIterator = unsigned; - using EdgeRange = osrm::range; + using EdgeRange = range; class InputEdge { @@ -72,7 +77,7 @@ template class DynamicGraph node_array.resize(number_of_nodes + 1); EdgeIterator edge = 0; EdgeIterator position = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) @@ -87,9 +92,9 @@ template class DynamicGraph edge_list.reserve(static_cast(edge_list.size() * 1.1)); edge_list.resize(position); edge = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { - for (const auto i : osrm::irange(node_array[node].first_edge, + for (const auto i : irange(node_array[node].first_edge, node_array[node].first_edge + node_array[node].edges)) { edge_list[i].target = graph[edge].target; @@ -111,7 +116,7 @@ template class DynamicGraph unsigned GetDirectedOutDegree(const NodeIterator n) const { unsigned degree = 0; - for (const auto edge : osrm::irange(BeginEdges(n), EndEdges(n))) + for (const auto edge : irange(BeginEdges(n), EndEdges(n))) { if (!GetEdgeData(edge).reversed) { @@ -141,7 +146,7 @@ template class DynamicGraph EdgeRange GetAdjacentEdgeRange(const NodeIterator node) const { - return osrm::irange(BeginEdges(node), EndEdges(node)); + return irange(BeginEdges(node), EndEdges(node)); } NodeIterator InsertNode() @@ -175,12 +180,12 @@ template class DynamicGraph edge_list.reserve(requiredCapacity * 1.1); } edge_list.resize(edge_list.size() + newSize); - for (const auto i : osrm::irange(0u, node.edges)) + for (const auto i : irange(0u, node.edges)) { edge_list[newFirstEdge + i] = edge_list[node.first_edge + i]; makeDummy(node.first_edge + i); } - for (const auto i : osrm::irange(node.edges + 1, newSize)) + for (const auto i : irange(node.edges + 1, newSize)) { makeDummy(newFirstEdge + i); } @@ -235,7 +240,7 @@ template class DynamicGraph // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { - for (const auto i : osrm::irange(BeginEdges(from), EndEdges(from))) + for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_list[i].target) { @@ -316,4 +321,7 @@ template class DynamicGraph DeallocatingVector edge_list; }; +} +} + #endif // DYNAMICGRAPH_HPP diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index bb58fe697..14b869871 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // implements a singleton, i.e. there is one and only one conviguration object class FingerPrint { @@ -29,4 +34,7 @@ class FingerPrint static_assert(std::is_trivial::value, "FingerPrint needs to be trivial."); +} +} + #endif /* FingerPrint_H */ diff --git a/include/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in index 85fcebdb0..f391e4ca2 100644 --- a/include/util/fingerprint_impl.hpp.in +++ b/include/util/fingerprint_impl.hpp.in @@ -13,6 +13,11 @@ #cmakedefine MD5GRAPH "${MD5GRAPH}" #cmakedefine MD5OBJECTS "${MD5OBJECTS}" +namespace osrm +{ +namespace util +{ + FingerPrint FingerPrint::GetValid() { FingerPrint fingerprint; @@ -52,7 +57,7 @@ bool FingerPrint::TestGraphUtil(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("hsgr input file misses magic number. Check or reprocess the file"); + throw exception("hsgr input file misses magic number. Check or reprocess the file"); } return std::equal(md5_graph, md5_graph + 32, other.md5_graph); } @@ -61,7 +66,7 @@ bool FingerPrint::TestPrepare(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("osrm input file misses magic number. Check or reprocess the file"); + throw exception("osrm input file misses magic number. Check or reprocess the file"); } return std::equal(md5_prepare, md5_prepare + 32, other.md5_prepare); } @@ -70,7 +75,7 @@ bool FingerPrint::TestRTree(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("r-tree input file misses magic number. Check or reprocess the file"); + throw exception("r-tree input file misses magic number. Check or reprocess the file"); } return std::equal(md5_tree, md5_tree + 32, other.md5_tree); } @@ -79,7 +84,10 @@ bool FingerPrint::TestQueryObjects(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("missing magic number. Check or reprocess the file"); + throw exception("missing magic number. Check or reprocess the file"); } return std::equal(md5_objects, md5_objects + 32, other.md5_objects); } + +} +} diff --git a/include/util/fixed_point_number.hpp b/include/util/fixed_point_number.hpp index 0ff409fc8..ba4b111db 100644 --- a/include/util/fixed_point_number.hpp +++ b/include/util/fixed_point_number.hpp @@ -11,6 +11,8 @@ namespace osrm { +namespace util +{ // implements an binary based fixed point number type template ), "FP19 has wrong size != 4"); + } +} + #endif // FIXED_POINT_NUMBER_HPP diff --git a/include/util/floating_point.hpp b/include/util/floating_point.hpp index 79ec495bd..e7963e630 100644 --- a/include/util/floating_point.hpp +++ b/include/util/floating_point.hpp @@ -8,11 +8,16 @@ namespace osrm { +namespace util +{ + template bool epsilon_compare(const FloatT number1, const FloatT number2) { static_assert(std::is_floating_point::value, "type must be floating point"); return (std::abs(number1 - number2) < std::numeric_limits::epsilon()); } + +} } #endif // FLOATING_POINT_HPP diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index c64048ede..6ff030b5a 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -22,13 +22,18 @@ #include #include +namespace osrm +{ +namespace util +{ + /** * Reads the .restrictions file and loads it to a vector. * The since the restrictions reference nodes using their external node id, * we need to renumber it to the new internal id. */ unsigned loadRestrictionsFromFile(std::istream &input_stream, - std::vector &restriction_list) + std::vector &restriction_list) { const FingerPrint fingerprint_valid = FingerPrint::GetValid(); FingerPrint fingerprint_loaded; @@ -45,7 +50,7 @@ unsigned loadRestrictionsFromFile(std::istream &input_stream, if (number_of_usable_restrictions > 0) { input_stream.read((char *)restriction_list.data(), - number_of_usable_restrictions * sizeof(TurnRestriction)); + number_of_usable_restrictions * sizeof(extractor::TurnRestriction)); } return number_of_usable_restrictions; @@ -60,7 +65,7 @@ unsigned loadRestrictionsFromFile(std::istream &input_stream, NodeID loadNodesFromFile(std::istream &input_stream, std::vector &barrier_node_list, std::vector &traffic_light_node_list, - std::vector &node_array) + std::vector &node_array) { const FingerPrint fingerprint_valid = FingerPrint::GetValid(); FingerPrint fingerprint_loaded; @@ -76,10 +81,10 @@ NodeID loadNodesFromFile(std::istream &input_stream, input_stream.read(reinterpret_cast(&n), sizeof(NodeID)); SimpleLogger().Write() << "Importing n = " << n << " nodes "; - ExternalMemoryNode current_node; + extractor::ExternalMemoryNode current_node; for (NodeID i = 0; i < n; ++i) { - input_stream.read(reinterpret_cast(¤t_node), sizeof(ExternalMemoryNode)); + input_stream.read(reinterpret_cast(¤t_node), sizeof(extractor::ExternalMemoryNode)); node_array.emplace_back(current_node.lat, current_node.lon, current_node.node_id); if (current_node.barrier) { @@ -101,21 +106,21 @@ NodeID loadNodesFromFile(std::istream &input_stream, /** * Reads a .osrm file and produces the edges. */ -NodeID loadEdgesFromFile(std::istream &input_stream, std::vector &edge_list) +NodeID loadEdgesFromFile(std::istream &input_stream, std::vector &edge_list) { EdgeID m; input_stream.read(reinterpret_cast(&m), sizeof(unsigned)); edge_list.resize(m); SimpleLogger().Write() << " and " << m << " edges "; - input_stream.read((char *)edge_list.data(), m * sizeof(NodeBasedEdge)); + input_stream.read((char *)edge_list.data(), m * sizeof(extractor::NodeBasedEdge)); BOOST_ASSERT(edge_list.size() > 0); #ifndef NDEBUG SimpleLogger().Write() << "Validating loaded edges..."; tbb::parallel_sort(edge_list.begin(), edge_list.end(), - [](const NodeBasedEdge &lhs, const NodeBasedEdge &rhs) + [](const extractor::NodeBasedEdge &lhs, const extractor::NodeBasedEdge &rhs) { return (lhs.source < rhs.source) || (lhs.source == rhs.source && lhs.target < rhs.target); @@ -148,11 +153,11 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file, { if (!boost::filesystem::exists(hsgr_file)) { - throw osrm::exception("hsgr file does not exist"); + throw exception("hsgr file does not exist"); } if (0 == boost::filesystem::file_size(hsgr_file)) { - throw osrm::exception("hsgr file is empty"); + throw exception("hsgr file is empty"); } boost::filesystem::ifstream hsgr_input_stream(hsgr_file, std::ios::binary); @@ -192,4 +197,7 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file, return number_of_nodes; } +} +} + #endif // GRAPH_LOADER_HPP diff --git a/include/util/graph_utils.hpp b/include/util/graph_utils.hpp index 7c907ff22..c2165c5b6 100644 --- a/include/util/graph_utils.hpp +++ b/include/util/graph_utils.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + /// This function checks if the graph (consisting of directed edges) is undirected template bool isUndirectedGraph(const GraphT &graph) { @@ -91,4 +96,7 @@ std::vector directedEdgesFromCompressed(const std::vector +namespace osrm +{ +namespace util +{ + // computes a 64 bit value that corresponds to the hilbert space filling curve struct FixedPointCoordinate; @@ -19,4 +24,7 @@ class HilbertCode inline void TransposeCoordinate(uint32_t *X) const; }; +} +} + #endif /* HILBERT_VALUE_HPP */ diff --git a/include/util/ini_file.hpp b/include/util/ini_file.hpp index a99962f52..1ccc302e8 100644 --- a/include/util/ini_file.hpp +++ b/include/util/ini_file.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace { @@ -21,4 +26,7 @@ std::string read_file_lower_content(const boost::filesystem::path &path) return ini_file_content; } } +} +} + #endif // INI_FILE_HPP diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index 6c27b55dc..cba88ad92 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -9,6 +9,8 @@ namespace osrm { +namespace util +{ template class range { @@ -45,6 +47,8 @@ irange(const Integer first, { return range(first, last); } + +} } #endif // INTEGER_RANGE_HPP diff --git a/include/util/iso_8601_duration_parser.hpp b/include/util/iso_8601_duration_parser.hpp index aded519f9..493149c01 100644 --- a/include/util/iso_8601_duration_parser.hpp +++ b/include/util/iso_8601_duration_parser.hpp @@ -5,6 +5,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace qi = boost::spirit::qi; template struct iso_8601_grammar : qi::grammar @@ -72,4 +77,7 @@ template struct iso_8601_grammar : qi::grammar } }; +} +} + #endif // ISO_8601_DURATION_PARSER_HPP diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index cb3333f70..6b81cc6fc 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -10,6 +10,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -17,7 +19,7 @@ namespace json // thread safe manner. class Logger { - using MapT = std::unordered_map; + using MapT = std::unordered_map; public: static Logger *get() @@ -53,6 +55,8 @@ class Logger boost::thread_specific_ptr map; }; + +} } } diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index b0e7de640..9f6656053 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -11,6 +11,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -156,5 +158,7 @@ inline void render(std::vector &out, const Object &object) } } // namespace json +} // namespace util } // namespace osrm + #endif // JSON_RENDERER_HPP diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index d1eb7ae3f..2cf012eb2 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -8,6 +8,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -26,16 +28,16 @@ template T clamp_float(T d) return d; } -template osrm::json::Array make_array(Args... args) +template Array make_array(Args... args) { - osrm::json::Array a; + Array a; append_to_container(a.values, args...); return a; } -template osrm::json::Array make_array(const std::vector &vector) +template Array make_array(const std::vector &vector) { - osrm::json::Array a; + Array a; for (const auto &v : vector) { a.values.emplace_back(v); @@ -44,9 +46,9 @@ template osrm::json::Array make_array(const std::vector &vector) } // template specialization needed as clang does not play nice -template <> osrm::json::Array make_array(const std::vector &vector) +template <> Array make_array(const std::vector &vector) { - osrm::json::Array a; + Array a; for (const bool v : vector) { a.values.emplace_back(v); @@ -55,22 +57,24 @@ template <> osrm::json::Array make_array(const std::vector &vector) } // Easy acces to object hierachies -osrm::json::Value &get(osrm::json::Value &value) { return value; } +Value &get(Value &value) { return value; } template -osrm::json::Value &get(osrm::json::Value &value, const char *key, Keys... keys) +Value &get(Value &value, const char *key, Keys... keys) { - using recursive_object_t = mapbox::util::recursive_wrapper; + using recursive_object_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); } template -osrm::json::Value &get(osrm::json::Value &value, unsigned key, Keys... keys) +Value &get(Value &value, unsigned key, Keys... keys) { - using recursive_array_t = mapbox::util::recursive_wrapper; + using recursive_array_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); } } // namespace json +} // namespace util } // namespace osrm + #endif // JSON_UTIL_HPP diff --git a/include/util/lua_util.hpp b/include/util/lua_util.hpp index f45dbffa1..47339fdd8 100644 --- a/include/util/lua_util.hpp +++ b/include/util/lua_util.hpp @@ -13,6 +13,11 @@ extern "C" { #include #include +namespace osrm +{ +namespace util +{ + template void LUA_print(T output) { std::cout << "[LUA] " << output << std::endl; } // Check if the lua function is defined @@ -35,4 +40,7 @@ inline void luaAddScriptFolderToLoadPath(lua_State *lua_state, const char *file_ luaL_dostring(lua_state, lua_code.c_str()); } +} +} + #endif // LUA_UTIL_HPP diff --git a/include/util/make_unique.hpp b/include/util/make_unique.hpp index 9c42ac520..09a1dd924 100644 --- a/include/util/make_unique.hpp +++ b/include/util/make_unique.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + // Implement make_unique according to N3656. Taken from libcxx's implementation /// \brief Constructs a `new T()` with the given args and returns a @@ -42,5 +45,8 @@ make_unique(size_t n) /// This function isn't used and is only here to provide better compile errors. template typename std::enable_if::value != 0>::type make_unique(Args &&...) = delete; + } +} + #endif // MAKE_UNIQUE_H_ diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index 37f99403d..dc8e561d7 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -7,10 +7,15 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace util +{ + // Provides the debug interface for introspection tools struct MatchingDebugInfo { - MatchingDebugInfo(const osrm::json::Logger *logger) : logger(logger) + MatchingDebugInfo(const json::Logger *logger) : logger(logger) { if (logger) { @@ -26,25 +31,25 @@ struct MatchingDebugInfo return; } - osrm::json::Array states; + json::Array states; for (auto &elem : candidates_list) { - osrm::json::Array timestamps; + json::Array timestamps; for (auto &elem_s : elem) { - osrm::json::Object state; - state.values["transitions"] = osrm::json::Array(); + json::Object state; + state.values["transitions"] = json::Array(); state.values["coordinate"] = - osrm::json::make_array(elem_s.phantom_node.location.lat / COORDINATE_PRECISION, + json::make_array(elem_s.phantom_node.location.lat / COORDINATE_PRECISION, elem_s.phantom_node.location.lon / COORDINATE_PRECISION); state.values["viterbi"] = - osrm::json::clamp_float(osrm::matching::IMPOSSIBLE_LOG_PROB); + json::clamp_float(engine::map_matching::IMPOSSIBLE_LOG_PROB); state.values["pruned"] = 0u; timestamps.values.push_back(state); } states.values.push_back(timestamps); } - osrm::json::get(*object, "states") = states; + json::get(*object, "states") = states; } void add_transition_info(const unsigned prev_t, @@ -63,14 +68,14 @@ struct MatchingDebugInfo return; } - osrm::json::Object transistion; - transistion.values["to"] = osrm::json::make_array(current_t, current_state); - transistion.values["properties"] = osrm::json::make_array( - osrm::json::clamp_float(prev_viterbi), osrm::json::clamp_float(emission_pr), - osrm::json::clamp_float(transition_pr), network_distance, haversine_distance); + json::Object transistion; + transistion.values["to"] = json::make_array(current_t, current_state); + transistion.values["properties"] = json::make_array( + json::clamp_float(prev_viterbi), json::clamp_float(emission_pr), + json::clamp_float(transition_pr), network_distance, haversine_distance); - osrm::json::get(*object, "states", prev_t, prev_state, "transitions") - .get>() + json::get(*object, "states", prev_t, prev_state, "transitions") + .get>() .get() .values.push_back(transistion); } @@ -89,11 +94,11 @@ struct MatchingDebugInfo { for (auto s_prime = 0u; s_prime < viterbi[t].size(); ++s_prime) { - osrm::json::get(*object, "states", t, s_prime, "viterbi") = - osrm::json::clamp_float(viterbi[t][s_prime]); - osrm::json::get(*object, "states", t, s_prime, "pruned") = + json::get(*object, "states", t, s_prime, "viterbi") = + json::clamp_float(viterbi[t][s_prime]); + json::get(*object, "states", t, s_prime, "pruned") = static_cast(pruned[t][s_prime]); - osrm::json::get(*object, "states", t, s_prime, "suspicious") = + json::get(*object, "states", t, s_prime, "suspicious") = static_cast(suspicious[t][s_prime]); } } @@ -107,7 +112,7 @@ struct MatchingDebugInfo return; } - osrm::json::get(*object, "states", t, s, "chosen") = true; + json::get(*object, "states", t, s, "chosen") = true; } void add_breakage(const std::vector &breakage) @@ -118,11 +123,14 @@ struct MatchingDebugInfo return; } - osrm::json::get(*object, "breakage") = osrm::json::make_array(breakage); + json::get(*object, "breakage") = json::make_array(breakage); } - const osrm::json::Logger *logger; - osrm::json::Value *object; + const json::Logger *logger; + json::Value *object; }; +} +} + #endif // MATCHING_DEBUG_INFO_HPP diff --git a/include/util/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp index b6aada34b..11b1f2586 100644 --- a/include/util/matrix_graph_wrapper.hpp +++ b/include/util/matrix_graph_wrapper.hpp @@ -7,7 +7,12 @@ #include "util/typedefs.hpp" -// This Wrapper provides all methods that are needed for TarjanSCC, when the graph is given in a +namespace osrm +{ +namespace util +{ + +// This Wrapper provides all methods that are needed for extractor::TarjanSCC, when the graph is given in a // matrix representation (e.g. as output from a distance table call) template class MatrixGraphWrapper @@ -40,4 +45,7 @@ template class MatrixGraphWrapper const std::size_t number_of_nodes_; }; +} +} + #endif // MATRIX_GRAPH_WRAPPER_H diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp index e338d9b1b..230c1ad23 100644 --- a/include/util/mercator.hpp +++ b/include/util/mercator.hpp @@ -1,6 +1,11 @@ #ifndef MERCATOR_HPP #define MERCATOR_HPP +namespace osrm +{ +namespace util +{ + struct mercator { static double y2lat(const double value) noexcept; @@ -8,4 +13,7 @@ struct mercator static double lat2y(const double latitude) noexcept; }; +} +} + #endif // MERCATOR_HPP diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index 51842ebbe..09b082496 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace util +{ + struct NodeBasedEdgeData { NodeBasedEdgeData() @@ -25,7 +30,7 @@ struct NodeBasedEdgeData bool reversed, bool roundabout, bool startpoint, - TravelMode travel_mode) + extractor::TravelMode travel_mode) : distance(distance), edge_id(edge_id), name_id(name_id), access_restricted(access_restricted), reversed(reversed), roundabout(roundabout), startpoint(startpoint), travel_mode(travel_mode) @@ -39,7 +44,7 @@ struct NodeBasedEdgeData bool reversed : 1; bool roundabout : 1; bool startpoint : 1; - TravelMode travel_mode : 4; + extractor::TravelMode travel_mode : 4; bool IsCompatibleTo(const NodeBasedEdgeData &other) const { @@ -55,11 +60,11 @@ using NodeBasedDynamicGraph = DynamicGraph; /// two edges for undirected edges. inline std::shared_ptr NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, - const std::vector &input_edge_list) + const std::vector &input_edge_list) { auto edges_list = directedEdgesFromCompressed( input_edge_list, - [](NodeBasedDynamicGraph::InputEdge &output_edge, const NodeBasedEdge &input_edge) + [](NodeBasedDynamicGraph::InputEdge &output_edge, const extractor::NodeBasedEdge &input_edge) { output_edge.data.distance = static_cast(input_edge.weight); BOOST_ASSERT(output_edge.data.distance > 0); @@ -79,4 +84,7 @@ NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, return graph; } +} +} + #endif // NODE_BASED_GRAPH_HPP diff --git a/include/util/osrm_exception.hpp b/include/util/osrm_exception.hpp index a776f84fd..fc84cb981 100644 --- a/include/util/osrm_exception.hpp +++ b/include/util/osrm_exception.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + class exception final : public std::exception { public: @@ -21,5 +24,8 @@ class exception final : public std::exception const char *what() const noexcept override { return message.c_str(); } const std::string message; }; + } +} + #endif /* OSRM_EXCEPTION_HPP */ diff --git a/include/util/percent.hpp b/include/util/percent.hpp index bcca00e3c..4f0d0e72c 100644 --- a/include/util/percent.hpp +++ b/include/util/percent.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + class Percent { public: @@ -71,4 +76,7 @@ class Percent } }; +} +} + #endif // PERCENT_HPP diff --git a/include/util/range_algorithms.hpp b/include/util/range_algorithms.hpp index f821bf8ef..47393b523 100644 --- a/include/util/range_algorithms.hpp +++ b/include/util/range_algorithms.hpp @@ -5,6 +5,8 @@ namespace osrm { +namespace util +{ template auto max_element(const Container &c) -> decltype(std::max_element(c.begin(), c.end())) @@ -17,6 +19,8 @@ auto max_element(const Container &c) -> decltype(std::max_element(c.cbegin(), c. { return std::max_element(c.cbegin(), c.cend()); } + +} } #endif // RANGE_ALGORITHMS_HPP diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index 9e40f6b4c..97cbc3abe 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -7,6 +7,11 @@ #include #include + +namespace osrm +{ +namespace util +{ /* * These pre-declarations are needed because parsing C++ is hard * and otherwise the compiler gets confused. @@ -35,7 +40,7 @@ template class RangeTable using BlockT = std::array; using BlockContainerT = typename ShM::vector; using OffsetContainerT = typename ShM::vector; - using RangeT = osrm::range; + using RangeT = range; friend std::ostream &operator<<<>(std::ostream &out, const RangeTable &table); friend std::istream &operator>><>(std::istream &in, RangeTable &table); @@ -166,7 +171,7 @@ template class RangeTable BOOST_ASSERT(begin_idx < sum_lengths && end_idx <= sum_lengths); BOOST_ASSERT(begin_idx <= end_idx); - return osrm::irange(begin_idx, end_idx); + return irange(begin_idx, end_idx); } private: @@ -229,4 +234,7 @@ std::istream &operator>>(std::istream &in, RangeTable #include +namespace osrm +{ +namespace util +{ + // TODO: Make template type, add tests struct RectangleInt2D { @@ -173,4 +178,7 @@ struct RectangleInt2D } }; +} +} + #endif diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 8085c3aa5..f1a55c8fb 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -12,6 +12,11 @@ #include #include #include + +namespace osrm +{ +namespace util +{ const static unsigned INIT_OK_START_ENGINE = 0; const static unsigned INIT_OK_DO_NOT_START_ENGINE = 1; const static unsigned INIT_FAILED = -1; @@ -53,49 +58,49 @@ populate_base_path(std::unordered_map &ser if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".hsgr not found"); + throw exception(".hsgr not found"); } path_iterator = server_paths.find("nodesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".nodes not found"); + throw exception(".nodes not found"); } path_iterator = server_paths.find("edgesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".edges not found"); + throw exception(".edges not found"); } path_iterator = server_paths.find("geometries"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".geometry not found"); + throw exception(".geometry not found"); } path_iterator = server_paths.find("ramindex"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".ramIndex not found"); + throw exception(".ramIndex not found"); } path_iterator = server_paths.find("fileindex"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".fileIndex not found"); + throw exception(".fileIndex not found"); } path_iterator = server_paths.find("namesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".namesIndex not found"); + throw exception(".namesIndex not found"); } SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; @@ -226,15 +231,15 @@ GenerateServerProgramOptions(const int argc, if (1 > requested_num_threads) { - throw osrm::exception("Number of threads must be a positive number"); + throw exception("Number of threads must be a positive number"); } if (2 > max_locations_distance_table) { - throw osrm::exception("Max location for distance table must be at least two"); + throw exception("Max location for distance table must be at least two"); } if (2 > max_locations_map_matching) { - throw osrm::exception("Max location for map matching must be at least two"); + throw exception("Max location for map matching must be at least two"); } if (!use_shared_memory && option_variables.count("base")) @@ -254,4 +259,7 @@ GenerateServerProgramOptions(const int argc, return INIT_OK_DO_NOT_START_ENGINE; } +} +} + #endif // ROUTED_OPTIONS_HPP diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index fef9c78e7..ab651745d 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class ShMemIterator : public std::iterator { DataT *p; @@ -124,4 +129,7 @@ template struct ShM std::vector>::type; }; +} +} + #endif // SHARED_MEMORY_VECTOR_WRAPPER_HPP diff --git a/include/util/simple_logger.hpp b/include/util/simple_logger.hpp index 041225abe..0b33f51fa 100644 --- a/include/util/simple_logger.hpp +++ b/include/util/simple_logger.hpp @@ -12,6 +12,11 @@ enum LogLevel logDEBUG }; +namespace osrm +{ +namespace util +{ + class LogPolicy { public: @@ -44,4 +49,7 @@ class SimpleLogger LogLevel level; }; +} +} + #endif /* SIMPLE_LOGGER_HPP */ diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index e8270409f..744dabb8b 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -13,13 +13,18 @@ #include #include +namespace osrm +{ +namespace util +{ + template class StaticGraph { public: using NodeIterator = NodeID; using EdgeIterator = NodeID; using EdgeData = EdgeDataT; - using EdgeRange = osrm::range; + using EdgeRange = range; class InputEdge { @@ -57,7 +62,7 @@ template class StaticGraph EdgeRange GetAdjacentEdgeRange(const NodeID node) const { - return osrm::irange(BeginEdges(node), EndEdges(node)); + return irange(BeginEdges(node), EndEdges(node)); } template StaticGraph(const int nodes, const ContainerT &graph) @@ -70,7 +75,7 @@ template class StaticGraph node_array.resize(number_of_nodes + 1); EdgeIterator edge = 0; EdgeIterator position = 0; - for (const auto node : osrm::irange(0u, number_of_nodes + 1)) + for (const auto node : irange(0u, number_of_nodes + 1)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) @@ -82,10 +87,10 @@ template class StaticGraph } edge_array.resize(position); //(edge) edge = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator e = node_array[node + 1].first_edge; - for (const auto i : osrm::irange(node_array[node].first_edge, e)) + for (const auto i : irange(node_array[node].first_edge, e)) { edge_array[i].target = graph[edge].target; edge_array[i].data = graph[edge].data; @@ -132,7 +137,7 @@ template class StaticGraph // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { - for (const auto i : osrm::irange(BeginEdges(from), EndEdges(from))) + for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_array[i].target) { @@ -189,4 +194,7 @@ template class StaticGraph typename ShM::vector edge_array; }; +} +} + #endif // STATIC_GRAPH_HPP diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index ef8f9e839..0b244f167 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -32,6 +32,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // Static RTree for serving nearest neighbour queries template , @@ -265,11 +270,11 @@ class StaticRTree if (!boost::filesystem::exists(node_file)) { - throw osrm::exception("ram index file does not exist"); + throw exception("ram index file does not exist"); } if (0 == boost::filesystem::file_size(node_file)) { - throw osrm::exception("ram index file is empty"); + throw exception("ram index file is empty"); } boost::filesystem::ifstream tree_node_file(node_file, std::ios::binary); @@ -285,11 +290,11 @@ class StaticRTree // open leaf node file and store thread specific pointer if (!boost::filesystem::exists(leaf_file)) { - throw osrm::exception("mem index file does not exist"); + throw exception("mem index file does not exist"); } if (0 == boost::filesystem::file_size(leaf_file)) { - throw osrm::exception("mem index file is empty"); + throw exception("mem index file is empty"); } leaves_stream.open(leaf_file, std::ios::binary); @@ -306,11 +311,11 @@ class StaticRTree // open leaf node file and store thread specific pointer if (!boost::filesystem::exists(leaf_file)) { - throw osrm::exception("mem index file does not exist"); + throw exception("mem index file does not exist"); } if (0 == boost::filesystem::file_size(leaf_file)) { - throw osrm::exception("mem index file is empty"); + throw exception("mem index file is empty"); } leaves_stream.open(leaf_file, std::ios::binary); @@ -411,7 +416,7 @@ class StaticRTree LoadLeafFromDisk(leaf_id, current_leaf_node); // current object represents a block on disk - for (const auto i : osrm::irange(0u, current_leaf_node.object_count)) + for (const auto i : irange(0u, current_leaf_node.object_count)) { auto ¤t_edge = current_leaf_node.objects[i]; const float current_perpendicular_distance = @@ -449,7 +454,7 @@ class StaticRTree } if (!leaves_stream.good()) { - throw osrm::exception("Could not read from leaf file."); + throw exception("Could not read from leaf file."); } const uint64_t seek_pos = sizeof(uint64_t) + leaf_id * sizeof(LeafNode); leaves_stream.seekg(seek_pos); @@ -491,4 +496,7 @@ class StaticRTree //[2] "Nearest Neighbor Queries", N. Roussopulos et al; 1995; DOI: 10.1145/223784.223794 //[3] "Distance Browsing in Spatial Databases"; G. Hjaltason, H. Samet; 1999; ACM Trans. DB Sys // Vol.24 No.2, pp.265-318 +} +} + #endif // STATIC_RTREE_HPP diff --git a/include/util/string_util.hpp b/include/util/string_util.hpp index 78ccfb34a..6a3c772bd 100644 --- a/include/util/string_util.hpp +++ b/include/util/string_util.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // precision: position after decimal point // length: maximum number of digits including comma and decimals // work with negative values to prevent overflowing when taking -value @@ -122,4 +127,7 @@ inline std::size_t URIDecode(const std::string &input, std::string &output) inline std::size_t URIDecodeInPlace(std::string &URI) { return URIDecode(URI, URI); } +} +} + #endif // STRING_UTIL_HPP diff --git a/include/util/timing_util.hpp b/include/util/timing_util.hpp index dc6435634..44af92b89 100644 --- a/include/util/timing_util.hpp +++ b/include/util/timing_util.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + struct GlobalTimer { GlobalTimer() : time(0) {} @@ -60,4 +65,7 @@ class GlobalTimerFactory #define TIMER_MIN(_X) \ std::chrono::duration_cast(_X##_stop - _X##_start).count() +} +} + #endif // TIMING_UTIL_HPP diff --git a/include/util/tribool.hpp b/include/util/tribool.hpp index ff9637273..ec7ca76a7 100644 --- a/include/util/tribool.hpp +++ b/include/util/tribool.hpp @@ -3,11 +3,16 @@ namespace osrm { +namespace util +{ + enum class tribool : char { yes, no, indeterminate }; + +} } #endif // TRIBOOL_HPP diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index c02b5b78a..5c92829c0 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -6,6 +6,11 @@ #include +namespace osrm +{ +namespace util +{ + constexpr unsigned short atan_table[4096] = { 0x0000, 0x0014, 0x0028, 0x003d, 0x0051, 0x0065, 0x007a, 0x008e, 0x00a3, 0x00b7, 0x00cb, 0x00e0, 0x00f4, 0x0108, 0x011d, 0x0131, 0x0146, 0x015a, 0x016e, 0x0183, 0x0197, 0x01ab, 0x01c0, 0x01d4, @@ -418,4 +423,7 @@ inline double atan2_lookup(double y, double x) return angle; } +} +} + #endif // TRIGONOMETRY_TABLE_HPP diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index 0060a7381..243f04ed6 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -1,8 +1,9 @@ #ifndef TYPEDEFS_H #define TYPEDEFS_H -#include #include "osrm/strong_typedef.hpp" + +#include #include // Necessary workaround for Windows as VS doesn't implement C99 diff --git a/include/util/xml_renderer.hpp b/include/util/xml_renderer.hpp index b9de27c4f..b8fa82a58 100644 --- a/include/util/xml_renderer.hpp +++ b/include/util/xml_renderer.hpp @@ -7,6 +7,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -105,6 +107,9 @@ template inline void gpx_render(std::vector &out, const const std::string footer{""}; out.insert(out.end(), footer.begin(), footer.end()); } + } // namespace json +} // namespace util } // namespace osrm + #endif // XML_RENDERER_HPP diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 9e911c1f5..247c76ba6 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + /* This is an implementation of Tabulation hashing, which has suprising properties like universality. @@ -85,4 +90,7 @@ class XORMiniHash } }; +} +} + #endif // XOR_FAST_HASH_HPP diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 2754b4545..046580dc9 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class XORFastHashStorage { public: @@ -71,4 +76,7 @@ template class XORFastHashStorage unsigned current_timestamp; }; +} +} + #endif // XOR_FAST_HASH_STORAGE_HPP diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index db43bf20e..ab6b019a7 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace benchmarks +{ + // Choosen by a fair W20 dice roll (this value is completely arbitrary) constexpr unsigned RANDOM_SEED = 13; constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION; @@ -16,22 +21,22 @@ constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION; constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION; constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION; -using RTreeLeaf = EdgeBasedNode; -using FixedPointCoordinateListPtr = std::shared_ptr>; -using BenchStaticRTree = StaticRTree::vector, false>; -using BenchQuery = GeospatialQuery; +using RTreeLeaf = extractor::EdgeBasedNode; +using FixedPointCoordinateListPtr = std::shared_ptr>; +using BenchStaticRTree = util::StaticRTree::vector, false>; +using BenchQuery = engine::GeospatialQuery; FixedPointCoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file) { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); - QueryNode current_node; + extractor::QueryNode current_node; unsigned coordinate_count = 0; nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned)); auto coords = std::make_shared>(coordinate_count); for (unsigned i = 0; i < coordinate_count; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); coords->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(coords->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(coords->at(i).lon) >> 30) == 0); @@ -51,6 +56,7 @@ void benchmarkQuery(const std::vector &queries, for (const auto &q : queries) { auto result = query(q); + (void) result; } TIMER_STOP(query); @@ -102,6 +108,8 @@ void benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_quer return geo_query.NearestPhantomNodes(q, 10); }); } +} +} int main(int argc, char **argv) { @@ -116,12 +124,12 @@ int main(int argc, char **argv) const char *file_path = argv[2]; const char *nodes_path = argv[3]; - auto coords = loadCoordinates(nodes_path); + auto coords = osrm::benchmarks::loadCoordinates(nodes_path); - BenchStaticRTree rtree(ram_path, file_path, coords); - BenchQuery query(rtree, coords); + osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords); + osrm::benchmarks::BenchQuery query(rtree, coords); - benchmark(rtree, query, 10000); + osrm::benchmarks::benchmark(rtree, query, 10000); return 0; } diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index d25bb71fd..51b8228b7 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -8,6 +8,11 @@ #include +namespace osrm +{ +namespace contractor +{ + return_code ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &contractor_config) { @@ -87,13 +92,13 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont if (option_variables.count("version")) { - SimpleLogger().Write() << OSRM_VERSION; + util::SimpleLogger().Write() << OSRM_VERSION; return return_code::exit; } if (option_variables.count("help")) { - SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << "\n" << visible_options; return return_code::exit; } @@ -101,7 +106,7 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont if (!option_variables.count("input")) { - SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << "\n" << visible_options; return return_code::fail; } @@ -119,3 +124,5 @@ void ContractorOptions::GenerateOutputFilesNames(ContractorConfig &contractor_co contractor_config.edge_penalty_path = contractor_config.osrm_input_path.string() + ".edge_penalties"; } +} +} diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 7e814ded7..b108522fa 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -30,6 +30,24 @@ #include "util/debug_geometry.hpp" +namespace std +{ + +template <> struct hash> +{ + std::size_t operator()(const std::pair &k) const + { + return OSMNodeID_to_uint64_t(k.first) ^ (OSMNodeID_to_uint64_t(k.second) << 12); + } +}; +} + + +namespace osrm +{ +namespace contractor +{ + Prepare::~Prepare() {} int Prepare::Run() @@ -37,24 +55,24 @@ int Prepare::Run() #ifdef WIN32 #pragma message("Memory consumption on Windows can be higher due to different bit packing") #else - static_assert(sizeof(NodeBasedEdge) == 20, - "changing NodeBasedEdge type has influence on memory consumption!"); - static_assert(sizeof(EdgeBasedEdge) == 16, + static_assert(sizeof(extractor::NodeBasedEdge) == 20, + "changing extractor::NodeBasedEdge type has influence on memory consumption!"); + static_assert(sizeof(extractor::EdgeBasedEdge) == 16, "changing EdgeBasedEdge type has influence on memory consumption!"); #endif if (config.core_factor > 1.0 || config.core_factor < 0) { - throw osrm::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); + throw util::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); } TIMER_START(preparing); // Create a new lua state - SimpleLogger().Write() << "Loading edge-expanded graph representation"; + util::SimpleLogger().Write() << "Loading edge-expanded graph representation"; - DeallocatingVector edge_based_edge_list; + util::DeallocatingVector edge_based_edge_list; size_t max_edge_id = LoadEdgeExpandedGraph( config.edge_based_graph_path, edge_based_edge_list, config.edge_segment_lookup_path, @@ -69,12 +87,12 @@ int Prepare::Run() { ReadNodeLevels(node_levels); } - DeallocatingVector contracted_edge_list; + util::DeallocatingVector contracted_edge_list; ContractGraph(max_edge_id, edge_based_edge_list, contracted_edge_list, is_core_node, node_levels); TIMER_STOP(contraction); - SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; + util::SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; std::size_t number_of_used_edges = WriteContractedGraph(max_edge_id, contracted_edge_list); WriteCoreNodeMarker(std::move(is_core_node)); @@ -85,35 +103,23 @@ int Prepare::Run() TIMER_STOP(preparing); - SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; - SimpleLogger().Write() << "Contraction: " << ((max_edge_id + 1) / TIMER_SEC(contraction)) + util::SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; + util::SimpleLogger().Write() << "Contraction: " << ((max_edge_id + 1) / TIMER_SEC(contraction)) << " nodes/sec and " << number_of_used_edges / TIMER_SEC(contraction) << " edges/sec"; - SimpleLogger().Write() << "finished preprocessing"; + util::SimpleLogger().Write() << "finished preprocessing"; return 0; } -namespace std -{ - -template <> struct hash> -{ - std::size_t operator()(const std::pair &k) const - { - return OSMNodeID_to_uint64_t(k.first) ^ (OSMNodeID_to_uint64_t(k.second) << 12); - } -}; -} - std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_filename, - DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &edge_based_edge_list, const std::string &edge_segment_lookup_filename, const std::string &edge_penalty_filename, const std::string &segment_speed_filename) { - SimpleLogger().Write() << "Opening " << edge_based_graph_filename; + util::SimpleLogger().Write() << "Opening " << edge_based_graph_filename; boost::filesystem::ifstream input_stream(edge_based_graph_filename, std::ios::binary); const bool update_edge_weights = segment_speed_filename != ""; @@ -127,14 +133,14 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f edge_fixed_penalties_input_stream.open(edge_penalty_filename, std::ios::binary); if (!edge_segment_input_stream || !edge_fixed_penalties_input_stream) { - throw osrm::exception("Could not load .edge_segment_lookup or .edge_penalties, did you " + throw util::exception("Could not load .edge_segment_lookup or .edge_penalties, did you " "run osrm-extract with '--generate-edge-lookup'?"); } } - const FingerPrint fingerprint_valid = FingerPrint::GetValid(); - FingerPrint fingerprint_loaded; - input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); + const util::FingerPrint fingerprint_valid = util::FingerPrint::GetValid(); + util::FingerPrint fingerprint_loaded; + input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); fingerprint_loaded.TestPrepare(fingerprint_valid); size_t number_of_edges = 0; @@ -143,13 +149,13 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f input_stream.read((char *)&max_edge_id, sizeof(size_t)); edge_based_edge_list.resize(number_of_edges); - SimpleLogger().Write() << "Reading " << number_of_edges << " edges from the edge based graph"; + util::SimpleLogger().Write() << "Reading " << number_of_edges << " edges from the edge based graph"; std::unordered_map, unsigned> segment_speed_lookup; if (update_edge_weights) { - SimpleLogger().Write() << "Segment speed data supplied, will update edge weights from " + util::SimpleLogger().Write() << "Segment speed data supplied, will update edge weights from " << segment_speed_filename; io::CSVReader<3> csv_in(segment_speed_filename); csv_in.set_header("from_node", "to_node", "speed"); @@ -163,14 +169,14 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f } } - DEBUG_GEOMETRY_START(config); + util::DEBUG_GEOMETRY_START(config); - // TODO: can we read this in bulk? DeallocatingVector isn't necessarily + // TODO: can we read this in bulk? util::DeallocatingVector isn't necessarily // all stored contiguously for (; number_of_edges > 0; --number_of_edges) { - EdgeBasedEdge inbuffer; - input_stream.read((char *)&inbuffer, sizeof(EdgeBasedEdge)); + extractor::EdgeBasedEdge inbuffer; + input_stream.read((char *)&inbuffer, sizeof(extractor::EdgeBasedEdge)); if (update_edge_weights) { @@ -212,7 +218,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f (segment_length * 10.) / (speed_iter->second / 3.6) + .5))); new_weight += new_segment_weight; - DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, + util::DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, this_osm_node_id); } else @@ -220,7 +226,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f // If no lookup found, use the original weight value for this segment new_weight += segment_weight; - DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, + util::DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, this_osm_node_id); } @@ -233,8 +239,8 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f edge_based_edge_list.emplace_back(std::move(inbuffer)); } - DEBUG_GEOMETRY_STOP(); - SimpleLogger().Write() << "Done reading edges"; + util::DEBUG_GEOMETRY_STOP(); + util::SimpleLogger().Write() << "Done reading edges"; return max_edge_id; } @@ -277,17 +283,17 @@ void Prepare::WriteCoreNodeMarker(std::vector &&in_is_core_node) const } std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, - const DeallocatingVector &contracted_edge_list) + const util::DeallocatingVector &contracted_edge_list) { // Sorting contracted edges in a way that the static query graph can read some in in-place. tbb::parallel_sort(contracted_edge_list.begin(), contracted_edge_list.end()); const unsigned contracted_edge_count = contracted_edge_list.size(); - SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count + util::SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count << " edges"; - const FingerPrint fingerprint = FingerPrint::GetValid(); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); boost::filesystem::ofstream hsgr_output_stream(config.graph_output_path, std::ios::binary); - hsgr_output_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + hsgr_output_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); const unsigned max_used_node_id = [&contracted_edge_list] { unsigned tmp_max = 0; @@ -301,20 +307,20 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, return tmp_max; }(); - SimpleLogger().Write(logDEBUG) << "input graph has " << (max_node_id + 1) << " nodes"; - SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) << " nodes"; + util::SimpleLogger().Write(logDEBUG) << "input graph has " << (max_node_id + 1) << " nodes"; + util::SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) << " nodes"; - std::vector::NodeArrayEntry> node_array; + std::vector::NodeArrayEntry> node_array; // make sure we have at least one sentinel node_array.resize(max_node_id + 2); - SimpleLogger().Write() << "Building node array"; - StaticGraph::EdgeIterator edge = 0; - StaticGraph::EdgeIterator position = 0; - StaticGraph::EdgeIterator last_edge; + util::SimpleLogger().Write() << "Building node array"; + util::StaticGraph::EdgeIterator edge = 0; + util::StaticGraph::EdgeIterator position = 0; + util::StaticGraph::EdgeIterator last_edge; // initializing 'first_edge'-field of nodes: - for (const auto node : osrm::irange(0u, max_used_node_id + 1)) + for (const auto node : util::irange(0u, max_used_node_id + 1)) { last_edge = edge; while ((edge < contracted_edge_count) && (contracted_edge_list[edge].source == node)) @@ -326,17 +332,17 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, } for (const auto sentinel_counter : - osrm::irange(max_used_node_id + 1, node_array.size())) + util::irange(max_used_node_id + 1, node_array.size())) { // sentinel element, guarded against underflow node_array[sentinel_counter].first_edge = contracted_edge_count; } - SimpleLogger().Write() << "Serializing node array"; + util::SimpleLogger().Write() << "Serializing node array"; RangebasedCRC32 crc32_calculator; const unsigned edges_crc32 = crc32_calculator(contracted_edge_list); - SimpleLogger().Write() << "Writing CRC32: " << edges_crc32; + util::SimpleLogger().Write() << "Writing CRC32: " << edges_crc32; const unsigned node_array_size = node_array.size(); // serialize crc32, aka checksum @@ -349,15 +355,15 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, if (node_array_size > 0) { hsgr_output_stream.write((char *)&node_array[0], - sizeof(StaticGraph::NodeArrayEntry) * node_array_size); + sizeof(util::StaticGraph::NodeArrayEntry) * node_array_size); } // serialize all edges - SimpleLogger().Write() << "Building edge array"; + util::SimpleLogger().Write() << "Building edge array"; int number_of_used_edges = 0; - StaticGraph::EdgeArrayEntry current_edge; - for (const auto edge : osrm::irange(0, contracted_edge_list.size())) + util::StaticGraph::EdgeArrayEntry current_edge; + for (const auto edge : util::irange(0, contracted_edge_list.size())) { // no eigen loops BOOST_ASSERT(contracted_edge_list[edge].source != contracted_edge_list[edge].target); @@ -369,19 +375,19 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, #ifndef NDEBUG if (current_edge.data.distance <= 0) { - SimpleLogger().Write(logWARNING) << "Edge: " << edge + util::SimpleLogger().Write(logWARNING) << "Edge: " << edge << ",source: " << contracted_edge_list[edge].source << ", target: " << contracted_edge_list[edge].target << ", dist: " << current_edge.data.distance; - SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " + util::SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " << contracted_edge_list[edge].source << "/" << node_array.size() - 1; return 1; } #endif hsgr_output_stream.write((char *)¤t_edge, - sizeof(StaticGraph::EdgeArrayEntry)); + sizeof(util::StaticGraph::EdgeArrayEntry)); ++number_of_used_edges; } @@ -393,8 +399,8 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, \brief Build contracted graph. */ void Prepare::ContractGraph(const unsigned max_edge_id, - DeallocatingVector &edge_based_edge_list, - DeallocatingVector &contracted_edge_list, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, std::vector &is_core_node, std::vector &inout_node_levels) const { @@ -407,3 +413,5 @@ void Prepare::ContractGraph(const unsigned max_edge_id, contractor.GetCoreMarker(is_core_node); contractor.GetNodeLevels(inout_node_levels); } +} +} diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index 2be347fd8..cced730b2 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -9,13 +9,18 @@ #include #include +namespace osrm +{ +namespace engine +{ + namespace { struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; - CoordinatePairCalculator(const FixedPointCoordinate &coordinate_a, - const FixedPointCoordinate &coordinate_b) + CoordinatePairCalculator(const util::FixedPointCoordinate &coordinate_a, + const util::FixedPointCoordinate &coordinate_b) { // initialize distance calculator with two fixed coordinates a, b const float RAD = 0.017453292519943295769236907684886f; @@ -25,7 +30,7 @@ struct CoordinatePairCalculator second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * RAD; } - int operator()(FixedPointCoordinate &other) const + int operator()(util::FixedPointCoordinate &other) const { // set third coordinate c const float RAD = 0.017453292519943295769236907684886f; @@ -135,3 +140,5 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne } } } +} +} diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 0be92a777..200eb2741 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -28,43 +28,51 @@ #include #include +namespace osrm +{ +namespace engine +{ + OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig &lib_config) { if (lib_config.use_shared_memory) { - barrier = osrm::make_unique(); - query_data_facade = new SharedDataFacade(); + barrier = util::make_unique(); + query_data_facade = new datafacade::SharedDataFacade(); } else { // populate base path - populate_base_path(lib_config.server_paths); - query_data_facade = new InternalDataFacade(lib_config.server_paths); + util::populate_base_path(lib_config.server_paths); + query_data_facade = new datafacade::InternalDataFacade( + lib_config.server_paths); } + using DataFacade = datafacade::BaseDataFacade; + // The following plugins handle all requests. - RegisterPlugin(new DistanceTablePlugin>( + RegisterPlugin(new plugins::DistanceTablePlugin( query_data_facade, lib_config.max_locations_distance_table)); - RegisterPlugin(new HelloWorldPlugin()); - RegisterPlugin(new NearestPlugin>(query_data_facade)); - RegisterPlugin(new MapMatchingPlugin>( + RegisterPlugin(new plugins::HelloWorldPlugin()); + RegisterPlugin(new plugins::NearestPlugin(query_data_facade)); + RegisterPlugin(new plugins::MapMatchingPlugin( query_data_facade, lib_config.max_locations_map_matching)); - RegisterPlugin(new TimestampPlugin>(query_data_facade)); - RegisterPlugin(new ViaRoutePlugin>( - query_data_facade, lib_config.max_locations_viaroute)); - RegisterPlugin(new RoundTripPlugin>( - query_data_facade, lib_config.max_locations_trip)); + RegisterPlugin(new plugins::TimestampPlugin(query_data_facade)); + RegisterPlugin(new plugins::ViaRoutePlugin(query_data_facade, + lib_config.max_locations_viaroute)); + RegisterPlugin( + new plugins::RoundTripPlugin(query_data_facade, lib_config.max_locations_trip)); } -void OSRM::OSRM_impl::RegisterPlugin(BasePlugin *raw_plugin_ptr) +void OSRM::OSRM_impl::RegisterPlugin(plugins::BasePlugin *raw_plugin_ptr) { - std::unique_ptr plugin_ptr(raw_plugin_ptr); - SimpleLogger().Write() << "loaded plugin: " << plugin_ptr->GetDescriptor(); + std::unique_ptr plugin_ptr(raw_plugin_ptr); + util::SimpleLogger().Write() << "loaded plugin: " << plugin_ptr->GetDescriptor(); plugin_map[plugin_ptr->GetDescriptor()] = std::move(plugin_ptr); } int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, - osrm::json::Object &json_result) + util::json::Object &json_result) { const auto &plugin_iterator = plugin_map.find(route_parameters.service); @@ -124,17 +132,20 @@ void OSRM::OSRM_impl::increase_concurrent_query_count() // increment query count ++(barrier->number_of_queries); - (static_cast *>(query_data_facade)) + (static_cast *>( + query_data_facade)) ->CheckAndReloadFacade(); } // proxy code for compilation firewall -OSRM::OSRM(LibOSRMConfig &lib_config) : OSRM_pimpl_(osrm::make_unique(lib_config)) {} +OSRM::OSRM(LibOSRMConfig &lib_config) : OSRM_pimpl_(util::make_unique(lib_config)) {} // needed because unique_ptr needs the size of OSRM_impl for delete OSRM::~OSRM() {} -int OSRM::RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result) +int OSRM::RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result) { return OSRM_pimpl_->RunQuery(route_parameters, json_result); } +} +} diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 670ffe706..e5b5873df 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace engine +{ + PhantomNode::PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id, @@ -15,10 +20,10 @@ PhantomNode::PhantomNode(NodeID forward_node_id, unsigned packed_geometry_id, bool is_tiny_component, unsigned component_id, - FixedPointCoordinate &location, + util::FixedPointCoordinate &location, unsigned short fwd_segment_position, - TravelMode forward_travel_mode, - TravelMode backward_travel_mode) + extractor::TravelMode forward_travel_mode, + extractor::TravelMode backward_travel_mode) : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), forward_weight(forward_weight), reverse_weight(reverse_weight), forward_offset(forward_offset), reverse_offset(reverse_offset), @@ -74,3 +79,5 @@ bool PhantomNode::is_valid(const unsigned number_of_nodes) const bool PhantomNode::IsValid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } bool PhantomNode::operator==(const PhantomNode &other) const { return location == other.location; } +} +} diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 2cb7935f7..042653084 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -3,6 +3,11 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace engine +{ + std::string PolylineCompressor::encode_vector(std::vector &numbers) const { std::string output; @@ -47,7 +52,7 @@ PolylineCompressor::get_encoded_string(const std::vector &po std::vector delta_numbers; delta_numbers.reserve((polyline.size() - 1) * 2); - FixedPointCoordinate previous_coordinate = {0, 0}; + util::FixedPointCoordinate previous_coordinate = {0, 0}; for (const auto &segment : polyline) { if (segment.necessary) @@ -62,10 +67,10 @@ PolylineCompressor::get_encoded_string(const std::vector &po return encode_vector(delta_numbers); } -std::vector +std::vector PolylineCompressor::decode_string(const std::string &geometry_string) const { - std::vector new_coordinates; + std::vector new_coordinates; int index = 0, len = geometry_string.size(); int lat = 0, lng = 0; @@ -92,7 +97,7 @@ PolylineCompressor::decode_string(const std::string &geometry_string) const int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; - FixedPointCoordinate p; + util::FixedPointCoordinate p; p.lat = COORDINATE_PRECISION * (((double)lat / 1E6)); p.lon = COORDINATE_PRECISION * (((double)lng / 1E6)); new_coordinates.push_back(p); @@ -100,3 +105,5 @@ PolylineCompressor::decode_string(const std::string &geometry_string) const return new_coordinates; } +} +} diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 52fa4935d..0b22ddb24 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -5,21 +5,26 @@ #include "osrm/coordinate.hpp" -osrm::json::String +namespace osrm +{ +namespace engine +{ + +util::json::String PolylineFormatter::printEncodedString(const std::vector &polyline) const { - return osrm::json::String(PolylineCompressor().get_encoded_string(polyline)); + return util::json::String(PolylineCompressor().get_encoded_string(polyline)); } -osrm::json::Array +util::json::Array PolylineFormatter::printUnencodedString(const std::vector &polyline) const { - osrm::json::Array json_geometry_array; + util::json::Array json_geometry_array; for (const auto &segment : polyline) { if (segment.necessary) { - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.push_back(segment.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back(segment.location.lon / COORDINATE_PRECISION); json_geometry_array.values.push_back(json_coordinate); @@ -27,3 +32,5 @@ PolylineFormatter::printUnencodedString(const std::vector &p } return json_geometry_array; } +} +} diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index c0c1290fb..6565896f3 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -7,6 +7,11 @@ #include "engine/polyline_compressor.hpp" +namespace osrm +{ +namespace engine +{ + RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), compression(true), deprecatedAPI(false), uturn_default(false), classify(false), @@ -151,3 +156,5 @@ void RouteParameters::SetCoordinatesFromGeometry(const std::string &geometry_str PolylineCompressor pc; coordinates = pc.decode_string(geometry_string); } +} +} diff --git a/src/engine/search_engine_data.cpp b/src/engine/search_engine_data.cpp index d96fd22da..9aeb87d39 100644 --- a/src/engine/search_engine_data.cpp +++ b/src/engine/search_engine_data.cpp @@ -2,6 +2,11 @@ #include "util/binary_heap.hpp" +namespace osrm +{ +namespace engine +{ + void SearchEngineData::InitializeOrClearFirstThreadLocalStorage(const unsigned number_of_nodes) { if (forward_heap_1.get()) @@ -64,3 +69,5 @@ void SearchEngineData::InitializeOrClearThirdThreadLocalStorage(const unsigned n reverse_heap_3.reset(new QueryHeap(number_of_nodes)); } } +} +} diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index 2b9c5146f..9f20ac1ea 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -10,6 +10,11 @@ #include +namespace osrm +{ +namespace extractor +{ + CompressedEdgeContainer::CompressedEdgeContainer() { m_free_list.reserve(100); @@ -181,7 +186,7 @@ void CompressedEdgeContainer::PrintStatistics() const longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size()); } - SimpleLogger().Write() << "Geometry successfully removed:" + util::SimpleLogger().Write() << "Geometry successfully removed:" "\n compressed edges: " << compressed_edges << "\n compressed geometries: " << compressed_geometries @@ -212,3 +217,5 @@ NodeID CompressedEdgeContainer::GetLastEdgeSourceID(const EdgeID edge_id) const BOOST_ASSERT(bucket.size() >= 2); return bucket[bucket.size() - 2].first; } +} +} diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 896f84e7f..8bae91dc1 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -16,8 +16,13 @@ #include #include +namespace osrm +{ +namespace extractor +{ + EdgeBasedGraphFactory::EdgeBasedGraphFactory( - std::shared_ptr node_based_graph, + std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, @@ -32,7 +37,7 @@ EdgeBasedGraphFactory::EdgeBasedGraphFactory( { } -void EdgeBasedGraphFactory::GetEdgeBasedEdges(DeallocatingVector &output_edge_list) +void EdgeBasedGraphFactory::GetEdgeBasedEdges(util::DeallocatingVector &output_edge_list) { BOOST_ASSERT_MSG(0 == output_edge_list.size(), "Vector is not empty"); using std::swap; // Koenig swap @@ -108,7 +113,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI // TODO: move to lambda function with C++11 int temp_sum = 0; - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { forward_dist_prefix_sum[i] = temp_sum; temp_sum += forward_geometry[i].second; @@ -117,7 +122,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI } temp_sum = 0; - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { temp_sum += reverse_geometry[reverse_geometry.size() - 1 - i].second; reverse_dist_prefix_sum[i] = reverse_data.distance - temp_sum; @@ -127,7 +132,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI NodeID current_edge_source_coordinate_id = node_u; // traverse arrays from start and end respectively - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { BOOST_ASSERT(current_edge_source_coordinate_id == reverse_geometry[geometry_size - 1 - i].first); @@ -238,10 +243,10 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, TIMER_STOP(generate_edges); - SimpleLogger().Write() << "Timing statistics for edge-expanded graph:"; - SimpleLogger().Write() << "Renumbering edges: " << TIMER_SEC(renumber) << "s"; - SimpleLogger().Write() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s"; - SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s"; + util::SimpleLogger().Write() << "Timing statistics for edge-expanded graph:"; + util::SimpleLogger().Write() << "Renumbering edges: " << TIMER_SEC(renumber) << "s"; + util::SimpleLogger().Write() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s"; + util::SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s"; } /// Renumbers all _forward_ edges and sets the edge_id. @@ -251,7 +256,7 @@ unsigned EdgeBasedGraphFactory::RenumberEdges() { // renumber edge based node of outgoing edges unsigned numbered_edges_count = 0; - for (const auto current_node : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto current_node : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(current_node)) { @@ -277,10 +282,10 @@ unsigned EdgeBasedGraphFactory::RenumberEdges() /// Creates the nodes in the edge expanded graph from edges in the node-based graph. void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() { - Percent progress(m_node_based_graph->GetNumberOfNodes()); + util::Percent progress(m_node_based_graph->GetNumberOfNodes()); // loop over all edges and generate new set of nodes - for (const auto node_u : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto node_u : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { BOOST_ASSERT(node_u != SPECIAL_NODEID); BOOST_ASSERT(node_u < m_node_based_graph->GetNumberOfNodes()); @@ -315,7 +320,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() BOOST_ASSERT(m_edge_based_node_list.size() == m_edge_based_node_is_startpoint.size()); - SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() + util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " nodes in edge-expanded graph"; } @@ -337,7 +342,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const bool generate_edge_lookup) #endif { - SimpleLogger().Write() << "generating edge-expanded edges"; + util::SimpleLogger().Write() << "generating edge-expanded edges"; unsigned node_based_edge_counter = 0; unsigned original_edges_counter = 0; @@ -366,13 +371,13 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( unsigned skipped_barrier_turns_counter = 0; unsigned compressed = 0; - Percent progress(m_node_based_graph->GetNumberOfNodes()); + util::Percent progress(m_node_based_graph->GetNumberOfNodes()); #ifdef DEBUG_GEOMETRY - DEBUG_TURNS_START(debug_turns_path); + util::DEBUG_TURNS_START(debug_turns_path); #endif - for (const auto node_u : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto node_u : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { // progress.printStatus(node_u); for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(node_u)) @@ -446,7 +451,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { distance += speed_profile.traffic_signal_penalty; - DEBUG_SIGNAL(node_v, m_node_info_list, speed_profile.traffic_signal_penalty); + util::DEBUG_SIGNAL(node_v, m_node_info_list, speed_profile.traffic_signal_penalty); } // unpack last node of first segment if packed @@ -461,7 +466,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( ? m_compressed_edge_container.GetFirstEdgeTargetID(e2) : node_w)]; - const double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( + const double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( first_coordinate, m_node_info_list[node_v], third_coordinate); const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); @@ -470,10 +475,10 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { distance += speed_profile.u_turn_penalty; - DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); + util::DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); } - DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); + util::DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); distance += turn_penalty; @@ -541,7 +546,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const QueryNode &from = m_node_info_list[previous]; const QueryNode &to = m_node_info_list[target_node.first]; const double segment_length = - coordinate_calculation::greatCircleDistance(from.lat, from.lon, + util::coordinate_calculation::greatCircleDistance(from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&to.node_id), @@ -559,7 +564,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( static const unsigned node_count = 2; const QueryNode from = m_node_info_list[node_u]; const QueryNode to = m_node_info_list[node_v]; - const double segment_length = coordinate_calculation::greatCircleDistance( + const double segment_length = util::coordinate_calculation::greatCircleDistance( from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); @@ -578,7 +583,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( } } - DEBUG_TURNS_STOP(); + util::DEBUG_TURNS_STOP(); FlushVectorToStream(edge_data_file, original_edge_data_vector); @@ -586,15 +591,15 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( edge_data_file.write((char *)&original_edges_counter, sizeof(unsigned)); edge_data_file.close(); - SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " edge based nodes"; - SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter << " edges"; - SimpleLogger().Write() << "Edge-expanded graph ..."; - SimpleLogger().Write() << " contains " << m_edge_based_edge_list.size() << " edges"; - SimpleLogger().Write() << " skips " << restricted_turns_counter << " turns, " + util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " edge based nodes"; + util::SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter << " edges"; + util::SimpleLogger().Write() << "Edge-expanded graph ..."; + util::SimpleLogger().Write() << " contains " << m_edge_based_edge_list.size() << " edges"; + util::SimpleLogger().Write() << " skips " << restricted_turns_counter << " turns, " "defined by " << m_restriction_map->size() << " restrictions"; - SimpleLogger().Write() << " skips " << skipped_uturns_counter << " U turns"; - SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter << " turns over barriers"; + util::SimpleLogger().Write() << " skips " << skipped_uturns_counter << " U turns"; + util::SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter << " turns over barriers"; } int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) const @@ -611,7 +616,7 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co } catch (const luabind::error &er) { - SimpleLogger().Write(logWARNING) << er.what(); + util::SimpleLogger().Write(logWARNING) << er.what(); } } return 0; @@ -673,3 +678,5 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, return TurnInstructionsClass::GetTurnDirectionOfInstruction(angle); } +} +} diff --git a/src/extractor/external_memory_node.cpp b/src/extractor/external_memory_node.cpp index 35dc18af1..249c25606 100644 --- a/src/extractor/external_memory_node.cpp +++ b/src/extractor/external_memory_node.cpp @@ -3,6 +3,11 @@ #include +namespace osrm +{ +namespace extractor +{ + ExternalMemoryNode::ExternalMemoryNode( int lat, int lon, OSMNodeID node_id, bool barrier, bool traffic_lights) : QueryNode(lat, lon, node_id), barrier(barrier), traffic_lights(traffic_lights) @@ -37,3 +42,5 @@ ExternalMemoryNodeSTXXLCompare::value_type ExternalMemoryNodeSTXXLCompare::min_v { return ExternalMemoryNode::min_value(); } +} +} diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 80fe2ac5f..72333644a 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -24,6 +24,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + static const int WRITE_BLOCK_BUFFER_SIZE = 8000; ExtractionContainers::ExtractionContainers() @@ -65,8 +70,8 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, { std::ofstream file_out_stream; file_out_stream.open(output_file_name.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - file_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); PrepareNodes(); WriteNodes(file_out_stream); @@ -100,7 +105,7 @@ void ExtractionContainers::WriteNames(const std::string &names_file_name) const } // builds and writes the index - RangeTable<> name_index_range(name_lengths); + util::RangeTable<> name_index_range(name_lengths); name_file_stream << name_index_range; name_file_stream.write((char *)&total_length, sizeof(unsigned)); @@ -182,7 +187,7 @@ void ExtractionContainers::PrepareNodes() } if (internal_id > std::numeric_limits::max()) { - throw osrm::exception("There are too many nodes remaining after filtering, OSRM only " + throw util::exception("There are too many nodes remaining after filtering, OSRM only " "supports 2^32 unique nodes"); } max_internal_node_id = boost::numeric_cast(internal_id); @@ -212,7 +217,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) { if (edge_iterator->result.osm_source_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge_iterator->result.source; edge_iterator->result.source = SPECIAL_NODEID; ++edge_iterator; @@ -249,7 +254,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // them. This happens when using osmosis with bbox or polygon to extract smaller areas. auto markSourcesInvalid = [](InternalExtractorEdge &edge) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge.result.source; edge.result.source = SPECIAL_NODEID; edge.result.osm_source_id = SPECIAL_OSM_NODEID; @@ -284,7 +289,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) if (edge_iterator->result.osm_target_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << OSMNodeID_to_uint64_t(edge_iterator->result.osm_target_id); edge_iterator->result.target = SPECIAL_NODEID; @@ -302,11 +307,11 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) BOOST_ASSERT(edge_iterator->source_coordinate.lat != std::numeric_limits::min()); BOOST_ASSERT(edge_iterator->source_coordinate.lon != std::numeric_limits::min()); - const double distance = coordinate_calculation::greatCircleDistance( + const double distance = util::coordinate_calculation::greatCircleDistance( edge_iterator->source_coordinate.lat, edge_iterator->source_coordinate.lon, node_iterator->lat, node_iterator->lon); - if (lua_function_exists(segment_state, "segment_function")) + if (util::lua_function_exists(segment_state, "segment_function")) { luabind::call_function( segment_state, "segment_function", boost::cref(edge_iterator->source_coordinate), @@ -325,7 +330,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) return (distance * 10.) / (data.speed / 3.6); break; case InternalExtractorEdge::WeightType::INVALID: - osrm::exception("invalid weight type"); + util::exception("invalid weight type"); } return -1.0; }(edge_iterator->weight_data); @@ -356,7 +361,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // them. This happens when using osmosis with bbox or polygon to extract smaller areas. auto markTargetsInvalid = [](InternalExtractorEdge &edge) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge.result.target; edge.result.target = SPECIAL_NODEID; }; @@ -488,7 +493,7 @@ void ExtractionContainers::WriteEdges(std::ofstream &file_out_stream) const if (used_edges_counter > std::numeric_limits::max()) { - throw osrm::exception("There are too many edges, OSRM only supports 2^32"); + throw util::exception("There are too many edges, OSRM only supports 2^32"); } TIMER_STOP(write_edges); std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; @@ -501,7 +506,7 @@ void ExtractionContainers::WriteEdges(std::ofstream &file_out_stream) const file_out_stream.write((char *)&used_edges_counter_buffer, sizeof(unsigned)); std::cout << "ok" << std::endl; - SimpleLogger().Write() << "Processed " << used_edges_counter << " edges"; + util::SimpleLogger().Write() << "Processed " << used_edges_counter << " edges"; } void ExtractionContainers::WriteNodes(std::ofstream &file_out_stream) const @@ -541,7 +546,7 @@ void ExtractionContainers::WriteNodes(std::ofstream &file_out_stream) const TIMER_STOP(write_nodes); std::cout << "ok, after " << TIMER_SEC(write_nodes) << "s" << std::endl; - SimpleLogger().Write() << "Processed " << max_internal_node_id << " nodes"; + util::SimpleLogger().Write() << "Processed " << max_internal_node_id << " nodes"; } void ExtractionContainers::WriteRestrictions(const std::string &path) const @@ -550,8 +555,8 @@ void ExtractionContainers::WriteRestrictions(const std::string &path) const std::ofstream restrictions_out_stream; unsigned written_restriction_count = 0; restrictions_out_stream.open(path.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - restrictions_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + restrictions_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); const auto count_position = restrictions_out_stream.tellp(); restrictions_out_stream.write((char *)&written_restriction_count, sizeof(unsigned)); @@ -569,7 +574,7 @@ void ExtractionContainers::WriteRestrictions(const std::string &path) const restrictions_out_stream.seekp(count_position); restrictions_out_stream.write((char *)&written_restriction_count, sizeof(unsigned)); restrictions_out_stream.close(); - SimpleLogger().Write() << "usable restrictions: " << written_restriction_count; + util::SimpleLogger().Write() << "usable restrictions: " << written_restriction_count; } void ExtractionContainers::PrepareRestrictions() @@ -609,7 +614,7 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.from.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.from.way; restrictions_iterator->restriction.from.node = SPECIAL_NODEID; ++restrictions_iterator; @@ -625,7 +630,7 @@ void ExtractionContainers::PrepareRestrictions() auto via_id_iter = external_to_internal_node_id_map.find(via_node_id); if (via_id_iter == external_to_internal_node_id_map.end()) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " << restrictions_iterator->restriction.via.node; restrictions_iterator->restriction.via.node = SPECIAL_NODEID; ++restrictions_iterator; @@ -686,7 +691,7 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.to.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.to.way; restrictions_iterator->restriction.to.way = SPECIAL_NODEID; ++restrictions_iterator; @@ -720,3 +725,5 @@ void ExtractionContainers::PrepareRestrictions() TIMER_STOP(fix_restriction_ends); std::cout << "ok, after " << TIMER_SEC(fix_restriction_ends) << "s" << std::endl; } +} +} diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 4038b3ec9..053e5bd1c 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -46,6 +46,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * TODO: Refactor this function into smaller functions for better readability. * @@ -69,7 +74,7 @@ int extractor::run() { try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); TIMER_START(extracting); const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads(); @@ -77,15 +82,15 @@ int extractor::run() std::min(recommended_num_threads, config.requested_num_threads); tbb::task_scheduler_init init(number_of_threads); - SimpleLogger().Write() << "Input file: " << config.input_path.filename().string(); - SimpleLogger().Write() << "Profile: " << config.profile_path.filename().string(); - SimpleLogger().Write() << "Threads: " << number_of_threads; + util::SimpleLogger().Write() << "Input file: " << config.input_path.filename().string(); + util::SimpleLogger().Write() << "Profile: " << config.profile_path.filename().string(); + util::SimpleLogger().Write() << "Threads: " << number_of_threads; // setup scripting environment ScriptingEnvironment scripting_environment(config.profile_path.string().c_str()); ExtractionContainers extraction_containers; - auto extractor_callbacks = osrm::make_unique(extraction_containers); + auto extractor_callbacks = util::make_unique(extraction_containers); const osmium::io::File input_file(config.input_path.string()); osmium::io::Reader reader(input_file); @@ -96,12 +101,12 @@ int extractor::run() std::atomic number_of_relations{0}; std::atomic number_of_others{0}; - SimpleLogger().Write() << "Parsing in progress.."; + util::SimpleLogger().Write() << "Parsing in progress.."; TIMER_START(parsing); lua_State *segment_state = scripting_environment.GetLuaState(); - if (lua_function_exists(segment_state, "source_function")) + if (util::lua_function_exists(segment_state, "source_function")) { // bind a single instance of SourceContainer class to relevant lua state SourceContainer sources; @@ -115,7 +120,7 @@ int extractor::run() { generator = "unknown tool"; } - SimpleLogger().Write() << "input file generated by " << generator; + util::SimpleLogger().Write() << "input file generated by " << generator; // write .timestamp data file std::string timestamp = header.get("osmosis_replication_timestamp"); @@ -123,7 +128,7 @@ int extractor::run() { timestamp = "n/a"; } - SimpleLogger().Write() << "timestamp: " << timestamp; + util::SimpleLogger().Write() << "timestamp: " << timestamp; boost::filesystem::ofstream timestamp_out(config.timestamp_file_name); timestamp_out.write(timestamp.c_str(), timestamp.length()); @@ -214,9 +219,9 @@ int extractor::run() } } TIMER_STOP(parsing); - SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; + util::SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; - SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " + util::SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " << number_of_ways.load() << " ways, and " << number_of_relations.load() << " relations, and " << number_of_others.load() << " unknown entities"; @@ -225,7 +230,7 @@ int extractor::run() if (extraction_containers.all_edges_list.empty()) { - SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; + util::SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return 1; } @@ -233,11 +238,11 @@ int extractor::run() config.names_file_name, segment_state); TIMER_STOP(extracting); - SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; + util::SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return 1; } @@ -250,12 +255,12 @@ int extractor::run() // // // Create a new lua state - SimpleLogger().Write() << "Generating edge-expanded graph representation"; + util::SimpleLogger().Write() << "Generating edge-expanded graph representation"; TIMER_START(expansion); std::vector node_based_edge_list; - DeallocatingVector edge_based_edge_list; + util::DeallocatingVector edge_based_edge_list; std::vector node_is_startpoint; std::vector internal_to_external_node_map; auto graph_size = @@ -267,7 +272,7 @@ int extractor::run() TIMER_STOP(expansion); - SimpleLogger().Write() << "building r-tree ..."; + util::SimpleLogger().Write() << "building r-tree ..."; TIMER_START(rtree); FindComponents(max_edge_id, edge_based_edge_list, node_based_edge_list); @@ -277,21 +282,21 @@ int extractor::run() TIMER_STOP(rtree); - SimpleLogger().Write() << "writing node map ..."; + util::SimpleLogger().Write() << "writing node map ..."; WriteNodeMapping(internal_to_external_node_map); WriteEdgeBasedGraph(config.edge_graph_output_path, max_edge_id, edge_based_edge_list); - SimpleLogger().Write() << "Expansion : " + util::SimpleLogger().Write() << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) << " edges/sec"; - SimpleLogger().Write() << "To prepare the data for routing, run: " + util::SimpleLogger().Write() << "To prepare the data for routing, run: " << "./osrm-prepare " << config.output_file_name << std::endl; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return 1; } @@ -309,39 +314,39 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, luaL_openlibs(lua_state); // adjust lua load path - luaAddScriptFolderToLoadPath(lua_state, config.profile_path.string().c_str()); + util::luaAddScriptFolderToLoadPath(lua_state, config.profile_path.string().c_str()); // Now call our function in a lua script if (0 != luaL_dofile(lua_state, config.profile_path.string().c_str())) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } if (0 != luaL_dostring(lua_state, "return traffic_signal_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); - SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " + util::SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " << speed_profile.traffic_signal_penalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } speed_profile.u_turn_penalty = 10 * lua_tointeger(lua_state, -1); - speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function"); + speed_profile.has_turn_penalty_function = util::lua_function_exists(lua_state, "turn_function"); } void extractor::FindComponents(unsigned max_edge_id, - const DeallocatingVector &input_edge_list, + const util::DeallocatingVector &input_edge_list, std::vector &input_nodes) const { struct UncontractedEdgeData @@ -363,7 +368,7 @@ void extractor::FindComponents(unsigned max_edge_id, return source == rhs.source && target == rhs.target; } }; - using UncontractedGraph = StaticGraph; + using UncontractedGraph = util::StaticGraph; std::vector edges; edges.reserve(input_edge_list.size() * 2); @@ -424,9 +429,9 @@ std::shared_ptr extractor::LoadRestrictionMap() std::ios::in | std::ios::binary); std::vector restriction_list; - loadRestrictionsFromFile(input_stream, restriction_list); + util::loadRestrictionsFromFile(input_stream, restriction_list); - SimpleLogger().Write() << " - " << restriction_list.size() << " restrictions."; + util::SimpleLogger().Write() << " - " << restriction_list.size() << " restrictions."; return std::make_shared(restriction_list); } @@ -434,7 +439,7 @@ std::shared_ptr extractor::LoadRestrictionMap() /** \brief Load node based graph from .osrm file */ -std::shared_ptr +std::shared_ptr extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map) @@ -446,10 +451,10 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::vector barrier_list; std::vector traffic_light_list; - NodeID number_of_node_based_nodes = loadNodesFromFile( + NodeID number_of_node_based_nodes = util::loadNodesFromFile( input_stream, barrier_list, traffic_light_list, internal_to_external_node_map); - SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " + util::SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " << traffic_light_list.size() << " traffic lights"; // insert into unordered sets for fast lookup @@ -461,15 +466,15 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, traffic_light_list.clear(); traffic_light_list.shrink_to_fit(); - loadEdgesFromFile(input_stream, edge_list); + util::loadEdgesFromFile(input_stream, edge_list); if (edge_list.empty()) { - SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; - return std::shared_ptr(); + util::SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; + return std::shared_ptr(); } - return NodeBasedDynamicGraphFromEdges(number_of_node_based_nodes, edge_list); + return util::NodeBasedDynamicGraphFromEdges(number_of_node_based_nodes, edge_list); } /** @@ -479,7 +484,7 @@ std::pair extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, - DeallocatingVector &edge_based_edge_list) + util::DeallocatingVector &edge_based_edge_list) { lua_State *lua_state = luaL_newstate(); luabind::open(lua_state); @@ -550,7 +555,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, std::vector node_is_startpoint, const std::vector &internal_to_external_node_map) { - SimpleLogger().Write() << "constructing r-tree of " << node_based_edge_list.size() + util::SimpleLogger().Write() << "constructing r-tree of " << node_based_edge_list.size() << " edge elements build on-top of " << internal_to_external_node_map.size() << " coordinates"; @@ -559,7 +564,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, // Filter node based edges based on startpoint auto out_iter = node_based_edge_list.begin(); auto in_iter = node_based_edge_list.begin(); - for (auto index : osrm::irange(0, node_is_startpoint.size())) + for (auto index : util::irange(0, node_is_startpoint.size())) { BOOST_ASSERT(in_iter != node_based_edge_list.end()); if (node_is_startpoint[index]) @@ -573,23 +578,23 @@ void extractor::BuildRTree(std::vector node_based_edge_list, node_based_edge_list.resize(new_size); TIMER_START(construction); - StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, + util::StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, config.rtree_leafs_output_path, internal_to_external_node_map); TIMER_STOP(construction); - SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) + util::SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) << " seconds"; } void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, size_t const max_edge_id, - DeallocatingVector const &edge_based_edge_list) + util::DeallocatingVector const &edge_based_edge_list) { std::ofstream file_out_stream; file_out_stream.open(output_file_filename.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - file_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); std::cout << "[extractor] Writing edge-based-graph egdes ... " << std::flush; TIMER_START(write_edges); @@ -606,6 +611,8 @@ void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, TIMER_STOP(write_edges); std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; - SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; + util::SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; file_out_stream.close(); } +} +} diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 9b740c6dd..03f60134f 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -18,6 +18,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + ExtractorCallbacks::ExtractorCallbacks(ExtractionContainers &extraction_containers) : external_memory(extraction_containers) { @@ -45,7 +50,7 @@ void ExtractorCallbacks::ProcessRestriction( if (restriction) { external_memory.restrictions_list.push_back(restriction.get()); - // SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node << + // util::SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node << // ",via: " << restriction.get().restriction.via.node << // ", to: " << restriction.get().restriction.to.node << // ", only: " << (restriction.get().restriction.flags.is_only ? @@ -79,7 +84,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (std::numeric_limits::max() == input_way.id()) { - SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id() + util::SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id() << " of size " << input_way.nodes().size(); return; } @@ -118,7 +123,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (forward_weight_data.type == InternalExtractorEdge::WeightType::INVALID && backward_weight_data.type == InternalExtractorEdge::WeightType::INVALID) { - SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id(); + util::SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id(); return; } @@ -159,7 +164,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti { BOOST_ASSERT(split_edge == false); BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE); - osrm::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(), + util::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( @@ -179,7 +184,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti { const bool forward_only = split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode; - osrm::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(), + util::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( @@ -192,7 +197,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (split_edge) { BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE); - osrm::for_each_pair( + util::for_each_pair( input_way.nodes().cbegin(), input_way.nodes().cend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { @@ -210,3 +215,5 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti OSMNodeID(input_way.nodes()[1].ref()), OSMNodeID(input_way.nodes()[0].ref())}); } } +} +} diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 16bc3de53..90d9ee8e3 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace extractor +{ + return_code ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extractor_config) { @@ -87,13 +92,13 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac option_variables); if (option_variables.count("version")) { - SimpleLogger().Write() << OSRM_VERSION; + util::SimpleLogger().Write() << OSRM_VERSION; return return_code::exit; } if (option_variables.count("help")) { - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::exit; } @@ -102,10 +107,10 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac // parse config file if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) { - SimpleLogger().Write() << "Reading options from: " + util::SimpleLogger().Write() << "Reading options from: " << extractor_config.config_file_path.string(); std::string ini_file_contents = - read_file_lower_content(extractor_config.config_file_path); + util::read_file_lower_content(extractor_config.config_file_path); std::stringstream config_stream(ini_file_contents); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); @@ -114,13 +119,13 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac if (!option_variables.count("input")) { - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::exit; } } catch (std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return return_code::fail; } @@ -205,3 +210,5 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.edge_penalty_path.replace(pos, 8, ".osrm.edge_penalties"); } } +} +} diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index 751c10eb0..ec02fdc57 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -8,6 +8,11 @@ #include "util/simple_logger.hpp" +namespace osrm +{ +namespace extractor +{ + GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) : speed_profile(std::move(speed_profile)) { @@ -16,15 +21,15 @@ GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) void GraphCompressor::Compress(const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, RestrictionMap &restriction_map, - NodeBasedDynamicGraph &graph, + util::NodeBasedDynamicGraph &graph, CompressedEdgeContainer &geometry_compressor) { const unsigned original_number_of_nodes = graph.GetNumberOfNodes(); const unsigned original_number_of_edges = graph.GetNumberOfEdges(); - Percent progress(original_number_of_nodes); + util::Percent progress(original_number_of_nodes); - for (const NodeID node_v : osrm::irange(0u, original_number_of_nodes)) + for (const NodeID node_v : util::irange(0u, original_number_of_nodes)) { progress.printStatus(node_v); @@ -163,13 +168,13 @@ void GraphCompressor::Compress(const std::unordered_set &barrier_nodes, void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, unsigned original_number_of_edges, - const NodeBasedDynamicGraph &graph) const + const util::NodeBasedDynamicGraph &graph) const { unsigned new_node_count = 0; unsigned new_edge_count = 0; - for (const auto i : osrm::irange(0u, graph.GetNumberOfNodes())) + for (const auto i : util::irange(0u, graph.GetNumberOfNodes())) { if (graph.GetOutDegree(i) > 0) { @@ -177,8 +182,10 @@ void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i)); } } - SimpleLogger().Write() << "Node compression ratio: " + util::SimpleLogger().Write() << "Node compression ratio: " << new_node_count / (double)original_number_of_nodes; - SimpleLogger().Write() << "Edge compression ratio: " + util::SimpleLogger().Write() << "Edge compression ratio: " << new_edge_count / (double)original_number_of_edges; } +} +} diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp index 999559219..b3b6b612d 100644 --- a/src/extractor/import_edge.cpp +++ b/src/extractor/import_edge.cpp @@ -3,6 +3,11 @@ #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const { if (source == other.source) @@ -84,3 +89,5 @@ EdgeBasedEdge::EdgeBasedEdge(const NodeID source, backward(backward) { } +} +} diff --git a/src/extractor/raster_source.cpp b/src/extractor/raster_source.cpp index 3c9abb16f..840e79449 100644 --- a/src/extractor/raster_source.cpp +++ b/src/extractor/raster_source.cpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace extractor +{ + RasterSource::RasterSource(RasterGrid _raster_data, std::size_t _width, std::size_t _height, @@ -87,20 +92,20 @@ int SourceContainer::loadRasterSource(const std::string &path_string, const auto itr = LoadedSourcePaths.find(path_string); if (itr != LoadedSourcePaths.end()) { - SimpleLogger().Write() << "[source loader] Already loaded source '" << path_string + util::SimpleLogger().Write() << "[source loader] Already loaded source '" << path_string << "' at source_id " << itr->second; return itr->second; } int source_id = static_cast(LoadedSources.size()); - SimpleLogger().Write() << "[source loader] Loading from " << path_string << " ... "; + util::SimpleLogger().Write() << "[source loader] Loading from " << path_string << " ... "; TIMER_START(loading_source); boost::filesystem::path filepath(path_string); if (!boost::filesystem::exists(filepath)) { - throw osrm::exception("error reading: no such path"); + throw util::exception("error reading: no such path"); } RasterGrid rasterData{filepath, ncols, nrows}; @@ -110,7 +115,7 @@ int SourceContainer::loadRasterSource(const std::string &path_string, LoadedSourcePaths.emplace(path_string, source_id); LoadedSources.push_back(std::move(source)); - SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s"; + util::SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s"; return source_id; } @@ -120,7 +125,7 @@ RasterDatum SourceContainer::getRasterDataFromSource(unsigned int source_id, int { if (LoadedSources.size() < source_id + 1) { - throw osrm::exception("error reading: no such loaded source"); + throw util::exception("error reading: no such loaded source"); } BOOST_ASSERT(lat < (90 * COORDINATE_PRECISION)); @@ -138,7 +143,7 @@ SourceContainer::getRasterInterpolateFromSource(unsigned int source_id, int lon, { if (LoadedSources.size() < source_id + 1) { - throw osrm::exception("error reading: no such loaded source"); + throw util::exception("error reading: no such loaded source"); } BOOST_ASSERT(lat < (90 * COORDINATE_PRECISION)); @@ -149,3 +154,5 @@ SourceContainer::getRasterInterpolateFromSource(unsigned int source_id, int lon, const auto &found = LoadedSources[source_id]; return found.getRasterInterpolate(lon, lat); } +} +} diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index f5f84446e..d41b1c497 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -1,5 +1,10 @@ #include "extractor/restriction_map.hpp" +namespace osrm +{ +namespace extractor +{ + RestrictionMap::RestrictionMap(const std::vector &restriction_list) : m_count(0) { // decompose restriction consisting of a start, via and end node into a @@ -152,3 +157,5 @@ bool RestrictionMap::IsSourceNode(const NodeID node) const { return m_restriction_start_nodes.find(node) != m_restriction_start_nodes.end(); } +} +} diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index bb631894c..2c3641a4c 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -19,11 +19,16 @@ #include #include +namespace osrm +{ +namespace extractor +{ + namespace { int luaErrorCallback(lua_State *lua_state) { std::string error_msg = lua_tostring(lua_state, -1); - throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); + throw util::exception("ERROR occurred in profile script:\n" + error_msg); } } @@ -47,33 +52,33 @@ void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) if (use_turn_restrictions) { - SimpleLogger().Write() << "Using turn restrictions"; + util::SimpleLogger().Write() << "Using turn restrictions"; } else { - SimpleLogger().Write() << "Ignoring turn restrictions"; + util::SimpleLogger().Write() << "Ignoring turn restrictions"; } } void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) { - if (lua_function_exists(lua_state, "get_exceptions")) + if (util::lua_function_exists(lua_state, "get_exceptions")) { luabind::set_pcall_callback(&luaErrorCallback); // get list of turn restriction exceptions luabind::call_function(lua_state, "get_exceptions", boost::ref(restriction_exceptions)); const unsigned exception_count = restriction_exceptions.size(); - SimpleLogger().Write() << "Found " << exception_count + util::SimpleLogger().Write() << "Found " << exception_count << " exceptions to turn restrictions:"; for (const std::string &str : restriction_exceptions) { - SimpleLogger().Write() << " " << str; + util::SimpleLogger().Write() << " " << str; } } else { - SimpleLogger().Write() << "Found no exceptions to turn restrictions"; + util::SimpleLogger().Write() << "Found no exceptions to turn restrictions"; } } @@ -222,3 +227,5 @@ bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_st std::end(restriction_exceptions), current_string); }); } +} +} diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index f4fae0da3..247291f74 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -17,6 +17,11 @@ #include #include + +namespace osrm +{ +namespace extractor +{ namespace { // wrapper method as luabind doesn't automatically overload funcs w/ default parameters @@ -32,13 +37,13 @@ int luaErrorCallback(lua_State *state) std::string error_msg = lua_tostring(state, -1); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); + throw util::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } ScriptingEnvironment::ScriptingEnvironment(const std::string &file_name) : file_name(file_name) { - SimpleLogger().Write() << "Using script " << file_name; + util::SimpleLogger().Write() << "Using script " << file_name; } void ScriptingEnvironment::InitLuaState(lua_State *lua_state) @@ -49,11 +54,11 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) // open utility libraries string library; luaL_openlibs(lua_state); - luaAddScriptFolderToLoadPath(lua_state, file_name.c_str()); + util::luaAddScriptFolderToLoadPath(lua_state, file_name.c_str()); // Add our function to the state's global scope luabind::module(lua_state) - [luabind::def("print", LUA_print), + [luabind::def("print", util::LUA_print), luabind::def("durationIsValid", durationIsValid), luabind::def("parseDuration", parseDuration), luabind::class_("sources") @@ -110,9 +115,9 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) luabind::class_("EdgeTarget") .property("lat", &ExternalMemoryNode::lat) .property("lon", &ExternalMemoryNode::lon), - luabind::class_("Coordinate") - .property("lat", &FixedPointCoordinate::lat) - .property("lon", &FixedPointCoordinate::lon), + luabind::class_("Coordinate") + .property("lat", &util::FixedPointCoordinate::lat) + .property("lon", &util::FixedPointCoordinate::lon), luabind::class_("RasterDatum") .property("datum", &RasterDatum::datum) .def("invalid_data", &RasterDatum::get_invalid)]; @@ -122,7 +127,7 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) luabind::object error_msg(luabind::from_stack(lua_state, -1)); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); + throw util::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } @@ -141,3 +146,5 @@ lua_State *ScriptingEnvironment::GetLuaState() return ref.get(); } +} +} diff --git a/src/server/connection.cpp b/src/server/connection.cpp index 0a93e18af..58718a050 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -10,7 +10,9 @@ #include #include -namespace http +namespace osrm +{ +namespace server { Connection::Connection(boost::asio::io_service &io_service, RequestHandler &handler) @@ -38,14 +40,14 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t } // no error detected, let's parse the request - compression_type compression_type(no_compression); - osrm::tribool result; + http::compression_type compression_type(http::no_compression); + util::tribool result; std::tie(result, compression_type) = request_parser.parse(current_request, incoming_data_buffer.data(), incoming_data_buffer.data() + bytes_transferred); // the request has been parsed - if (result == osrm::tribool::yes) + if (result == util::tribool::yes) { current_request.endpoint = TCP_socket.remote_endpoint().address(); request_handler.handle_request(current_request, current_reply); @@ -56,7 +58,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t // compress the result w/ gzip/deflate if requested switch (compression_type) { - case deflate_rfc1951: + case http::deflate_rfc1951: // use deflate for compression current_reply.headers.insert(current_reply.headers.begin(), {"Content-Encoding", "deflate"}); @@ -65,7 +67,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t output_buffer = current_reply.headers_to_buffers(); output_buffer.push_back(boost::asio::buffer(compressed_output)); break; - case gzip_rfc1952: + case http::gzip_rfc1952: // use gzip for compression current_reply.headers.insert(current_reply.headers.begin(), {"Content-Encoding", "gzip"}); @@ -74,7 +76,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t output_buffer = current_reply.headers_to_buffers(); output_buffer.push_back(boost::asio::buffer(compressed_output)); break; - case no_compression: + case http::no_compression: // don't use any compression current_reply.set_uncompressed_size(); output_buffer = current_reply.to_buffers(); @@ -86,9 +88,9 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t strand.wrap(boost::bind(&Connection::handle_write, this->shared_from_this(), boost::asio::placeholders::error))); } - else if (result == osrm::tribool::no) + else if (result == util::tribool::no) { // request is not parseable - current_reply = reply::stock_reply(reply::bad_request); + current_reply = http::reply::stock_reply(http::reply::bad_request); boost::asio::async_write( TCP_socket, current_reply.to_buffers(), @@ -118,14 +120,14 @@ void Connection::handle_write(const boost::system::error_code &error) } std::vector Connection::compress_buffers(const std::vector &uncompressed_data, - const compression_type compression_type) + const http::compression_type compression_type) { boost::iostreams::gzip_params compression_parameters; // there's a trade-off between speed and size. speed wins compression_parameters.level = boost::iostreams::zlib::best_speed; // check which compression flavor is used - if (deflate_rfc1951 == compression_type) + if (http::deflate_rfc1951 == compression_type) { compression_parameters.noheader = true; } @@ -141,3 +143,4 @@ std::vector Connection::compress_buffers(const std::vector &uncompre return compressed_data; } } +} diff --git a/src/server/http/reply.cpp b/src/server/http/reply.cpp index be6e3bfbc..87faa1ba1 100644 --- a/src/server/http/reply.cpp +++ b/src/server/http/reply.cpp @@ -2,6 +2,10 @@ #include +namespace osrm +{ +namespace server +{ namespace http { @@ -101,3 +105,5 @@ boost::asio::const_buffer reply::status_to_buffer(const reply::status_type statu reply::reply() : status(ok) {} } +} +} diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 00d1d8f23..a579a039d 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -20,22 +20,27 @@ #include #include +namespace osrm +{ +namespace server +{ + RequestHandler::RequestHandler() : routing_machine(nullptr) {} void RequestHandler::handle_request(const http::request ¤t_request, http::reply ¤t_reply) { - osrm::json::Object json_result; + util::json::Object json_result; // parse command try { std::string request_string; - URIDecode(current_request.uri, request_string); + util::URIDecode(current_request.uri, request_string); // deactivated as GCC apparently does not implement that, not even in 4.9 // std::time_t t = std::time(nullptr); - // SimpleLogger().Write() << std::put_time(std::localtime(&t), "%m-%d-%Y %H:%M:%S") << + // util::SimpleLogger().Write() << std::put_time(std::localtime(&t), "%m-%d-%Y %H:%M:%S") << // " " << current_request.endpoint.to_string() << " " << // current_request.referrer << ( 0 == current_request.referrer.length() ? "- " :" ") << // current_request.agent << ( 0 == current_request.agent.length() ? "- " :" ") << @@ -48,7 +53,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, time_stamp = localtime(<ime); // log timestamp - SimpleLogger().Write() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday + util::SimpleLogger().Write() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday << "-" << (time_stamp->tm_mon + 1 < 10 ? "0" : "") << (time_stamp->tm_mon + 1) << "-" << 1900 + time_stamp->tm_year << " " << (time_stamp->tm_hour < 10 ? "0" : "") @@ -61,7 +66,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, << (0 == current_request.agent.length() ? "- " : " ") << request_string; - RouteParameters route_parameters; + engine::RouteParameters route_parameters; APIGrammarParser api_parser(&route_parameters); auto api_iterator = request_string.begin(); @@ -116,7 +121,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, std::to_string(current_reply.content.size())); if ("gpx" == route_parameters.output_format) { // gpx file - osrm::json::gpx_render(current_reply.content, json_result.values["route"]); + util::json::gpx_render(current_reply.content, json_result.values["route"]); current_reply.headers.emplace_back("Content-Type", "application/gpx+xml; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", @@ -124,14 +129,14 @@ void RequestHandler::handle_request(const http::request ¤t_request, } else if (route_parameters.jsonp_parameter.empty()) { // json file - osrm::json::render(current_reply.content, json_result); + util::json::render(current_reply.content, json_result); current_reply.headers.emplace_back("Content-Type", "application/json; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.json\""); } else { // jsonp - osrm::json::render(current_reply.content, json_result); + util::json::render(current_reply.content, json_result); current_reply.headers.emplace_back("Content-Type", "text/javascript; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.js\""); @@ -145,9 +150,11 @@ void RequestHandler::handle_request(const http::request ¤t_request, { current_reply = http::reply::stock_reply(http::reply::internal_server_error); ; - SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() + util::SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() << ", uri: " << current_request.uri; } } void RequestHandler::RegisterRoutingMachine(OSRM *osrm) { routing_machine = osrm; } +} +} diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 818ed44b3..3d6149d06 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -10,197 +10,199 @@ #include -namespace http +namespace osrm +{ +namespace server { RequestParser::RequestParser() : state(internal_state::method_start), current_header({"", ""}), - selected_compression(no_compression), is_post_header(false), content_length(0) + selected_compression(http::no_compression), is_post_header(false), content_length(0) { } -std::tuple -RequestParser::parse(request ¤t_request, char *begin, char *end) +std::tuple +RequestParser::parse(http::request ¤t_request, char *begin, char *end) { while (begin != end) { - osrm::tribool result = consume(current_request, *begin++); - if (result != osrm::tribool::indeterminate) + util::tribool result = consume(current_request, *begin++); + if (result != util::tribool::indeterminate) { return std::make_tuple(result, selected_compression); } } - osrm::tribool result = osrm::tribool::indeterminate; + util::tribool result = util::tribool::indeterminate; if (state == internal_state::post_request && content_length <= 0) { - result = osrm::tribool::yes; + result = util::tribool::yes; } return std::make_tuple(result, selected_compression); } -osrm::tribool RequestParser::consume(request ¤t_request, const char input) +util::tribool RequestParser::consume(http::request ¤t_request, const char input) { switch (state) { case internal_state::method_start: if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } if (input == 'P') { state = internal_state::post_O; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } state = internal_state::method; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::post_O: if (input == 'O') { state = internal_state::post_S; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_S: if (input == 'S') { state = internal_state::post_T; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_T: if (input == 'T') { is_post_header = true; state = internal_state::method; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_request: current_request.uri.push_back(input); --content_length; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::method: if (input == ' ') { state = internal_state::uri; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::uri_start: if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::uri; current_request.uri.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::uri: if (input == ' ') { state = internal_state::http_version_h; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_request.uri.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::http_version_h: if (input == 'H') { state = internal_state::http_version_t_1; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_t_1: if (input == 'T') { state = internal_state::http_version_t_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_t_2: if (input == 'T') { state = internal_state::http_version_p; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_p: if (input == 'P') { state = internal_state::http_version_slash; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_slash: if (input == '/') { state = internal_state::http_version_major_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_major_start: if (is_digit(input)) { state = internal_state::http_version_major; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_major: if (input == '.') { state = internal_state::http_version_minor_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_digit(input)) { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_minor_start: if (is_digit(input)) { state = internal_state::http_version_minor; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_minor: if (input == '\r') { state = internal_state::expecting_newline_1; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_digit(input)) { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::expecting_newline_1: if (input == '\n') { state = internal_state::header_line_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::header_line_start: if (boost::iequals(current_header.name, "Accept-Encoding")) { /* giving gzip precedence over deflate */ if (boost::icontains(current_header.value, "deflate")) { - selected_compression = deflate_rfc1951; + selected_compression = http::deflate_rfc1951; } if (boost::icontains(current_header.value, "gzip")) { - selected_compression = gzip_rfc1952; + selected_compression = http::gzip_rfc1952; } } @@ -228,77 +230,77 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) { if (!boost::icontains(current_header.value, "application/x-www-form-urlencoded")) { - return osrm::tribool::no; + return util::tribool::no; } } if (input == '\r') { state = internal_state::expecting_newline_3; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::header_name; current_header.clear(); current_header.name.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::header_lws: if (input == '\r') { state = internal_state::expecting_newline_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (input == ' ' || input == '\t') { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::header_name: if (input == ':') { state = internal_state::space_before_header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_header.name.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::space_before_header_value: if (input == ' ') { state = internal_state::header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::header_value: if (input == '\r') { state = internal_state::expecting_newline_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_header.value.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::expecting_newline_2: if (input == '\n') { state = internal_state::header_line_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::expecting_newline_3: if (input == '\n') { @@ -309,13 +311,13 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) current_request.uri.push_back('?'); } state = internal_state::post_request; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::yes; + return util::tribool::yes; } - return osrm::tribool::no; + return util::tribool::no; default: // should never be reached - return input == '\n' ? osrm::tribool::yes : osrm::tribool::no; + return input == '\n' ? util::tribool::yes : util::tribool::no; } } @@ -363,3 +365,4 @@ bool RequestParser::is_digit(const int character) const return character >= '0' && character <= '9'; } } +} diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 068e4b392..4c6b3deb1 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -12,45 +12,53 @@ #include #include -using EdgeData = QueryEdge::EdgeData; -using QueryGraph = StaticGraph; +namespace osrm +{ +namespace tools +{ + +using EdgeData = contractor::QueryEdge::EdgeData; +using QueryGraph = util::StaticGraph; + +} +} int main(int argc, char *argv[]) { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { if (argc != 2) { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; return 1; } boost::filesystem::path hsgr_path(argv[1]); - std::vector node_list; - std::vector edge_list; - SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); + std::vector node_list; + std::vector edge_list; + osrm::util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); unsigned m_check_sum = 0; unsigned m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); - SimpleLogger().Write() << "expecting " << m_number_of_nodes + osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes << " nodes, checksum: " << m_check_sum; BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); - SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() + osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() << " edges"; - auto m_query_graph = std::make_shared(node_list, edge_list); + auto m_query_graph = std::make_shared(node_list, edge_list); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - Percent progress(m_query_graph->GetNumberOfNodes()); - for (const auto node_u : osrm::irange(0u, m_query_graph->GetNumberOfNodes())) + osrm::util::Percent progress(m_query_graph->GetNumberOfNodes()); + for (const auto node_u : osrm::util::irange(0u, m_query_graph->GetNumberOfNodes())) { for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) { - const EdgeData &data = m_query_graph->GetEdgeData(eid); + const osrm::tools::EdgeData &data = m_query_graph->GetEdgeData(eid); if (!data.shortcut) { continue; @@ -59,7 +67,7 @@ int main(int argc, char *argv[]) const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); if (SPECIAL_EDGEID == edge_id_1) { - throw osrm::exception("cannot find first segment of edge (" + + throw osrm::util::exception("cannot find first segment of edge (" + std::to_string(node_u) + "," + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + std::to_string(eid)); @@ -67,7 +75,7 @@ int main(int argc, char *argv[]) const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); if (SPECIAL_EDGEID == edge_id_2) { - throw osrm::exception("cannot find second segment of edge (" + + throw osrm::util::exception("cannot find second segment of edge (" + std::to_string(node_u) + "," + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + std::to_string(eid)); @@ -76,11 +84,11 @@ int main(int argc, char *argv[]) progress.printStatus(node_u); } m_query_graph.reset(); - SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; + osrm::util::SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } diff --git a/src/tools/components.cpp b/src/tools/components.cpp index 411fca66d..ffefa984f 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -26,7 +26,9 @@ #include #include -namespace +namespace osrm +{ +namespace tools { struct TarjanEdgeData @@ -37,7 +39,7 @@ struct TarjanEdgeData unsigned name_id; }; -using TarjanGraph = StaticGraph; +using TarjanGraph = util::StaticGraph; using TarjanEdge = TarjanGraph::InputEdge; void deleteFileIfExists(const std::string &file_name) @@ -47,27 +49,26 @@ void deleteFileIfExists(const std::string &file_name) boost::filesystem::remove(file_name); } } -} std::size_t loadGraph(const char *path, - std::vector &coordinate_list, + std::vector &coordinate_list, std::vector &graph_edge_list) { std::ifstream input_stream(path, std::ifstream::in | std::ifstream::binary); if (!input_stream.is_open()) { - throw osrm::exception("Cannot open osrm file"); + throw util::exception("Cannot open osrm file"); } // load graph data - std::vector edge_list; + std::vector edge_list; std::vector traffic_light_node_list; std::vector barrier_node_list; - auto number_of_nodes = loadNodesFromFile(input_stream, barrier_node_list, + auto number_of_nodes = util::loadNodesFromFile(input_stream, barrier_node_list, traffic_light_node_list, coordinate_list); - loadEdgesFromFile(input_stream, edge_list); + util::loadEdgesFromFile(input_stream, edge_list); traffic_light_node_list.clear(); traffic_light_node_list.shrink_to_fit(); @@ -94,46 +95,48 @@ std::size_t loadGraph(const char *path, return number_of_nodes; } +} +} int main(int argc, char *argv[]) { - std::vector coordinate_list; + std::vector coordinate_list; - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { // enable logging if (argc < 2) { - SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; + osrm::util::SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; return -1; } - std::vector graph_edge_list; - auto number_of_nodes = loadGraph(argv[1], coordinate_list, graph_edge_list); + std::vector graph_edge_list; + auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); - const auto graph = std::make_shared(number_of_nodes, graph_edge_list); + const auto graph = std::make_shared(number_of_nodes, graph_edge_list); graph_edge_list.clear(); graph_edge_list.shrink_to_fit(); - SimpleLogger().Write() << "Starting SCC graph traversal"; + osrm::util::SimpleLogger().Write() << "Starting SCC graph traversal"; - auto tarjan = osrm::make_unique>(graph); + auto tarjan = osrm::util::make_unique>(graph); tarjan->run(); - SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() + osrm::util::SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() << " many components"; - SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; + osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; // output TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist - deleteFileIfExists("component.dbf"); - deleteFileIfExists("component.shx"); - deleteFileIfExists("component.shp"); + osrm::tools::deleteFileIfExists("component.dbf"); + osrm::tools::deleteFileIfExists("component.shx"); + osrm::tools::deleteFileIfExists("component.shp"); - Percent percentage(graph->GetNumberOfNodes()); + osrm::util::Percent percentage(graph->GetNumberOfNodes()); OGRRegisterAll(); @@ -142,13 +145,13 @@ int main(int argc, char *argv[]) OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); if (nullptr == po_driver) { - throw osrm::exception("ESRI Shapefile driver not available"); + throw osrm::util::exception("ESRI Shapefile driver not available"); } auto *po_datasource = po_driver->CreateDataSource("component.shp", nullptr); if (nullptr == po_datasource) { - throw osrm::exception("Creation of output file failed"); + throw osrm::util::exception("Creation of output file failed"); } auto *po_srs = new OGRSpatialReference(); @@ -158,26 +161,26 @@ int main(int argc, char *argv[]) if (nullptr == po_layer) { - throw osrm::exception("Layer creation failed."); + throw osrm::util::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); - SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. + osrm::util::SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; uint64_t total_network_length = 0; percentage.reinit(graph->GetNumberOfNodes()); TIMER_START(SCC_OUTPUT); - for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes())) + for (const NodeID source : osrm::util::irange(0u, graph->GetNumberOfNodes())) { percentage.printIncrement(); for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { - const TarjanGraph::NodeIterator target = graph->GetTarget(current_edge); + const auto target = graph->GetTarget(current_edge); if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source)) { total_network_length += - 100 * coordinate_calculation::greatCircleDistance( + 100 * osrm::util::coordinate_calculation::greatCircleDistance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); @@ -193,17 +196,17 @@ int main(int argc, char *argv[]) if (size_of_containing_component < 1000) { OGRLineString line_string; - line_string.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, - coordinate_list[source].lat / COORDINATE_PRECISION); - line_string.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, - coordinate_list[target].lat / COORDINATE_PRECISION); + line_string.addPoint(coordinate_list[source].lon / osrm::COORDINATE_PRECISION, + coordinate_list[source].lat / osrm::COORDINATE_PRECISION); + line_string.addPoint(coordinate_list[target].lon / osrm::COORDINATE_PRECISION, + coordinate_list[target].lat / osrm::COORDINATE_PRECISION); OGRFeature *po_feature = OGRFeature::CreateFeature(po_layer->GetLayerDefn()); po_feature->SetGeometry(&line_string); if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) { - throw osrm::exception("Failed to create feature in shapefile."); + throw osrm::util::exception("Failed to create feature in shapefile."); } OGRFeature::DestroyFeature(po_feature); } @@ -213,18 +216,18 @@ int main(int argc, char *argv[]) OGRSpatialReference::DestroySpatialReference(po_srs); OGRDataSource::DestroyDataSource(po_datasource); TIMER_STOP(SCC_OUTPUT); - SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. + osrm::util::SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; - SimpleLogger().Write() << "total network distance: " + osrm::util::SimpleLogger().Write() << "total network distance: " << static_cast(total_network_length / 100 / 1000.) << " km"; - SimpleLogger().Write() << "finished component analysis"; + osrm::util::SimpleLogger().Write() << "finished component analysis"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index f5f994bcb..151965281 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -11,28 +11,30 @@ #include #include +using namespace osrm; + int main(int argc, char *argv[]) try { - LogPolicy::GetInstance().Unmute(); - ContractorConfig contractor_config; + util::LogPolicy::GetInstance().Unmute(); + contractor::ContractorConfig contractor_config; - const return_code result = ContractorOptions::ParseArguments(argc, argv, contractor_config); + const contractor::return_code result = contractor::ContractorOptions::ParseArguments(argc, argv, contractor_config); - if (return_code::fail == result) + if (contractor::return_code::fail == result) { return EXIT_FAILURE; } - if (return_code::exit == result) + if (contractor::return_code::exit == result) { return EXIT_SUCCESS; } - ContractorOptions::GenerateOutputFilesNames(contractor_config); + contractor::ContractorOptions::GenerateOutputFilesNames(contractor_config); if (1 > contractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; + util::SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return EXIT_FAILURE; } @@ -40,43 +42,43 @@ int main(int argc, char *argv[]) try if (recommended_num_threads != contractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "The recommended number of threads is " + util::SimpleLogger().Write(logWARNING) << "The recommended number of threads is " << recommended_num_threads << "! This setting may have performance side-effects."; } if (!boost::filesystem::is_regular_file(contractor_config.osrm_input_path)) { - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "Input file " << contractor_config.osrm_input_path.string() << " not found!"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(contractor_config.profile_path)) { - SimpleLogger().Write(logWARNING) << "Profile " << contractor_config.profile_path.string() + util::SimpleLogger().Write(logWARNING) << "Profile " << contractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } - SimpleLogger().Write() << "Input file: " + util::SimpleLogger().Write() << "Input file: " << contractor_config.osrm_input_path.filename().string(); - SimpleLogger().Write() << "Profile: " << contractor_config.profile_path.filename().string(); - SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; + util::SimpleLogger().Write() << "Profile: " << contractor_config.profile_path.filename().string(); + util::SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; tbb::task_scheduler_init init(contractor_config.requested_num_threads); - return Prepare(contractor_config).Run(); + return contractor::Prepare(contractor_config).Run(); } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 899fba4c7..b459465f2 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -19,10 +19,6 @@ #include "osrm/coordinate.hpp" -using RTreeLeaf = BaseDataFacade::RTreeLeaf; -using RTreeNode = StaticRTree::vector, true>::TreeNode; -using QueryGraph = StaticGraph; - #ifdef __linux__ #include #endif @@ -36,6 +32,20 @@ using QueryGraph = StaticGraph; #include #include +// FIXME remove after move to datastore +using namespace osrm::engine::datafacade; +using namespace osrm::datastore; +using namespace osrm; + +using RTreeLeaf = typename engine::datafacade::BaseDataFacade::RTreeLeaf; +using RTreeNode = util::StaticRTree::vector, true>::TreeNode; +using QueryGraph = util::StaticGraph; + +namespace osrm +{ +namespace tools +{ + // delete a shared memory region. report warning if it could not be deleted void deleteRegion(const SharedDataType region) { @@ -62,13 +72,16 @@ void deleteRegion(const SharedDataType region) } }(); - SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; + util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } +} +} + int main(const int argc, const char *argv[]) try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); SharedBarriers barrier; #ifdef __linux__ @@ -76,7 +89,7 @@ int main(const int argc, const char *argv[]) try const bool lock_flags = MCL_CURRENT | MCL_FUTURE; if (-1 == mlockall(lock_flags)) { - SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; + util::SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; } #endif @@ -91,45 +104,45 @@ int main(const int argc, const char *argv[]) try barrier.pending_update_mutex.unlock(); } - SimpleLogger().Write(logDEBUG) << "Checking input parameters"; + util::SimpleLogger().Write(logDEBUG) << "Checking input parameters"; std::unordered_map server_paths; - if (!GenerateDataStoreOptions(argc, argv, server_paths)) + if (!util::GenerateDataStoreOptions(argc, argv, server_paths)) { return EXIT_SUCCESS; } if (server_paths.find("hsgrdata") == server_paths.end()) { - throw osrm::exception("no hsgr file found"); + throw util::exception("no hsgr file found"); } if (server_paths.find("ramindex") == server_paths.end()) { - throw osrm::exception("no ram index file found"); + throw util::exception("no ram index file found"); } if (server_paths.find("fileindex") == server_paths.end()) { - throw osrm::exception("no leaf index file found"); + throw util::exception("no leaf index file found"); } if (server_paths.find("nodesdata") == server_paths.end()) { - throw osrm::exception("no nodes file found"); + throw util::exception("no nodes file found"); } if (server_paths.find("edgesdata") == server_paths.end()) { - throw osrm::exception("no edges file found"); + throw util::exception("no edges file found"); } if (server_paths.find("namesdata") == server_paths.end()) { - throw osrm::exception("no names file found"); + throw util::exception("no names file found"); } if (server_paths.find("geometry") == server_paths.end()) { - throw osrm::exception("no geometry file found"); + throw util::exception("no geometry file found"); } if (server_paths.find("core") == server_paths.end()) { - throw osrm::exception("no core file found"); + throw util::exception("no core file found"); } auto paths_iterator = server_paths.find("hsgrdata"); @@ -173,19 +186,19 @@ int main(const int argc, const char *argv[]) try // determine segment to use bool segment2_in_use = SharedMemory::RegionExists(LAYOUT_2); - const SharedDataType layout_region = [&] + const engine::datafacade::SharedDataType layout_region = [&] { return segment2_in_use ? LAYOUT_1 : LAYOUT_2; }(); - const SharedDataType data_region = [&] + const engine::datafacade::SharedDataType data_region = [&] { return segment2_in_use ? DATA_1 : DATA_2; }(); - const SharedDataType previous_layout_region = [&] + const engine::datafacade::SharedDataType previous_layout_region = [&] { return segment2_in_use ? LAYOUT_2 : LAYOUT_1; }(); - const SharedDataType previous_data_region = [&] + const engine::datafacade::SharedDataType previous_data_region = [&] { return segment2_in_use ? DATA_2 : DATA_1; }(); @@ -198,15 +211,15 @@ int main(const int argc, const char *argv[]) try file_index_path.length() + 1); // collect number of elements to store in shared memory object - SimpleLogger().Write() << "load names from: " << names_data_path; + util::SimpleLogger().Write() << "load names from: " << names_data_path; // number of entries in name index boost::filesystem::ifstream name_stream(names_data_path, std::ios::binary); unsigned name_blocks = 0; name_stream.read((char *)&name_blocks, sizeof(unsigned)); shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_OFFSETS, name_blocks); - shared_layout_ptr->SetBlockSize::BlockT>( + shared_layout_ptr->SetBlockSize::BlockT>( SharedDataLayout::NAME_BLOCKS, name_blocks); - SimpleLogger().Write() << "name offsets size: " << name_blocks; + util::SimpleLogger().Write() << "name offsets size: " << name_blocks; BOOST_ASSERT_MSG(0 != name_blocks, "name file broken"); unsigned number_of_chars = 0; @@ -223,9 +236,9 @@ int main(const int argc, const char *argv[]) try number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_ID_LIST, number_of_original_edges); - shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, + shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, number_of_original_edges); - shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, + shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, number_of_original_edges); // note: there are 32 geometry indicators in one unsigned block shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_INDICATORS, @@ -233,16 +246,16 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream hsgr_input_stream(hsgr_path, std::ios::binary); - FingerPrint fingerprint_valid = FingerPrint::GetValid(); - FingerPrint fingerprint_loaded; - hsgr_input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); + util::FingerPrint fingerprint_valid = util::FingerPrint::GetValid(); + util::FingerPrint fingerprint_loaded; + hsgr_input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); if (fingerprint_loaded.TestGraphUtil(fingerprint_valid)) { - SimpleLogger().Write(logDEBUG) << "Fingerprint checked out ok"; + util::SimpleLogger().Write(logDEBUG) << "Fingerprint checked out ok"; } else { - SimpleLogger().Write(logWARNING) << ".hsgr was prepared with different build. " + util::SimpleLogger().Write(logWARNING) << ".hsgr was prepared with different build. " "Reprocess to get rid of this warning."; } @@ -279,7 +292,7 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream timestamp_stream(timestamp_path); if (!timestamp_stream) { - SimpleLogger().Write(logWARNING) << timestamp_path << " not found. setting to default"; + util::SimpleLogger().Write(logWARNING) << timestamp_path << " not found. setting to default"; } else { @@ -309,7 +322,7 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream nodes_input_stream(nodes_data_path, std::ios::binary); unsigned coordinate_list_size = 0; nodes_input_stream.read((char *)&coordinate_list_size, sizeof(unsigned)); - shared_layout_ptr->SetBlockSize(SharedDataLayout::COORDINATE_LIST, + shared_layout_ptr->SetBlockSize(SharedDataLayout::COORDINATE_LIST, coordinate_list_size); // load geometries sizes @@ -326,7 +339,7 @@ int main(const int argc, const char *argv[]) try shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_LIST, number_of_compressed_geometries); // allocate shared memory block - SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() + util::SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() << " bytes"; SharedMemory *shared_memory = SharedMemoryFactory::Get(data_region, shared_layout_ptr->GetSizeOfLayout()); @@ -390,19 +403,19 @@ int main(const int argc, const char *argv[]) try unsigned *name_id_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::NAME_ID_LIST); - TravelMode *travel_mode_ptr = shared_layout_ptr->GetBlockPtr( + extractor::TravelMode *travel_mode_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::TRAVEL_MODE); - TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( + extractor::TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::TURN_INSTRUCTION); unsigned *geometries_indicator_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::GEOMETRIES_INDICATORS); - OriginalEdgeData current_edge_data; + extractor::OriginalEdgeData current_edge_data; for (unsigned i = 0; i < number_of_original_edges; ++i) { - edges_input_stream.read((char *)&(current_edge_data), sizeof(OriginalEdgeData)); + edges_input_stream.read((char *)&(current_edge_data), sizeof(extractor::OriginalEdgeData)); via_node_ptr[i] = current_edge_data.via_node; name_id_ptr[i] = current_edge_data.name_id; travel_mode_ptr[i] = current_edge_data.travel_mode; @@ -456,15 +469,15 @@ int main(const int argc, const char *argv[]) try } // Loading list of coordinates - FixedPointCoordinate *coordinates_ptr = - shared_layout_ptr->GetBlockPtr( + util::FixedPointCoordinate *coordinates_ptr = + shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::COORDINATE_LIST); - QueryNode current_node; + extractor::QueryNode current_node; for (unsigned i = 0; i < coordinate_list_size; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); - coordinates_ptr[i] = FixedPointCoordinate(current_node.lat, current_node.lon); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); + coordinates_ptr[i] = util::FixedPointCoordinate(current_node.lat, current_node.lon); } nodes_input_stream.close(); @@ -552,20 +565,21 @@ int main(const int argc, const char *argv[]) try data_timestamp_ptr->layout = layout_region; data_timestamp_ptr->data = data_region; data_timestamp_ptr->timestamp += 1; - deleteRegion(previous_data_region); - deleteRegion(previous_layout_region); - SimpleLogger().Write() << "all data loaded"; + tools::deleteRegion(previous_data_region); + tools::deleteRegion(previous_layout_region); + util::SimpleLogger().Write() << "all data loaded"; shared_layout_ptr->PrintInformation(); + return EXIT_SUCCESS; } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) << "Please provide more memory or disable locking the virtual " + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or disable locking the virtual " "address space (note: this makes OSRM swap, i.e. slow)"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); } diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 1d34a084f..7f317cb8d 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -8,55 +8,57 @@ #include #include +using namespace osrm; + int main(int argc, char *argv[]) try { - LogPolicy::GetInstance().Unmute(); - ExtractorConfig extractor_config; + util::LogPolicy::GetInstance().Unmute(); + extractor::ExtractorConfig extractor_config; - const return_code result = ExtractorOptions::ParseArguments(argc, argv, extractor_config); + const extractor::return_code result = extractor::ExtractorOptions::ParseArguments(argc, argv, extractor_config); - if (return_code::fail == result) + if (extractor::return_code::fail == result) { return EXIT_FAILURE; } - if (return_code::exit == result) + if (extractor::return_code::exit == result) { return EXIT_SUCCESS; } - ExtractorOptions::GenerateOutputFilesNames(extractor_config); + extractor::ExtractorOptions::GenerateOutputFilesNames(extractor_config); if (1 > extractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; + util::SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(extractor_config.input_path)) { - SimpleLogger().Write(logWARNING) << "Input file " << extractor_config.input_path.string() + util::SimpleLogger().Write(logWARNING) << "Input file " << extractor_config.input_path.string() << " not found!"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(extractor_config.profile_path)) { - SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string() + util::SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } - return extractor(extractor_config).run(); + return extractor::extractor(extractor_config).run(); } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index b29e78e85..dda28000e 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" @@ -20,7 +19,12 @@ #include #include -const unsigned number_of_elements = 268435456; +namespace osrm +{ +namespace tools +{ + +const unsigned NUMBER_OF_ELEMENTS = 268435456; struct Statistics { @@ -41,33 +45,34 @@ void runStatistics(std::vector &timings_vector, Statistics &stats) stats.dev = std::sqrt(primary_sq_sum / timings_vector.size() - (stats.mean * stats.mean)); } +} +} + int main(int argc, char *argv[]) { #ifdef __FreeBSD__ - SimpleLogger().Write() << "Not supported on FreeBSD"; + osrm::util::SimpleLogger().Write() << "Not supported on FreeBSD"; return 0; #endif #ifdef _WIN32 - SimpleLogger().Write() << "Not supported on Windows"; + osrm::util::SimpleLogger().Write() << "Not supported on Windows"; return 0; #else - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); boost::filesystem::path test_path; try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - if (1 == argc) { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; return -1; } test_path = boost::filesystem::path(argv[1]); test_path /= "osrm.tst"; - SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); + osrm::util::SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); // create files for testing if (2 == argc) @@ -75,17 +80,17 @@ int main(int argc, char *argv[]) // create file to test if (boost::filesystem::exists(test_path)) { - throw osrm::exception("Data file already exists"); + throw osrm::util::exception("Data file already exists"); } - int *random_array = new int[number_of_elements]; - std::generate(random_array, random_array + number_of_elements, std::rand); + int *random_array = new int[osrm::tools::NUMBER_OF_ELEMENTS]; + std::generate(random_array, random_array + osrm::tools::NUMBER_OF_ELEMENTS, std::rand); #ifdef __APPLE__ FILE *fd = fopen(test_path.string().c_str(), "w"); fcntl(fileno(fd), F_NOCACHE, 1); fcntl(fileno(fd), F_RDAHEAD, 0); TIMER_START(write_1gb); - write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned)); + write(fileno(fd), (char *)random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); TIMER_STOP(write_1gb); fclose(fd); #endif @@ -94,24 +99,24 @@ int main(int argc, char *argv[]) open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU); if (-1 == file_desc) { - throw osrm::exception("Could not open random data file"); + throw osrm::util::exception("Could not open random data file"); } TIMER_START(write_1gb); - int ret = write(file_desc, random_array, number_of_elements * sizeof(unsigned)); + int ret = write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); if (0 > ret) { - throw osrm::exception("could not write random data file"); + throw osrm::util::exception("could not write random data file"); } TIMER_STOP(write_1gb); close(file_desc); #endif delete[] random_array; - SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) + osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) << "s"; - SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) + osrm::util::SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) << "MB/sec"; - SimpleLogger().Write(logDEBUG) + osrm::util::SimpleLogger().Write(logDEBUG) << "finished creation of random data. Flush disk cache now!"; } else @@ -119,15 +124,15 @@ int main(int argc, char *argv[]) // Run Non-Cached I/O benchmarks if (!boost::filesystem::exists(test_path)) { - throw osrm::exception("data file does not exist"); + throw osrm::util::exception("data file does not exist"); } // volatiles do not get optimized - Statistics stats; + osrm::tools::Statistics stats; #ifdef __APPLE__ volatile unsigned single_block[1024]; - char *raw_array = new char[number_of_elements * sizeof(unsigned)]; + char *raw_array = new char[osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)]; FILE *fd = fopen(test_path.string().c_str(), "r"); fcntl(fileno(fd), F_NOCACHE, 1); fcntl(fileno(fd), F_RDAHEAD, 0); @@ -138,33 +143,33 @@ int main(int argc, char *argv[]) int file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); if (-1 == file_desc) { - SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); return -1; } - char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned)); + char *raw_array = (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); #endif TIMER_START(read_1gb); #ifdef __APPLE__ - read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned)); + read(fileno(fd), raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); close(fileno(fd)); fd = fopen(test_path.string().c_str(), "r"); #endif #ifdef __linux__ - int ret = read(file_desc, raw_array, number_of_elements * sizeof(unsigned)); - SimpleLogger().Write(logDEBUG) << "read " << ret + int ret = read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + osrm::util::SimpleLogger().Write(logDEBUG) << "read " << ret << " bytes, error: " << strerror(errno); close(file_desc); file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); - SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); #endif TIMER_STOP(read_1gb); - SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; - SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed + osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; + osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec"; std::vector timing_results_raw_random; - SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; #ifdef __APPLE__ fseek(fd, 0, SEEK_SET); @@ -173,7 +178,7 @@ int main(int argc, char *argv[]) lseek(file_desc, 0, SEEK_SET); #endif // make 1000 random access, time each I/O seperately - unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) / 4096; + unsigned number_of_blocks = (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution uniform_dist(0, number_of_blocks - 1); @@ -199,30 +204,30 @@ int main(int argc, char *argv[]) TIMER_STOP(random_access); if (((off_t)-1) == ret1) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); - throw osrm::exception("seek error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + throw osrm::util::exception("seek error"); } if (-1 == ret2) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); - throw osrm::exception("read error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + throw osrm::util::exception("read error"); } timing_results_raw_random.push_back(TIMER_SEC(random_access)); } // Do statistics - SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; std::ofstream random_csv("random.csv", std::ios::trunc); for (unsigned i = 0; i < timing_results_raw_random.size(); ++i) { random_csv << i << ", " << timing_results_raw_random[i] << std::endl; } random_csv.close(); - runStatistics(timing_results_raw_random, stats); + osrm::tools::runStatistics(timing_results_raw_random, stats); - SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed + osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " << "mean: " << stats.mean << "ms, " << "med: " << stats.med << "ms, " @@ -260,15 +265,15 @@ int main(int argc, char *argv[]) TIMER_STOP(read_every_100); if (((off_t)-1) == ret1) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); - throw osrm::exception("seek error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + throw osrm::util::exception("seek error"); } if (-1 == ret2) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); - throw osrm::exception("read error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + throw osrm::util::exception("read error"); } timing_results_raw_seq.push_back(TIMER_SEC(read_every_100)); } @@ -282,7 +287,7 @@ int main(int argc, char *argv[]) close(file_desc); #endif // Do statistics - SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; // print simple statistics: min, max, median, variance std::ofstream seq_csv("sequential.csv", std::ios::trunc); for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i) @@ -290,8 +295,8 @@ int main(int argc, char *argv[]) seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl; } seq_csv.close(); - runStatistics(timing_results_raw_seq, stats); - SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed + osrm::tools::runStatistics(timing_results_raw_seq, stats); + osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " << "mean: " << stats.mean << "ms, " << "med: " << stats.med << "ms, " @@ -301,18 +306,18 @@ int main(int argc, char *argv[]) if (boost::filesystem::exists(test_path)) { boost::filesystem::remove(test_path); - SimpleLogger().Write(logDEBUG) << "removing temporary files"; + osrm::util::SimpleLogger().Write(logDEBUG) << "removing temporary files"; } } } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); - SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; if (boost::filesystem::exists(test_path)) { boost::filesystem::remove(test_path); - SimpleLogger().Write(logWARNING) << "removing temporary files"; + osrm::util::SimpleLogger().Write(logWARNING) << "removing temporary files"; } return -1; } diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index 4890fa694..ee00fa38b 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -39,25 +39,27 @@ BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) } #endif +using namespace osrm; + int main(int argc, const char *argv[]) try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); bool trial_run = false; std::string ip_address; int ip_port, requested_thread_num; LibOSRMConfig lib_config; - const unsigned init_result = GenerateServerProgramOptions( + const unsigned init_result = util::GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, lib_config.max_locations_map_matching); - if (init_result == INIT_OK_DO_NOT_START_ENGINE) + if (init_result == util::INIT_OK_DO_NOT_START_ENGINE) { return EXIT_SUCCESS; } - if (init_result == INIT_FAILED) + if (init_result == util::INIT_FAILED) { return EXIT_FAILURE; } @@ -70,7 +72,7 @@ int main(int argc, const char *argv[]) try if (should_lock && -1 == mlockall(MCL_CURRENT | MCL_FUTURE)) { could_lock = false; - SimpleLogger().Write(logWARNING) << "memory could not be locked to RAM"; + util::SimpleLogger().Write(logWARNING) << "memory could not be locked to RAM"; } } ~MemoryLocker() @@ -81,16 +83,16 @@ int main(int argc, const char *argv[]) try bool should_lock = false, could_lock = true; } memory_locker(lib_config.use_shared_memory); #endif - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; + util::SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; if (lib_config.use_shared_memory) { - SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; + util::SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; } - SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; - SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; - SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; + util::SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; + util::SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; + util::SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; #ifndef _WIN32 int sig = 0; @@ -101,13 +103,13 @@ int main(int argc, const char *argv[]) try #endif OSRM osrm_lib(lib_config); - auto routing_server = Server::CreateServer(ip_address, ip_port, requested_thread_num); + auto routing_server = server::Server::CreateServer(ip_address, ip_port, requested_thread_num); routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib); if (trial_run) { - SimpleLogger().Write() << "trial run, quitting after successful initialization"; + util::SimpleLogger().Write() << "trial run, quitting after successful initialization"; } else { @@ -127,18 +129,18 @@ int main(int argc, const char *argv[]) try sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, nullptr); - SimpleLogger().Write() << "running and waiting for requests"; + util::SimpleLogger().Write() << "running and waiting for requests"; sigwait(&wait_mask, &sig); #else // Set console control handler to allow server to be stopped. - console_ctrl_function = std::bind(&Server::Stop, routing_server); + console_ctrl_function = std::bind(&server::Server::Stop, routing_server); SetConsoleCtrlHandler(console_ctrl_handler, TRUE); - SimpleLogger().Write() << "running and waiting for requests"; + util::SimpleLogger().Write() << "running and waiting for requests"; routing_server->Run(); #endif - SimpleLogger().Write() << "initiating shutdown"; + util::SimpleLogger().Write() << "initiating shutdown"; routing_server->Stop(); - SimpleLogger().Write() << "stopping threads"; + util::SimpleLogger().Write() << "stopping threads"; auto status = future.wait_for(std::chrono::seconds(2)); @@ -148,24 +150,24 @@ int main(int argc, const char *argv[]) try } else { - SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!"; + util::SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!"; server_task.reset(); // just kill it } } - SimpleLogger().Write() << "freeing objects"; + util::SimpleLogger().Write() << "freeing objects"; routing_server.reset(); - SimpleLogger().Write() << "shutdown completed"; + util::SimpleLogger().Write() << "shutdown completed"; } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp index 0e5460a9e..65198ee05 100644 --- a/src/tools/simpleclient.cpp +++ b/src/tools/simpleclient.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/json_renderer.hpp" #include "util/routed_options.hpp" #include "util/simple_logger.hpp" @@ -12,32 +11,31 @@ int main(int argc, const char *argv[]) { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { std::string ip_address; int ip_port, requested_thread_num; bool trial_run = false; - LibOSRMConfig lib_config; - const unsigned init_result = GenerateServerProgramOptions( + osrm::LibOSRMConfig lib_config; + const unsigned init_result = osrm::util::GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, lib_config.max_locations_map_matching); - if (init_result == INIT_OK_DO_NOT_START_ENGINE) + if (init_result == osrm::util::INIT_OK_DO_NOT_START_ENGINE) { return 0; } - if (init_result == INIT_FAILED) + if (init_result == osrm::util::INIT_FAILED) { return 1; } - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - OSRM routing_machine(lib_config); + osrm::OSRM routing_machine(lib_config); - RouteParameters route_parameters; + osrm::RouteParameters route_parameters; route_parameters.zoom_level = 18; // no generalization route_parameters.print_instructions = true; // turn by turn instructions route_parameters.alternate_route = true; // get an alternate route, too @@ -51,19 +49,19 @@ int main(int argc, const char *argv[]) // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly // start_coordinate - route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION, - 13.438640 * COORDINATE_PRECISION); + route_parameters.coordinates.emplace_back(52.519930 * osrm::COORDINATE_PRECISION, + 13.438640 * osrm::COORDINATE_PRECISION); // target_coordinate - route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION, - 13.415852 * COORDINATE_PRECISION); + route_parameters.coordinates.emplace_back(52.513191 * osrm::COORDINATE_PRECISION, + 13.415852 * osrm::COORDINATE_PRECISION); osrm::json::Object json_result; const int result_code = routing_machine.RunQuery(route_parameters, json_result); - SimpleLogger().Write() << "http code: " << result_code; - osrm::json::render(SimpleLogger().Write(), json_result); + osrm::util::SimpleLogger().Write() << "http code: " << result_code; + osrm::json::render(osrm::util::SimpleLogger().Write(), json_result); } catch (std::exception ¤t_exception) { - SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); return -1; } return 0; diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 2535478a5..f242e5ed2 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -2,9 +2,17 @@ #include "datastore/shared_memory_factory.hpp" #include "engine/datafacade/shared_datatype.hpp" -#include "util/version.hpp" #include "util/simple_logger.hpp" +namespace osrm +{ +namespace tools +{ + +// FIXME remove after folding back into datastore +using namespace datastore; +using namespace engine::datafacade; + void deleteRegion(const SharedDataType region) { if (SharedMemory::RegionExists(region) && !SharedMemory::Remove(region)) @@ -30,46 +38,47 @@ void deleteRegion(const SharedDataType region) } }(); - SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; + util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } // find all existing shmem regions and remove them. void springclean() { - SimpleLogger().Write() << "spring-cleaning all shared memory regions"; + util::SimpleLogger().Write() << "spring-cleaning all shared memory regions"; deleteRegion(DATA_1); deleteRegion(LAYOUT_1); deleteRegion(DATA_2); deleteRegion(LAYOUT_2); deleteRegion(CURRENT_REGIONS); } +} +} int main() { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION << "\n\n"; - SimpleLogger().Write() << "Releasing all locks"; - SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; - SimpleLogger().Write() << "----------------------"; - SimpleLogger().Write() << "This tool may put osrm-routed into an undefined state!"; - SimpleLogger().Write() << "Type 'Y' to acknowledge that you know what your are doing."; - SimpleLogger().Write() << "\n\nDo you want to purge all shared memory allocated " + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::util::SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; + osrm::util::SimpleLogger().Write() << "----------------------"; + osrm::util::SimpleLogger().Write() << "This tool may put osrm-routed into an undefined state!"; + osrm::util::SimpleLogger().Write() << "Type 'Y' to acknowledge that you know what your are doing."; + osrm::util::SimpleLogger().Write() << "\n\nDo you want to purge all shared memory allocated " << "by osrm-datastore? [type 'Y' to confirm]"; const auto letter = getchar(); if (letter != 'Y') { - SimpleLogger().Write() << "aborted."; + osrm::util::SimpleLogger().Write() << "aborted."; return 0; } - springclean(); + osrm::tools::springclean(); } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); } return 0; } diff --git a/src/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp index f4c248c48..f59bf7721 100644 --- a/src/tools/unlock_all_mutexes.cpp +++ b/src/tools/unlock_all_mutexes.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/simple_logger.hpp" #include "engine/datafacade/shared_barriers.hpp" @@ -6,19 +5,18 @@ int main() { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - SimpleLogger().Write() << "Releasing all locks"; - SharedBarriers barrier; + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::engine::datafacade::SharedBarriers barrier; barrier.pending_update_mutex.unlock(); barrier.query_mutex.unlock(); barrier.update_mutex.unlock(); } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); } return 0; } diff --git a/src/util/compute_angle.cpp b/src/util/compute_angle.cpp index 885cb8221..ebc2f0f2e 100644 --- a/src/util/compute_angle.cpp +++ b/src/util/compute_angle.cpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace util +{ + double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &first, const FixedPointCoordinate &second, const FixedPointCoordinate &third) noexcept @@ -25,3 +30,5 @@ double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &fi } return angle; } +} +} diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 0092b01cf..4a35c7ed4 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace util +{ + FixedPointCoordinate::FixedPointCoordinate() : lat(std::numeric_limits::min()), lon(std::numeric_limits::min()) { @@ -50,3 +55,5 @@ std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordina out << "(" << static_cast(coordinate.lat / COORDINATE_PRECISION) << "," << static_cast(coordinate.lon / COORDINATE_PRECISION) << ")"; return out; } +} +} diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 2e6a3137e..05190123f 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -11,6 +11,11 @@ #include +namespace osrm +{ +namespace util +{ + namespace { constexpr static const double RAD = 0.017453292519943295769236907684886; @@ -223,3 +228,5 @@ double bearing(const FixedPointCoordinate &first_coordinate, return result; } } +} +} diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index 96e39773b..5ddfce0b4 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -2,6 +2,11 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace util +{ + uint64_t HilbertCode::operator()(const FixedPointCoordinate ¤t_coordinate) const { unsigned location[2]; @@ -71,3 +76,5 @@ void HilbertCode::TransposeCoordinate(uint32_t *X) const X[i] ^= t; } } +} +} diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp index 36c1a9b84..ab9637172 100644 --- a/src/util/mercator.cpp +++ b/src/util/mercator.cpp @@ -2,6 +2,11 @@ #include +namespace osrm +{ +namespace util +{ + double mercator::y2lat(const double value) noexcept { return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); @@ -11,3 +16,5 @@ double mercator::lat2y(const double latitude) noexcept { return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); } +} +} diff --git a/src/util/osrm_exception.cpp b/src/util/osrm_exception.cpp index 475e75194..a987bc75d 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/osrm_exception.cpp @@ -1,7 +1,5 @@ #include "util/osrm_exception.hpp" -namespace osrm -{ // This function exists to 'anchor' the class, and stop the compiler from // copying vtable and RTTI info into every object file that includes // this header. (Caught by -Wweak-vtables under Clang.) @@ -12,5 +10,13 @@ namespace osrm // always have at least one out-of-line virtual method in the class. Without // this, the compiler will copy the vtable and RTTI into every .o file that // #includes the header, bloating .o file sizes and increasing link times. + +namespace osrm +{ +namespace util +{ + void exception::anchor() const {} + +} } diff --git a/src/util/simple_logger.cpp b/src/util/simple_logger.cpp index de3d68190..13ee10391 100644 --- a/src/util/simple_logger.cpp +++ b/src/util/simple_logger.cpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace { static const char COL_RESET[]{"\x1b[0m"}; @@ -92,3 +97,5 @@ SimpleLogger::~SimpleLogger() } } } +} +} diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 827ce5016..0a5bc0a87 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -10,9 +10,12 @@ BOOST_AUTO_TEST_SUITE(douglas_peucker) +using namespace osrm; +using namespace osrm::engine; + SegmentInformation getTestInfo(int lat, int lon, bool necessary) { - return SegmentInformation(FixedPointCoordinate(lat, lon), 0, 0, 0, TurnInstruction::HeadOn, + return SegmentInformation(util::FixedPointCoordinate(lat, lon), 0, 0, 0, extractor::TurnInstruction::HeadOn, necessary, false, 0); } diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index 7e5e07c2c..182cabda8 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -9,23 +9,28 @@ #include #include -BOOST_AUTO_TEST_CASE(geometry_string) +BOOST_AUTO_TEST_SUITE(polyline) + +using namespace osrm; +using namespace osrm::engine; + +BOOST_AUTO_TEST_CASE(decode) { // Polyline string for the 5 coordinates const std::string polyline = "_gjaR_gjaR_pR_ibE_pR_ibE_pR_ibE_pR_ibE"; PolylineCompressor pc; - std::vector coords = pc.decode_string(polyline); + std::vector coords = pc.decode_string(polyline); // Test coordinates; these would be the coordinates we give the loc parameter, // e.g. loc=10.00,10.0&loc=10.01,10.1... - FixedPointCoordinate coord1(10.00 * COORDINATE_PRECISION, 10.0 * COORDINATE_PRECISION); - FixedPointCoordinate coord2(10.01 * COORDINATE_PRECISION, 10.1 * COORDINATE_PRECISION); - FixedPointCoordinate coord3(10.02 * COORDINATE_PRECISION, 10.2 * COORDINATE_PRECISION); - FixedPointCoordinate coord4(10.03 * COORDINATE_PRECISION, 10.3 * COORDINATE_PRECISION); - FixedPointCoordinate coord5(10.04 * COORDINATE_PRECISION, 10.4 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord1(10.00 * COORDINATE_PRECISION, 10.0 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord2(10.01 * COORDINATE_PRECISION, 10.1 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord3(10.02 * COORDINATE_PRECISION, 10.2 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord4(10.03 * COORDINATE_PRECISION, 10.3 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord5(10.04 * COORDINATE_PRECISION, 10.4 * COORDINATE_PRECISION); // Put the test coordinates into the vector for comparison - std::vector cmp_coords; + std::vector cmp_coords; cmp_coords.emplace_back(coord1); cmp_coords.emplace_back(coord2); cmp_coords.emplace_back(coord3); @@ -45,3 +50,5 @@ BOOST_AUTO_TEST_CASE(geometry_string) BOOST_CHECK_CLOSE(cmp1_lon, cmp2_lon, 0.0001); } } + +BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/extractor/compressed_edge_container.cpp b/unit_tests/extractor/compressed_edge_container.cpp index 4a83f0402..593ec597c 100644 --- a/unit_tests/extractor/compressed_edge_container.cpp +++ b/unit_tests/extractor/compressed_edge_container.cpp @@ -6,6 +6,9 @@ BOOST_AUTO_TEST_SUITE(compressed_edge_container) +using namespace osrm; +using namespace osrm::extractor; + BOOST_AUTO_TEST_CASE(long_road_test) { // 0 1 2 3 diff --git a/unit_tests/extractor/graph_compressor.cpp b/unit_tests/extractor/graph_compressor.cpp index e4cd1ddbb..83751bf6a 100644 --- a/unit_tests/extractor/graph_compressor.cpp +++ b/unit_tests/extractor/graph_compressor.cpp @@ -12,6 +12,11 @@ BOOST_AUTO_TEST_SUITE(graph_compressor) +using namespace osrm; +using namespace osrm::extractor; +using InputEdge = util::NodeBasedDynamicGraph::InputEdge; +using Graph = util::NodeBasedDynamicGraph; + BOOST_AUTO_TEST_CASE(long_road_test) { // @@ -25,7 +30,6 @@ BOOST_AUTO_TEST_CASE(long_road_test) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, // travel_mode @@ -42,7 +46,7 @@ BOOST_AUTO_TEST_CASE(long_road_test) BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[4].data)); BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[6].data)); - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK_EQUAL(graph.FindEdge(0, 1), SPECIAL_EDGEID); @@ -67,7 +71,6 @@ BOOST_AUTO_TEST_CASE(loop_test) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, forward, backward, // roundabout, travel_mode @@ -98,7 +101,7 @@ BOOST_AUTO_TEST_CASE(loop_test) BOOST_ASSERT(edges[9].data.IsCompatibleTo(edges[10].data)); BOOST_ASSERT(edges[10].data.IsCompatibleTo(edges[11].data)); - NodeBasedDynamicGraph graph(6, edges); + Graph graph(6, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK_EQUAL(graph.FindEdge(5, 0), SPECIAL_EDGEID); @@ -125,7 +128,6 @@ BOOST_AUTO_TEST_CASE(t_intersection) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, // travel_mode @@ -143,7 +145,7 @@ BOOST_AUTO_TEST_CASE(t_intersection) BOOST_ASSERT(edges[3].data.IsCompatibleTo(edges[4].data)); BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[5].data)); - NodeBasedDynamicGraph graph(4, edges); + Graph graph(4, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); @@ -164,7 +166,6 @@ BOOST_AUTO_TEST_CASE(street_name_changes) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, forward, backward, // roundabout, travel_mode @@ -177,7 +178,7 @@ BOOST_AUTO_TEST_CASE(street_name_changes) BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[1].data)); BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[3].data)); - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); @@ -197,7 +198,6 @@ BOOST_AUTO_TEST_CASE(direction_changes) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reverse, roundabout, // travel_mode @@ -207,7 +207,7 @@ BOOST_AUTO_TEST_CASE(direction_changes) {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, }; - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); diff --git a/unit_tests/extractor/raster_source.cpp b/unit_tests/extractor/raster_source.cpp index 3f43d2f40..2160372f1 100644 --- a/unit_tests/extractor/raster_source.cpp +++ b/unit_tests/extractor/raster_source.cpp @@ -9,6 +9,9 @@ BOOST_AUTO_TEST_SUITE(raster_source) +using namespace osrm; +using namespace osrm::extractor; + int normalize(double coord) { return static_cast(coord * COORDINATE_PRECISION); } #define CHECK_QUERY(source_id, lon, lat, expected) \ @@ -73,11 +76,11 @@ BOOST_AUTO_TEST_CASE(raster_test) BOOST_CHECK_EQUAL(source_already_loaded_id, 0); BOOST_CHECK_THROW(sources.getRasterDataFromSource(1, normalize(0.02), normalize(0.02)), - osrm::exception); + util::exception); BOOST_CHECK_THROW( sources.loadRasterSource("../unit_tests/fixtures/nonexistent.asc", 0, 0.1, 0, 0.1, 7, 7), - osrm::exception); + util::exception); } BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/util/bearing.cpp b/unit_tests/util/bearing.cpp index 90664b27d..77e2ede66 100644 --- a/unit_tests/util/bearing.cpp +++ b/unit_tests/util/bearing.cpp @@ -5,7 +5,10 @@ #include #include -BOOST_AUTO_TEST_SUITE(bearing) +BOOST_AUTO_TEST_SUITE(bearing_test) + +using namespace osrm; +using namespace osrm::util; // Verify that the bearing-bounds checking function behaves as expected BOOST_AUTO_TEST_CASE(bearing_range_test) diff --git a/unit_tests/util/binary_heap.cpp b/unit_tests/util/binary_heap.cpp index 4f270f168..44aef1342 100644 --- a/unit_tests/util/binary_heap.cpp +++ b/unit_tests/util/binary_heap.cpp @@ -12,6 +12,9 @@ BOOST_AUTO_TEST_SUITE(binary_heap) +using namespace osrm; +using namespace osrm::util; + struct TestData { unsigned value; diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index e636d2f8f..8c32f080c 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -6,6 +6,9 @@ #include +using namespace osrm; +using namespace osrm::util; + // Regression test for bug captured in #1347 BOOST_AUTO_TEST_CASE(regression_test_1347) { diff --git a/unit_tests/util/duration_parsing.cpp b/unit_tests/util/duration_parsing.cpp index b92916ad7..72a5b6306 100644 --- a/unit_tests/util/duration_parsing.cpp +++ b/unit_tests/util/duration_parsing.cpp @@ -5,33 +5,36 @@ BOOST_AUTO_TEST_SUITE(durations_are_valid) +using namespace osrm; +using namespace osrm::util; + BOOST_AUTO_TEST_CASE(all_necessary_test) { - BOOST_CHECK_EQUAL(durationIsValid("00:01"), true); - BOOST_CHECK_EQUAL(durationIsValid("00:01:01"), true); - BOOST_CHECK_EQUAL(durationIsValid("PT15M"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("00:01"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("00:01:01"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("PT15M"), true); } BOOST_AUTO_TEST_CASE(common_durations_get_translated) { - BOOST_CHECK_EQUAL(parseDuration("00:01"), 60); - BOOST_CHECK_EQUAL(parseDuration("00:01:01"), 61); - BOOST_CHECK_EQUAL(parseDuration("01:01"), 3660); + BOOST_CHECK_EQUAL(extractor::parseDuration("00:01"), 60); + BOOST_CHECK_EQUAL(extractor::parseDuration("00:01:01"), 61); + BOOST_CHECK_EQUAL(extractor::parseDuration("01:01"), 3660); // check all combinations of iso duration tokens - BOOST_CHECK_EQUAL(parseDuration("PT1M1S"), 61); - BOOST_CHECK_EQUAL(parseDuration("PT1H1S"), 3601); - BOOST_CHECK_EQUAL(parseDuration("PT15M"), 900); - BOOST_CHECK_EQUAL(parseDuration("PT15S"), 15); - BOOST_CHECK_EQUAL(parseDuration("PT15H"), 54000); - BOOST_CHECK_EQUAL(parseDuration("PT1H15M"), 4500); - BOOST_CHECK_EQUAL(parseDuration("PT1H15M1S"), 4501); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1M1S"), 61); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H1S"), 3601); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15M"), 900); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15S"), 15); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15H"), 54000); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H15M"), 4500); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H15M1S"), 4501); } BOOST_AUTO_TEST_CASE(iso_8601_durations_case_insensitive) { - BOOST_CHECK_EQUAL(parseDuration("PT15m"), 900); - BOOST_CHECK_EQUAL(parseDuration("PT1h15m"), 4500); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15m"), 900); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1h15m"), 4500); } BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/util/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp index 44f69eb76..263b60c7a 100644 --- a/unit_tests/util/dynamic_graph.cpp +++ b/unit_tests/util/dynamic_graph.cpp @@ -8,6 +8,9 @@ BOOST_AUTO_TEST_SUITE(dynamic_graph) +using namespace osrm; +using namespace osrm::util; + struct TestData { EdgeID id; diff --git a/unit_tests/util/range_table.cpp b/unit_tests/util/range_table.cpp index 01fe9448f..a5db4c597 100644 --- a/unit_tests/util/range_table.cpp +++ b/unit_tests/util/range_table.cpp @@ -7,11 +7,14 @@ #include #include +BOOST_AUTO_TEST_SUITE(range_table) + +using namespace osrm; +using namespace osrm::util; + constexpr unsigned BLOCK_SIZE = 16; typedef RangeTable TestRangeTable; -BOOST_AUTO_TEST_SUITE(range_table) - void ConstructionTest(stxxl::vector lengths, std::vector offsets) { BOOST_ASSERT(lengths.size() == offsets.size() - 1); diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index f9b69f629..7f6c6ab4c 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -10,6 +10,9 @@ BOOST_AUTO_TEST_SUITE(static_graph) +using namespace osrm; +using namespace osrm::util; + struct TestData { EdgeID id; diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 9e0cc9520..fd3a19b69 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -25,10 +25,13 @@ BOOST_AUTO_TEST_SUITE(static_rtree) +using namespace osrm; +using namespace osrm::util; + constexpr uint32_t TEST_BRANCHING_FACTOR = 8; constexpr uint32_t TEST_LEAF_NODE_SIZE = 64; -typedef EdgeBasedNode TestData; +using TestData = extractor::EdgeBasedNode; using TestStaticRTree = StaticRTree, false, @@ -108,7 +111,7 @@ template struct RandomGraphFixture { int lat = lat_udist(g); int lon = lon_udist(g); - nodes.emplace_back(QueryNode(lat, lon, OSMNodeID(i))); + nodes.emplace_back(extractor::QueryNode(lat, lon, OSMNodeID(i))); coords->emplace_back(FixedPointCoordinate(lat, lon)); } @@ -131,7 +134,7 @@ template struct RandomGraphFixture } } - std::vector nodes; + std::vector nodes; std::shared_ptr> coords; std::vector edges; }; @@ -148,7 +151,7 @@ struct GraphFixture FixedPointCoordinate c(input_coords[i].first * COORDINATE_PRECISION, input_coords[i].second * COORDINATE_PRECISION); coords->emplace_back(c); - nodes.emplace_back(QueryNode(c.lat, c.lon, OSMNodeID(i))); + nodes.emplace_back(extractor::QueryNode(c.lat, c.lon, OSMNodeID(i))); } for (const auto &pair : input_edges) @@ -166,7 +169,7 @@ struct GraphFixture } } - std::vector nodes; + std::vector nodes; std::shared_ptr> coords; std::vector edges; }; @@ -252,7 +255,7 @@ void build_rtree(const std::string &prefix, boost::filesystem::ofstream node_stream(coords_path, std::ios::binary); const auto num_nodes = static_cast(fixture->nodes.size()); node_stream.write((char *)&num_nodes, sizeof(unsigned)); - node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(QueryNode)); + node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(extractor::QueryNode)); node_stream.close(); RTreeT r(fixture->edges, nodes_path, leaves_path, fixture->nodes); @@ -408,7 +411,7 @@ BOOST_AUTO_TEST_CASE(bearing_tests) std::string nodes_path; build_rtree("test_bearing", &fixture, leaves_path, nodes_path); MiniStaticRTree rtree(nodes_path, leaves_path, fixture.coords); - GeospatialQuery query(rtree, fixture.coords); + engine::GeospatialQuery query(rtree, fixture.coords); FixedPointCoordinate input(5.0 * COORDINATE_PRECISION, 5.1 * COORDINATE_PRECISION); diff --git a/unit_tests/util/string_util.cpp b/unit_tests/util/string_util.cpp index 1cee413b6..e3a7204cf 100644 --- a/unit_tests/util/string_util.cpp +++ b/unit_tests/util/string_util.cpp @@ -7,6 +7,9 @@ BOOST_AUTO_TEST_SUITE(string_util) +using namespace osrm; +using namespace osrm::util; + BOOST_AUTO_TEST_CASE(json_escaping) { std::string input{"\b\\"};