From 84db1d1338a6d589f33f62c844b88cdbb356d374 Mon Sep 17 00:00:00 2001 From: Lev Dragunov Date: Wed, 17 Dec 2014 14:43:09 +0300 Subject: [PATCH] OSRM update to commit 75f9c0844550261d5e9c842d0a10b8f82eac2965. CHECK MAPS.ME OSRM DIFFS FROM HERE --- 3party/osrm/osrm-backend/.clang-format | 53 -- 3party/osrm/osrm-backend/.gitignore | 93 --- 3party/osrm/osrm-backend/.gitmodules | 0 3party/osrm/osrm-backend/.travis.yml | 54 -- .../Algorithms/BFSComponentExplorer.h | 17 +- .../Algorithms/DouglasPeucker.cpp | 16 +- .../osrm-backend/Algorithms/DouglasPeucker.h | 2 +- .../Algorithms/IteratorBasedCRC32.h | 124 +-- .../osrm-backend/Algorithms/ObjectToBase64.h | 101 ++- .../Algorithms/PolylineCompressor.cpp | 18 +- .../Algorithms/StronglyConnectedComponents.h | 14 +- .../Benchmarks/StaticRTreeBench.cpp | 76 +- 3party/osrm/osrm-backend/CMakeLists.txt | 145 ++-- .../osrm/osrm-backend/Contractor/Contractor.h | 19 +- .../Contractor/EdgeBasedGraphFactory.cpp | 333 +++----- .../Contractor/EdgeBasedGraphFactory.h | 20 +- .../Contractor/GeometryCompressor.cpp | 15 +- .../Contractor/GeometryCompressor.h | 10 +- .../osrm/osrm-backend/Contractor/Prepare.cpp | 124 +-- 3party/osrm/osrm-backend/Contractor/Prepare.h | 18 +- .../osrm-backend/DataStructures/BinaryHeap.h | 4 +- .../DataStructures/ConcurrentQueue.h | 2 - .../DataStructures/Coordinate.cpp | 58 +- .../DataStructures/DeallocatingVector.h | 6 +- .../DataStructures/DynamicGraph.h | 12 +- .../DataStructures/EdgeBasedNode.h | 26 +- .../DataStructures/EdgeBasedNodeData.h | 123 --- .../DataStructures/FixedPointNumber.h | 216 +++++ .../osrm-backend/DataStructures/HashTable.h | 2 +- .../DataStructures/ImportEdge.cpp | 11 +- .../osrm-backend/DataStructures/ImportEdge.h | 13 +- .../DataStructures/JSONContainer.h | 83 +- .../DataStructures/NodeBasedGraph.h | 36 +- .../DataStructures/OriginalEdgeData.h | 10 +- .../DataStructures/PhantomNodes.h | 20 +- .../osrm-backend/DataStructures/QueryNode.h | 6 +- .../osrm/osrm-backend/DataStructures/Range.h | 5 +- .../osrm-backend/DataStructures/RangeTable.h | 14 +- .../DataStructures/RawRouteData.h | 19 +- .../osrm-backend/DataStructures/Restriction.h | 4 +- .../DataStructures/RestrictionMap.cpp | 13 +- .../DataStructures/RestrictionMap.h | 10 +- .../DataStructures/RouteParameters.cpp | 10 +- .../DataStructures/SearchEngineData.h | 6 +- .../DataStructures/SegmentInformation.h | 18 +- .../DataStructures/SharedMemoryFactory.h | 23 +- .../SharedMemoryVectorWrapper.h | 10 +- .../osrm-backend/DataStructures/StaticGraph.h | 17 +- .../DataStructures/StaticKDTree.h | 2 +- .../osrm-backend/DataStructures/StaticRTree.h | 121 +-- .../TravelMode.h} | 18 +- .../DataStructures/TurnInstructions.h | 2 +- .../DataStructures/XORFastHashStorage.h | 8 +- .../Descriptors/DescriptionFactory.cpp | 51 +- .../Descriptors/DescriptionFactory.h | 15 +- .../osrm-backend/Descriptors/GPXDescriptor.h | 19 +- .../osrm-backend/Descriptors/JSONDescriptor.h | 54 +- .../osrm-backend/Extractor/BaseParser.cpp | 2 +- .../Extractor/ExtractionContainers.cpp | 12 +- .../Extractor/ExtractionContainers.h | 14 +- .../Extractor/ExtractionHelperFunctions.h | 15 +- .../osrm-backend/Extractor/ExtractionWay.h | 63 +- .../osrm/osrm-backend/Extractor/Extractor.cpp | 4 +- .../Extractor/ExtractorCallbacks.cpp | 41 +- .../osrm-backend/Extractor/ExtractorStructs.h | 6 +- .../Extractor/InternalExtractorEdge.h | 28 +- .../osrm/osrm-backend/Extractor/PBFParser.cpp | 3 +- .../Extractor/ScriptingEnvironment.cpp | 9 +- .../osrm/osrm-backend/Extractor/XMLParser.cpp | 19 +- .../osrm-backend/Include/osrm/Coordinate.h | 11 +- .../osrm/osrm-backend/Include/osrm/Header.h | 2 +- .../Include/osrm/RouteParameters.h | 3 + 3party/osrm/osrm-backend/Library/OSRM.h | 6 +- .../osrm/osrm-backend/Library/OSRM_impl.cpp | 25 +- 3party/osrm/osrm-backend/Library/OSRM_impl.h | 9 +- .../Plugins/DistanceTablePlugin.h | 18 +- .../osrm-backend/Plugins/HelloWorldPlugin.h | 22 +- .../osrm/osrm-backend/Plugins/LocatePlugin.h | 13 +- .../osrm/osrm-backend/Plugins/NearestPlugin.h | 55 +- .../osrm-backend/Plugins/TimestampPlugin.h | 6 +- .../osrm-backend/Plugins/ViaRoutePlugin.h | 23 +- 3party/osrm/osrm-backend/README.md | 2 +- 3party/osrm/osrm-backend/Rakefile | 8 +- .../AlternativePathRouting.h | 13 +- .../RoutingAlgorithms/BasicRoutingInterface.h | 190 +++-- .../RoutingAlgorithms/ManyToManyRouting.h | 8 +- .../RoutingAlgorithms/ShortestPathRouting.h | 6 +- 3party/osrm/osrm-backend/Server/APIGrammar.h | 5 +- .../Server/DataStructures/BaseDataFacade.h | 17 +- .../DataStructures/InternalDataFacade.h | 77 +- .../Server/DataStructures/SharedDataFacade.h | 121 +-- .../Server/DataStructures/SharedDataType.h | 7 +- .../osrm/osrm-backend/Server/Http/Reply.cpp | 7 +- .../osrm-backend/Server/RequestHandler.cpp | 26 +- .../osrm/osrm-backend/Server/RequestHandler.h | 2 +- .../osrm-backend/Server/RequestParser.cpp | 22 +- 3party/osrm/osrm-backend/Server/Server.h | 31 +- .../ThirdParty/variant/recursive_wrapper.hpp | 127 +++ .../ThirdParty/variant/variant.hpp | 740 ++++++++++++++++++ 3party/osrm/osrm-backend/Tools/check-hsgr.cpp | 63 +- 3party/osrm/osrm-backend/Tools/components.cpp | 42 +- .../osrm/osrm-backend/Tools/io-benchmark.cpp | 90 +-- .../osrm/osrm-backend/Tools/simpleclient.cpp | 5 +- .../osrm/osrm-backend/Tools/springclean.cpp | 102 +++ .../osrm-backend/Tools/unlock_all_mutexes.cpp | 5 +- .../DataStructures/StaticRTreeTest.cpp | 8 +- .../osrm-backend/Util/BoostFileSystemFix.h | 19 +- .../osrm/osrm-backend/Util/DataStoreOptions.h | 9 +- .../osrm/osrm-backend/Util/FingerPrint.cpp.in | 3 +- 3party/osrm/osrm-backend/Util/GraphLoader.h | 37 +- 3party/osrm/osrm-backend/Util/MachineInfo.h | 4 +- 3party/osrm/osrm-backend/Util/MercatorUtil.h | 8 +- .../osrm/osrm-backend/Util/ProgramOptions.h | 189 ++--- 3party/osrm/osrm-backend/Util/SimpleLogger.h | 159 ---- .../osrm-backend/Util/StdHashExtensions.h | 12 +- 3party/osrm/osrm-backend/Util/StringUtil.h | 153 +--- .../osrm-backend/Util/TrigonometryTables.h | 2 +- 3party/osrm/osrm-backend/Util/cast.hpp | 188 +++++ .../{ComputeAngle.h => compute_angle.cpp} | 20 +- .../osrm/osrm-backend/Util/compute_angle.hpp | 41 + .../Util/{ContainerUtils.h => container.hpp} | 23 +- .../osrm/osrm-backend/Util/floating_point.hpp | 44 ++ 3party/osrm/osrm-backend/Util/make_unique.hpp | 57 ++ .../osrm/osrm-backend/Util/simple_logger.cpp | 135 ++++ .../simple_logger.hpp} | 59 +- 3party/osrm/osrm-backend/appveyor.yml | 11 +- .../cmake/CPackDebianConfig.cmake | 44 ++ .../osrm/osrm-backend/cmake/FindDebArch.cmake | 19 + .../osrm-backend/cmake/check_luabind.cmake | 40 + 3party/osrm/osrm-backend/cmake/postinst.in | 2 + 3party/osrm/osrm-backend/datastore.cpp | 54 +- 3party/osrm/osrm-backend/extractor.cpp | 11 +- .../features/bicycle/mode.feature | 234 ++++-- .../features/bicycle/pushing.feature | 26 +- .../osrm-backend/features/car/ferry.feature | 37 +- .../osrm-backend/features/car/link.feature | 111 +++ .../features/car/maxspeed.feature | 30 +- .../osrm-backend/features/car/speed.feature | 10 +- .../osrm-backend/features/car/surface.feature | 140 ++++ .../osrm-backend/features/foot/ferry.feature | 18 +- .../features/options/extract/files.feature | 6 +- .../features/options/prepare/files.feature | 6 +- .../features/options/routed/files.feature | 13 +- .../features/step_definitions/data.rb | 16 + .../features/step_definitions/locate.rb | 2 +- .../features/step_definitions/nearest.rb | 2 +- .../features/step_definitions/options.rb | 6 +- .../features/step_definitions/requests.rb | 4 +- .../features/step_definitions/routability.rb | 8 +- .../features/step_definitions/routing.rb | 14 +- .../osrm-backend/features/support/data.rb | 78 +- .../osrm/osrm-backend/features/support/env.rb | 30 +- .../features/support/exceptions.rb | 6 + .../osrm-backend/features/support/hash.rb | 26 +- .../osrm-backend/features/support/hooks.rb | 4 + .../osrm-backend/features/support/launch.rb | 181 +++-- .../osrm/osrm-backend/features/support/log.rb | 6 +- .../osrm/osrm-backend/features/support/run.rb | 18 +- .../osrm-backend/features/testbot/bad.feature | 2 +- .../features/testbot/basic.feature | 2 +- .../features/testbot/bearing.feature | 2 +- .../features/testbot/bearing_param.feature | 2 +- .../features/testbot/compression.feature | 22 + .../features/testbot/datastore.feature | 31 + .../features/testbot/distance.feature | 2 +- .../features/testbot/fastest.feature | 2 +- .../features/testbot/geometry.feature | 2 +- .../features/testbot/graph.feature | 21 +- .../features/testbot/load.feature | 63 ++ .../features/testbot/loop.feature | 8 +- .../features/testbot/mode.feature | 227 +++++- .../features/testbot/oneway.feature | 64 +- .../features/testbot/origin.feature | 2 +- .../features/testbot/penalty.feature | 2 +- .../features/testbot/planetary.feature | 2 +- .../features/testbot/projection.feature | 2 +- .../features/testbot/protobuffer.feature | 2 +- .../features/testbot/snap.feature | 2 +- .../features/testbot/status.feature | 2 +- .../features/testbot/time.feature | 2 +- .../features/testbot/turns.feature | 2 +- .../osrm-backend/features/testbot/utf.feature | 2 +- .../features/testbot/uturn.feature | 8 +- .../osrm-backend/features/testbot/via.feature | 24 +- .../osrm/osrm-backend/mapsme/CMakeLists.txt | 12 - 3party/osrm/osrm-backend/mapsme/converter.cpp | 389 --------- 3party/osrm/osrm-backend/mapsme/converter.hpp | 13 - 3party/osrm/osrm-backend/mapsme/main.cpp | 29 - 3party/osrm/osrm-backend/profile.lua | 413 +++++++++- 3party/osrm/osrm-backend/profiles/bicycle.lua | 163 ++-- 3party/osrm/osrm-backend/profiles/car.lua | 186 ++++- .../profiles/examples/postgis.lua | 4 +- 3party/osrm/osrm-backend/profiles/foot.lua | 50 +- .../osrm-backend/profiles/lib/maxspeed.lua | 17 + 3party/osrm/osrm-backend/profiles/testbot.lua | 33 +- 3party/osrm/osrm-backend/routed.cpp | 41 +- 3party/osrm/osrm-backend/taginfo.json | 84 ++ 3party/osrm/osrm-backend/test/.stxxl | 1 + 3party/osrm/osrm-backend/typedefs.h | 15 +- 199 files changed, 5584 insertions(+), 3195 deletions(-) delete mode 100644 3party/osrm/osrm-backend/.clang-format delete mode 100644 3party/osrm/osrm-backend/.gitignore delete mode 100644 3party/osrm/osrm-backend/.gitmodules delete mode 100644 3party/osrm/osrm-backend/.travis.yml delete mode 100644 3party/osrm/osrm-backend/DataStructures/EdgeBasedNodeData.h create mode 100644 3party/osrm/osrm-backend/DataStructures/FixedPointNumber.h rename 3party/osrm/osrm-backend/{Util/NumericUtil.h => DataStructures/TravelMode.h} (83%) create mode 100644 3party/osrm/osrm-backend/ThirdParty/variant/recursive_wrapper.hpp create mode 100644 3party/osrm/osrm-backend/ThirdParty/variant/variant.hpp create mode 100644 3party/osrm/osrm-backend/Tools/springclean.cpp delete mode 100644 3party/osrm/osrm-backend/Util/SimpleLogger.h create mode 100644 3party/osrm/osrm-backend/Util/cast.hpp rename 3party/osrm/osrm-backend/Util/{ComputeAngle.h => compute_angle.cpp} (77%) create mode 100644 3party/osrm/osrm-backend/Util/compute_angle.hpp rename 3party/osrm/osrm-backend/Util/{ContainerUtils.h => container.hpp} (81%) create mode 100644 3party/osrm/osrm-backend/Util/floating_point.hpp create mode 100644 3party/osrm/osrm-backend/Util/make_unique.hpp create mode 100644 3party/osrm/osrm-backend/Util/simple_logger.cpp rename 3party/osrm/osrm-backend/{Server/ServerFactory.h => Util/simple_logger.hpp} (64%) create mode 100644 3party/osrm/osrm-backend/cmake/CPackDebianConfig.cmake create mode 100644 3party/osrm/osrm-backend/cmake/FindDebArch.cmake create mode 100644 3party/osrm/osrm-backend/cmake/check_luabind.cmake create mode 100644 3party/osrm/osrm-backend/cmake/postinst.in create mode 100644 3party/osrm/osrm-backend/features/car/link.feature create mode 100644 3party/osrm/osrm-backend/features/car/surface.feature create mode 100644 3party/osrm/osrm-backend/features/testbot/compression.feature create mode 100644 3party/osrm/osrm-backend/features/testbot/datastore.feature create mode 100644 3party/osrm/osrm-backend/features/testbot/load.feature delete mode 100644 3party/osrm/osrm-backend/mapsme/CMakeLists.txt delete mode 100644 3party/osrm/osrm-backend/mapsme/converter.cpp delete mode 100644 3party/osrm/osrm-backend/mapsme/converter.hpp delete mode 100644 3party/osrm/osrm-backend/mapsme/main.cpp mode change 120000 => 100644 3party/osrm/osrm-backend/profile.lua create mode 100644 3party/osrm/osrm-backend/profiles/lib/maxspeed.lua create mode 100644 3party/osrm/osrm-backend/taginfo.json create mode 100644 3party/osrm/osrm-backend/test/.stxxl diff --git a/3party/osrm/osrm-backend/.clang-format b/3party/osrm/osrm-backend/.clang-format deleted file mode 100644 index 47429976bc..0000000000 --- a/3party/osrm/osrm-backend/.clang-format +++ /dev/null @@ -1,53 +0,0 @@ ---- -Language: Cpp -# BasedOnStyle: LLVM -AccessModifierOffset: -2 -ConstructorInitializerIndentWidth: 4 -AlignEscapedNewlinesLeft: false -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AllowShortFunctionsOnASingleLine: true -AlwaysBreakTemplateDeclarations: false -AlwaysBreakBeforeMultilineStrings: false -BreakBeforeBinaryOperators: false -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BinPackParameters: false -ColumnLimit: 100 -ConstructorInitializerAllOnOneLineOrOnePerLine: false -DerivePointerBinding: false -ExperimentalAutoDetectBinPacking: false -IndentCaseLabels: false -MaxEmptyLinesToKeep: 1 -KeepEmptyLinesAtTheStartOfBlocks: true -NamespaceIndentation: None -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true -PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 -PenaltyBreakString: 1000 -PenaltyBreakFirstLessLess: 120 -PenaltyExcessCharacter: 1000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerBindsToType: false -SpacesBeforeTrailingComments: 1 -Cpp11BracedListStyle: true -Standard: Cpp11 -IndentWidth: 4 -TabWidth: 8 -UseTab: Never -BreakBeforeBraces: Allman -IndentFunctionDeclarationAfterType: false -SpacesInParentheses: false -SpacesInAngles: false -SpaceInEmptyParentheses: false -SpacesInCStyleCastParentheses: false -SpacesInContainerLiterals: true -SpaceBeforeAssignmentOperators: true -ContinuationIndentWidth: 4 -CommentPragmas: '^ IWYU pragma:' -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] -SpaceBeforeParens: ControlStatements -... diff --git a/3party/osrm/osrm-backend/.gitignore b/3party/osrm/osrm-backend/.gitignore deleted file mode 100644 index 5e8c12d8bc..0000000000 --- a/3party/osrm/osrm-backend/.gitignore +++ /dev/null @@ -1,93 +0,0 @@ -# Compiled source # -################### -*.com -*.class -*.dll -*.exe -*.o -*.so - -# Packages # -############ -# it's better to unpack these files and commit the raw source -# git has its own built in compression methods -*.7z -*.dmg -*.gz -*.iso -*.jar -*.rar -*.tar -*.zip - -# Logs and databases # -###################### -*.log -*.sql -*.sqlite - -# OS generated files # -###################### -.DS_Store -ehthumbs.db -Icon? -Thumbs.db - -# build related files # -####################### -/build/ -/Util/FingerPrint.cpp -/Util/GitDescription.cpp - -# Eclipse related files # -######################### -.setting* -.scb -.cproject -.project - -# stxxl related files # -####################### -.stxxl -stxxl.log -stxxl.errlog - -# compiled protobuffers # -######################### -/DataStructures/pbf-proto/*.pb.h -/DataStructures/pbf-proto/*.pb.cc - -# External Libs # -################# -/lib/ -/win/lib - -# Visual Studio Temp + build Files # -#################################### -/win/*.user -/win/*.ncb -/win/*.suo -/win/Debug/ -/win/Release/ -/win/bin/ -/win/bin-debug/ -/osrm-extract -/osrm-io-benchmark -/osrm-components -/osrm-routed -/osrm-datastore -/osrm-prepare -/osrm-unlock-all -/osrm-cli -/osrm-check-hsgr -/nohup.out - -# Sandbox folder # -################### -/sandbox/ - -/test/profile.lua - -# Deprecated config file # -########################## -/server.ini diff --git a/3party/osrm/osrm-backend/.gitmodules b/3party/osrm/osrm-backend/.gitmodules deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/3party/osrm/osrm-backend/.travis.yml b/3party/osrm/osrm-backend/.travis.yml deleted file mode 100644 index 8817e38747..0000000000 --- a/3party/osrm/osrm-backend/.travis.yml +++ /dev/null @@ -1,54 +0,0 @@ -language: cpp -compiler: - - gcc -# - clang -# Make sure CMake is installed -install: - - sudo apt-add-repository -y ppa:ubuntu-toolchain-r/test - - sudo add-apt-repository -y ppa:boost-latest/ppa - - sudo apt-get update >/dev/null - - sudo apt-get -q install libprotoc-dev libprotobuf7 libprotobuf-dev libosmpbf-dev libbz2-dev libstxxl-dev libstxxl1 libxml2-dev libzip-dev lua5.1 liblua5.1-0-dev rubygems libtbb-dev - - sudo apt-get -q install g++-4.7 - - sudo apt-get install libboost1.54-all-dev - #luabind - - curl https://gist.githubusercontent.com/DennisOSRM/f2eb7b948e6fe1ae319e/raw/install-luabind.sh | sudo bash - #osmosis - - curl -s https://gist.githubusercontent.com/DennisOSRM/803a64a9178ec375069f/raw/ | sudo bash -before_script: - - rvm use 1.9.3 - - gem install bundler - - bundle install - - mkdir build - - cd build - - cmake .. $CMAKEOPTIONS -script: - - make -j 2 - - cd .. - - cucumber -p verify -after_script: -# - cd .. -# - cucumber -p verify -branches: - only: - - master - - develop -cache: -- bundler -- apt -env: - - CMAKEOPTIONS="-DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++-4.7" OSRM_PORT=5000 OSRM_TIMEOUT=60 - - CMAKEOPTIONS="-DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=g++-4.7" OSRM_PORT=5010 OSRM_TIMEOUT=60 -notifications: - irc: - channels: - - irc.oftc.net#osrm - on_success: change - on_failure: always - use_notice: true - skip_join: false - - recipients: - - dennis@mapbox.com - email: - on_success: change - on_failure: always diff --git a/3party/osrm/osrm-backend/Algorithms/BFSComponentExplorer.h b/3party/osrm/osrm-backend/Algorithms/BFSComponentExplorer.h index 7bc7ecb302..daab82a14f 100644 --- a/3party/osrm/osrm-backend/Algorithms/BFSComponentExplorer.h +++ b/3party/osrm/osrm-backend/Algorithms/BFSComponentExplorer.h @@ -1,8 +1,7 @@ -#ifndef __BFS_COMPONENT_EXPLORER_H__ -#define __BFS_COMPONENT_EXPLORER_H__ +#ifndef BFS_COMPONENT_EXPLORER_H_ +#define BFS_COMPONENT_EXPLORER_H_ #include "../typedefs.h" -#include "../DataStructures/DynamicGraph.h" #include "../DataStructures/RestrictionMap.h" #include @@ -13,10 +12,10 @@ template class BFSComponentExplorer { public: - BFSComponentExplorer(const GraphT &dynamicGraph, + BFSComponentExplorer(const GraphT &dynamic_graph, const RestrictionMap &restrictions, const std::unordered_set &barrier_nodes) - : m_graph(dynamicGraph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes) + : m_graph(dynamic_graph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes) { BOOST_ASSERT(m_graph.GetNumberOfNodes() > 0); } @@ -24,14 +23,14 @@ template class BFSComponentExplorer /*! * Returns the size of the component that the node belongs to. */ - inline unsigned int GetComponentSize(NodeID node) + unsigned int GetComponentSize(const NodeID node) const { BOOST_ASSERT(node < m_component_index_list.size()); return m_component_index_size[m_component_index_list[node]]; } - inline unsigned int GetNumberOfComponents() { return m_component_index_size.size(); } + unsigned int GetNumberOfComponents() { return m_component_index_size.size(); } /*! * Computes the component sizes. @@ -68,7 +67,7 @@ template class BFSComponentExplorer /*! * Explores the current component that starts at node using BFS. */ - inline unsigned ExploreComponent(std::queue> &bfs_queue, + unsigned ExploreComponent(std::queue> &bfs_queue, NodeID node, unsigned current_component) { @@ -145,4 +144,4 @@ template class BFSComponentExplorer const std::unordered_set &m_barrier_nodes; }; -#endif +#endif // BFS_COMPONENT_EXPLORER_H_ diff --git a/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.cpp b/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.cpp index f3a657fe17..6444f13575 100644 --- a/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.cpp +++ b/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.cpp @@ -25,17 +25,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include - #include "DouglasPeucker.h" + +#include "../DataStructures/Range.h" #include "../DataStructures/SegmentInformation.h" +#include + #include #include #include +namespace { struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; @@ -77,6 +80,7 @@ struct CoordinatePairCalculator float second_lat; float second_lon; }; +} DouglasPeucker::DouglasPeucker() : douglas_peucker_thresholds({512440, // z0 @@ -149,13 +153,13 @@ void DouglasPeucker::Run(std::vector &input_geometry, const int max_int_distance = 0; unsigned farthest_entry_index = pair.second; - const CoordinatePairCalculator DistCalc(input_geometry[pair.first].location, - input_geometry[pair.second].location); + const CoordinatePairCalculator dist_calc(input_geometry[pair.first].location, + input_geometry[pair.second].location); // sweep over range to find the maximum - for (unsigned i = pair.first + 1; i < pair.second; ++i) + for (const auto i : osrm::irange(pair.first + 1, pair.second)) { - const int distance = DistCalc(input_geometry[i].location); + const int distance = dist_calc(input_geometry[i].location); // found new feasible maximum? if (distance > max_int_distance && distance > douglas_peucker_thresholds[zoom_level]) { diff --git a/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.h b/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.h index d0f295cc6a..60fc377b10 100644 --- a/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.h +++ b/3party/osrm/osrm-backend/Algorithms/DouglasPeucker.h @@ -46,7 +46,7 @@ class DouglasPeucker private: std::vector douglas_peucker_thresholds; - typedef std::pair GeometryRange; + using GeometryRange = std::pair; // Stack to simulate the recursion std::stack recursion_stack; diff --git a/3party/osrm/osrm-backend/Algorithms/IteratorBasedCRC32.h b/3party/osrm/osrm-backend/Algorithms/IteratorBasedCRC32.h index 84a404a88f..a68514dceb 100644 --- a/3party/osrm/osrm-backend/Algorithms/IteratorBasedCRC32.h +++ b/3party/osrm/osrm-backend/Algorithms/IteratorBasedCRC32.h @@ -28,44 +28,59 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ITERATOR_BASED_CRC32_H #define ITERATOR_BASED_CRC32_H -#include "../Util/SimpleLogger.h" - -#include - #if defined(__x86_64__) && !defined(__MINGW64__) #include -#else +#endif + #include // for boost::crc_32_type -inline void __get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) +#include + +class IteratorbasedCRC32 { - *ecx = 0; -} -#endif + public: + bool using_hardware() const { return use_hardware_implementation; } -template class IteratorbasedCRC32 -{ - private: - typedef typename ContainerT::iterator IteratorType; - unsigned crc; + IteratorbasedCRC32() : crc(0) { use_hardware_implementation = detect_hardware_support(); } - bool use_SSE42_CRC_function; - -#if !defined(__x86_64__) - boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> CRC32_processor; -#endif - unsigned SoftwareBasedCRC32(char *str, unsigned len) + template unsigned operator()(Iterator iter, const Iterator end) { -#if !defined(__x86_64__) - CRC32_processor.process_bytes(str, len); - return CRC32_processor.checksum(); -#else - return 0; -#endif + unsigned crc = 0; + while (iter != end) + { + using value_type = typename std::iterator_traits::value_type; + char *data = (char *)(&(*iter)); + + if (use_hardware_implementation) + { + crc = compute_in_hardware(data, sizeof(value_type)); + } + else + { + crc = compute_in_software(data, sizeof(value_type)); + } + ++iter; + } + return crc; + } + + private: + bool detect_hardware_support() const + { + static const int sse42_bit = 0x00100000; + const unsigned ecx = cpuid(); + const bool sse42_found = (ecx & sse42_bit) != 0; + return sse42_found; + } + + unsigned compute_in_software(char *str, unsigned len) + { + crc_processor.process_bytes(str, len); + return crc_processor.checksum(); } // adapted from http://byteworm.com/2010/10/13/crc32/ - unsigned SSE42BasedCRC32(char *str, unsigned len) + unsigned compute_in_hardware(char *str, unsigned len) { #if defined(__x86_64__) unsigned q = len / sizeof(unsigned); @@ -101,44 +116,31 @@ template class IteratorbasedCRC32 return ecx; } - bool DetectNativeCRC32Support() +#if defined(__MINGW64__) || defined(_MSC_VER) + inline void + __get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) const { - static const int SSE42_BIT = 0x00100000; - const unsigned ecx = cpuid(); - const bool has_SSE42 = (ecx & SSE42_BIT) != 0; - if (has_SSE42) - { - SimpleLogger().Write() << "using hardware based CRC32 computation"; - } - else - { - SimpleLogger().Write() << "using software based CRC32 computation"; - } - return has_SSE42; + *ecx = 0; + } +#endif + + boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> crc_processor; + unsigned crc; + bool use_hardware_implementation; +}; + +struct RangebasedCRC32 +{ + template + unsigned operator()(const Iteratable &iterable) + { + return crc32(std::begin(iterable), std::end(iterable)); } - public: - IteratorbasedCRC32() : crc(0) { use_SSE42_CRC_function = DetectNativeCRC32Support(); } + bool using_hardware() const { return crc32.using_hardware(); } - unsigned operator()(IteratorType iter, const IteratorType end) - { - unsigned crc = 0; - while (iter != end) - { - char *data = reinterpret_cast(&(*iter)); - - if (use_SSE42_CRC_function) - { - crc = SSE42BasedCRC32(data, sizeof(typename ContainerT::value_type)); - } - else - { - crc = SoftwareBasedCRC32(data, sizeof(typename ContainerT::value_type)); - } - ++iter; - } - return crc; - } + private: + IteratorbasedCRC32 crc32; }; #endif /* ITERATOR_BASED_CRC32_H */ diff --git a/3party/osrm/osrm-backend/Algorithms/ObjectToBase64.h b/3party/osrm/osrm-backend/Algorithms/ObjectToBase64.h index b273043790..6930b9c2c1 100644 --- a/3party/osrm/osrm-backend/Algorithms/ObjectToBase64.h +++ b/3party/osrm/osrm-backend/Algorithms/ObjectToBase64.h @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef OBJECTTOBASE64_H_ -#define OBJECTTOBASE64_H_ +#ifndef OBJECT_TO_BASE64_H_ +#define OBJECT_TO_BASE64_H_ #include "../Util/StringUtil.h" @@ -39,61 +39,56 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -typedef - boost::archive::iterators::base64_from_binary< - boost::archive::iterators::transform_width - > base64_t; +struct ObjectEncoder +{ + using base64_t = boost::archive::iterators::base64_from_binary< + boost::archive::iterators::transform_width>; -typedef - boost::archive::iterators::transform_width< - boost::archive::iterators::binary_from_base64< - std::string::const_iterator>, 8, 6 - > binary_t; + using binary_t = boost::archive::iterators::transform_width< + boost::archive::iterators::binary_from_base64, + 8, + 6>; -template -static void EncodeObjectToBase64(const ObjectT & object, std::string& encoded) { - const char * char_ptr_to_object = (const char *)&object; - std::vector data(sizeof(object)); - std::copy( - char_ptr_to_object, - char_ptr_to_object + sizeof(ObjectT), - data.begin() - ); + template + static void EncodeToBase64(const ObjectT &object, std::string &encoded) + { + const char *char_ptr_to_object = (const char *)&object; + std::vector data(sizeof(object)); + std::copy(char_ptr_to_object, char_ptr_to_object + sizeof(ObjectT), data.begin()); - unsigned char number_of_padded_chars = 0; // is in {0,1,2}; - while(data.size() % 3 != 0) { - ++number_of_padded_chars; - data.push_back(0x00); + unsigned char number_of_padded_chars = 0; // is in {0,1,2}; + while (data.size() % 3 != 0) + { + ++number_of_padded_chars; + data.push_back(0x00); + } + + BOOST_ASSERT_MSG(0 == data.size() % 3, "base64 input data size is not a multiple of 3!"); + encoded.resize(sizeof(ObjectT)); + encoded.assign(base64_t(&data[0]), + base64_t(&data[0] + (data.size() - number_of_padded_chars))); + replaceAll(encoded, "+", "-"); + replaceAll(encoded, "/", "_"); } - BOOST_ASSERT_MSG( - 0 == data.size() % 3, - "base64 input data size is not a multiple of 3!" - ); - encoded.resize(sizeof(ObjectT)); - encoded.assign( - base64_t( &data[0] ), - base64_t( &data[0] + (data.size() - number_of_padded_chars) ) - ); - replaceAll(encoded, "+", "-"); - replaceAll(encoded, "/", "_"); -} + template + static void DecodeFromBase64(const std::string &input, ObjectT &object) + { + try + { + std::string encoded(input); + // replace "-" with "+" and "_" with "/" + replaceAll(encoded, "-", "+"); + replaceAll(encoded, "_", "/"); -template -static void DecodeObjectFromBase64(const std::string& input, ObjectT & object) { - try { - std::string encoded(input); - //replace "-" with "+" and "_" with "/" - replaceAll(encoded, "-", "+"); - replaceAll(encoded, "_", "/"); + std::copy(binary_t(encoded.begin()), + binary_t(encoded.begin() + encoded.length() - 1), + (char *)&object); + } + catch (...) + { + } + } +}; - std::copy ( - binary_t( encoded.begin() ), - binary_t( encoded.begin() + encoded.length() - 1), - (char *)&object - ); - - } catch(...) { } -} - -#endif /* OBJECTTOBASE64_H_ */ +#endif /* OBJECT_TO_BASE64_H_ */ diff --git a/3party/osrm/osrm-backend/Algorithms/PolylineCompressor.cpp b/3party/osrm/osrm-backend/Algorithms/PolylineCompressor.cpp index ca4a019c06..bae40052b3 100644 --- a/3party/osrm/osrm-backend/Algorithms/PolylineCompressor.cpp +++ b/3party/osrm/osrm-backend/Algorithms/PolylineCompressor.cpp @@ -30,8 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -void PolylineCompressor::encodeVectorSignedNumber(std::vector &numbers, std::string &output) - const +void PolylineCompressor::encodeVectorSignedNumber(std::vector &numbers, + std::string &output) const { const unsigned end = static_cast(numbers.size()); for (unsigned i = 0; i < end; ++i) @@ -69,8 +69,8 @@ void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output) } } -JSON::String PolylineCompressor::printEncodedString(const std::vector &polyline) - const +JSON::String +PolylineCompressor::printEncodedString(const std::vector &polyline) const { std::string output; std::vector delta_numbers; @@ -102,12 +102,10 @@ PolylineCompressor::printUnencodedString(const std::vector & { if (segment.necessary) { - std::string tmp, output; - FixedPointCoordinate::convertInternalLatLonToString(segment.location.lat, tmp); - output += (tmp + ","); - FixedPointCoordinate::convertInternalLatLonToString(segment.location.lon, tmp); - output += tmp; - json_geometry_array.values.push_back(output); + 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); } } return json_geometry_array; diff --git a/3party/osrm/osrm-backend/Algorithms/StronglyConnectedComponents.h b/3party/osrm/osrm-backend/Algorithms/StronglyConnectedComponents.h index bc9ba0406b..681f78fa3b 100644 --- a/3party/osrm/osrm-backend/Algorithms/StronglyConnectedComponents.h +++ b/3party/osrm/osrm-backend/Algorithms/StronglyConnectedComponents.h @@ -39,7 +39,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/TurnInstructions.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/StdHashExtensions.h" #include "../Util/TimingUtil.h" @@ -92,12 +92,12 @@ class TarjanSCC NodeID parent; }; - typedef DynamicGraph TarjanDynamicGraph; - typedef TarjanDynamicGraph::InputEdge TarjanEdge; - typedef std::pair RestrictionSource; - typedef std::pair RestrictionTarget; - typedef std::vector EmanatingRestrictionsVector; - typedef std::unordered_map RestrictionMap; + using TarjanDynamicGraph = DynamicGraph; + using TarjanEdge = TarjanDynamicGraph::InputEdge; + using RestrictionSource = std::pair; + using RestrictionTarget = std::pair; + using EmanatingRestrictionsVector = std::vector; + using RestrictionMap = std::unordered_map; std::vector m_coordinate_list; std::vector m_restriction_bucket_list; diff --git a/3party/osrm/osrm-backend/Benchmarks/StaticRTreeBench.cpp b/3party/osrm/osrm-backend/Benchmarks/StaticRTreeBench.cpp index a7c9a5c2e5..b0b34fb6e0 100644 --- a/3party/osrm/osrm-backend/Benchmarks/StaticRTreeBench.cpp +++ b/3party/osrm/osrm-backend/Benchmarks/StaticRTreeBench.cpp @@ -11,16 +11,16 @@ // 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; -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; +constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION; +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; -typedef EdgeBasedNode RTreeLeaf; -typedef std::shared_ptr> FixedPointCoordinateListPtr; -typedef StaticRTree::vector, false> BenchStaticRTree; +using RTreeLeaf = EdgeBasedNode; +using FixedPointCoordinateListPtr = std::shared_ptr>; +using BenchStaticRTree = StaticRTree::vector, false>; -FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path& nodes_file) +FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes_file) { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); @@ -39,74 +39,86 @@ FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path& nodes return coords; } -void Benchmark(BenchStaticRTree& rtree, unsigned num_queries) +void Benchmark(BenchStaticRTree &rtree, unsigned num_queries) { - std::mt19937 g(RANDOM_SEED); + std::mt19937 mt_rand(RANDOM_SEED); std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT); std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON); std::vector queries; for (unsigned i = 0; i < num_queries; i++) { - queries.emplace_back( - FixedPointCoordinate(lat_udist(g), lon_udist(g)) - ); + queries.emplace_back(FixedPointCoordinate(lat_udist(mt_rand), lon_udist(mt_rand))); } const unsigned num_results = 5; - std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results << " phantom nodes" << std::endl; + std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results + << " phantom nodes" + << "\n"; TIMER_START(query_phantom); std::vector resulting_phantom_node_vector; - for (const auto& q : queries) + for (const auto &q : queries) { resulting_phantom_node_vector.clear(); - rtree.IncrementalFindPhantomNodeForCoordinate(q, resulting_phantom_node_vector, 3, num_results); + rtree.IncrementalFindPhantomNodeForCoordinate( + q, resulting_phantom_node_vector, 3, num_results); resulting_phantom_node_vector.clear(); - rtree.IncrementalFindPhantomNodeForCoordinate(q, resulting_phantom_node_vector, 17, num_results); + rtree.IncrementalFindPhantomNodeForCoordinate( + q, resulting_phantom_node_vector, 17, num_results); } TIMER_STOP(query_phantom); - std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries." << std::endl; - std::cout << TIMER_MSEC(query_phantom)/((double) num_queries) << " msec/query." << std::endl; + std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries." + << "\n"; + std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query." + << "\n"; - std::cout << "#### LocateClosestEndPointForCoordinate" << std::endl; + std::cout << "#### LocateClosestEndPointForCoordinate" + << "\n"; TIMER_START(query_endpoint); FixedPointCoordinate result; - for (const auto& q : queries) + for (const auto &q : queries) { rtree.LocateClosestEndPointForCoordinate(q, result, 3); } TIMER_STOP(query_endpoint); - std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries." << std::endl; - std::cout << TIMER_MSEC(query_endpoint)/((double) num_queries) << " msec/query." << std::endl; + std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries." + << "\n"; + std::cout << TIMER_MSEC(query_endpoint) / ((double)num_queries) << " msec/query." + << "\n"; - std::cout << "#### FindPhantomNodeForCoordinate" << std::endl; + std::cout << "#### FindPhantomNodeForCoordinate" + << "\n"; TIMER_START(query_phantomnode); - for (const auto& q : queries) + for (const auto &q : queries) { PhantomNode phantom; rtree.FindPhantomNodeForCoordinate(q, phantom, 3); } TIMER_STOP(query_phantomnode); - std::cout << "Took " << TIMER_MSEC(query_phantomnode) << " msec for " << num_queries << " queries." << std::endl; - std::cout << TIMER_MSEC(query_phantomnode)/((double) num_queries) << " msec/query." << std::endl; + std::cout << "Took " << TIMER_MSEC(query_phantomnode) << " msec for " << num_queries + << " queries." + << "\n"; + std::cout << TIMER_MSEC(query_phantomnode) / ((double)num_queries) << " msec/query." + << "\n"; } -int main(int argc, char** argv) +int main(int argc, char **argv) { if (argc < 4) { - std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes" << std::endl; + std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes" + << "\n"; return 1; } - const char* ramPath = argv[1]; - const char* filePath = argv[2]; - const char* nodesPath = argv[3]; + const char *ramPath = argv[1]; + const char *filePath = argv[2]; + const char *nodesPath = argv[3]; auto coords = LoadCoordinates(nodesPath); diff --git a/3party/osrm/osrm-backend/CMakeLists.txt b/3party/osrm/osrm-backend/CMakeLists.txt index 4ce0e220df..b1034b1fdd 100644 --- a/3party/osrm/osrm-backend/CMakeLists.txt +++ b/3party/osrm/osrm-backend/CMakeLists.txt @@ -1,11 +1,16 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 2.8.8) + +if( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE ) + message(FATAL_ERROR "In-source builds are not allowed. +Please create a directory and run cmake from there, passing the path to this source directory as the last argument. +This process created the file `CMakeCache.txt' and the directory `CMakeFiles'. Please delete them.") +endif() + project(OSRM) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) include(CheckCXXCompilerFlag) include(FindPackageHandleStandardArgs) -set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) - list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") include(GetGitRevisionDescription) git_describe(GIT_DESCRIPTION) @@ -22,7 +27,8 @@ if (WIN32 AND MSVC_VERSION LESS 1800) message(FATAL_ERROR "Building with Microsoft compiler needs Visual Studio 2013 or later (Express version works too)") endif() -OPTION(WITH_TOOLS "Build ORSM tools" OFF) +OPTION(WITH_TOOLS "Build OSRM tools" OFF) +OPTION(BUILD_TOOLS "Build OSRM tools" OFF) include_directories(${CMAKE_SOURCE_DIR}/Include/) @@ -35,33 +41,36 @@ add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp FingerPrint.c VERBATIM) add_custom_target(FingerPrintConfigure DEPENDS ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp) +add_custom_target(tests DEPENDS datastructure-tests) +add_custom_target(benchmarks DEPENDS rtree-bench) -set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread) +set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread unit_test_framework) configure_file( ${CMAKE_SOURCE_DIR}/Util/GitDescription.cpp.in ${CMAKE_SOURCE_DIR}/Util/GitDescription.cpp ) file(GLOB ExtractorGlob Extractor/*.cpp) -file(GLOB ExtractorGlobH Extractor/*.h) file(GLOB ImporterGlob DataStructures/Import*.cpp) -add_library(IMPORT STATIC ${ImporterGlob}) -set(ExtractorSources extractor.cpp ${ExtractorGlob} ${ExtractorGlobH}) -add_executable(osrm-extract ${ExtractorSources}) +add_library(IMPORT OBJECT ${ImporterGlob}) +add_library(LOGGER OBJECT Util/simple_logger.cpp) -file(GLOB PrepareGlobH Contractor/*.h DataStructures/*.h) -file(GLOB PrepareGlob Contractor/*.cpp DataStructures/HilbertValue.cpp DataStructures/RestrictionMap.cpp) -set(PrepareSources prepare.cpp ${PrepareGlob} ${PrepareGlobH}) -add_executable(osrm-prepare ${PrepareSources}) +set(ExtractorSources extractor.cpp ${ExtractorGlob}) +add_executable(osrm-extract ${ExtractorSources} $ $ $ $ $) + +file(GLOB PrepareGlob Contractor/*.cpp DataStructures/HilbertValue.cpp DataStructures/RestrictionMap.cpp Util/compute_angle.cpp) +set(PrepareSources prepare.cpp ${PrepareGlob}) +add_executable(osrm-prepare ${PrepareSources} $ $ $ $ $) file(GLOB ServerGlob Server/*.cpp) -file(GLOB RoutingAlgs RoutingAlgorithms/*.h) file(GLOB DescriptorGlob Descriptors/*.cpp) file(GLOB DatastructureGlob DataStructures/SearchEngineData.cpp DataStructures/RouteParameters.cpp) +list(REMOVE_ITEM DatastructureGlob DataStructures/Coordinate.cpp) file(GLOB CoordinateGlob DataStructures/Coordinate.cpp) file(GLOB AlgorithmGlob Algorithms/*.cpp) file(GLOB HttpGlob Server/Http/*.cpp) file(GLOB LibOSRMGlob Library/*.cpp) +file(GLOB DataStructureTestsGlob UnitTests/DataStructures/*.cpp DataStructures/HilbertValue.cpp) set( OSRMSources @@ -72,14 +81,20 @@ set( ${AlgorithmGlob} ${HttpGlob} ) -add_library(COORDLIB STATIC ${CoordinateGlob}) -add_library(FINGERPRINT STATIC Util/FingerPrint.cpp) -add_library(OSRM ${OSRMSources} Util/GitDescription.cpp Util/FingerPrint.cpp) -add_library(GITDESCRIPTION STATIC Util/GitDescription.cpp) +add_library(COORDINATE OBJECT ${CoordinateGlob}) +add_library(FINGERPRINT OBJECT Util/FingerPrint.cpp) +add_library(GITDESCRIPTION OBJECT Util/GitDescription.cpp) +add_library(OSRM ${OSRMSources} $ $ $ $) add_dependencies(FINGERPRINT FingerPrintConfigure) -add_executable(osrm-routed routed.cpp ${ServerGlob} ${RoutingAlgs}) -add_executable(osrm-datastore datastore.cpp) +add_executable(osrm-routed routed.cpp ${ServerGlob}) +add_executable(osrm-datastore datastore.cpp $ $ $ $) + +# Unit tests +add_executable(datastructure-tests EXCLUDE_FROM_ALL UnitTests/datastructure_tests.cpp ${DataStructureTestsGlob} $ $) + +# Benchmarks +add_executable(rtree-bench EXCLUDE_FROM_ALL Benchmarks/StaticRTreeBench.cpp $ $) # Check the release mode if(NOT CMAKE_BUILD_TYPE MATCHES Debug) @@ -103,7 +118,7 @@ if(CMAKE_BUILD_TYPE MATCHES Release) # Since gcc 4.9 the LTO format is non-standart ('slim'), so we need to use the build-in tools if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND - NOT "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9.0") + NOT "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9.0" AND NOT MINGW) message(STATUS "Using gcc specific binutils for LTO.") set(CMAKE_AR "/usr/bin/gcc-ar") set(CMAKE_RANLIB "/usr/bin/gcc-ranlib") @@ -111,6 +126,10 @@ if(CMAKE_BUILD_TYPE MATCHES Release) endif (HAS_LTO_FLAG) endif() +if (NOT WIN32) +add_definitions(-DBOOST_TEST_DYN_LINK) +endif() + # Configuring compilers if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # using Clang @@ -119,10 +138,9 @@ elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # using GCC set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -fPIC") if (WIN32) # using mingw - add_definitions(-DM_PI=3.141592653589793238462643383) # define M_PI + add_definitions(-D_USE_MATH_DEFINES) # define M_PI, M_1_PI etc. add_definitions(-DWIN32) SET(OPTIONAL_SOCKET_LIBS ws2_32 wsock32) - SET(OPTIONAL_OMP_LIB gomp) endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") # using Intel C++ @@ -136,18 +154,6 @@ elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") add_definitions(-D_WIN32_WINNT=0x0501) endif() -# disable partitioning of LTO process when possible (fixes Debian issues) -set(LTO_PARTITION_FLAGS "") -CHECK_CXX_COMPILER_FLAG("-flto-partition=none" HAS_LTO_PARTITION_FLAG) -if (HAS_LTO_PARTITION_FLAG) - set(LTO_PARTITION_FLAGS "${LTO_PARTITION_FLAGS} -flto-partition=none") -endif (HAS_LTO_PARTITION_FLAG) - -# Add Link-Time-Optimization flags, if supported (GCC >= 4.7) and enabled -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LTO_FLAGS}") -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LTO_FLAGS} ${LTO_PARTITION_FLAGS}") -set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LTO_FLAGS} ${LTO_PARTITION_FLAGS}") - # Activate C++11 if(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") ADD_DEFINITIONS(-std=c++11) @@ -182,16 +188,21 @@ if(NOT Boost_FOUND) endif() include_directories(${Boost_INCLUDE_DIRS}) -target_link_libraries(OSRM ${Boost_LIBRARIES} COORDLIB) -target_link_libraries(osrm-extract ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB IMPORT) -target_link_libraries(osrm-prepare ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB IMPORT) -target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM FINGERPRINT GITDESCRIPTION) -target_link_libraries(osrm-datastore ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB) +target_link_libraries(OSRM ${Boost_LIBRARIES}) +target_link_libraries(osrm-extract ${Boost_LIBRARIES}) +target_link_libraries(osrm-prepare ${Boost_LIBRARIES}) +target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) +target_link_libraries(osrm-datastore ${Boost_LIBRARIES}) +target_link_libraries(datastructure-tests ${Boost_LIBRARIES}) +target_link_libraries(rtree-bench ${Boost_LIBRARIES}) find_package(Threads REQUIRED) -target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT} ${OPTIONAL_OMP_LIB}) +target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(osrm-datastore ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(osrm-prepare ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(OSRM ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(datastructure-tests ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(rtree-bench ${CMAKE_THREAD_LIBS_INIT}) find_package(TBB REQUIRED) if(WIN32 AND CMAKE_BUILD_TYPE MATCHES Debug) @@ -201,21 +212,13 @@ target_link_libraries(osrm-datastore ${TBB_LIBRARIES}) target_link_libraries(osrm-extract ${TBB_LIBRARIES}) target_link_libraries(osrm-prepare ${TBB_LIBRARIES}) target_link_libraries(osrm-routed ${TBB_LIBRARIES}) +target_link_libraries(datastructure-tests ${TBB_LIBRARIES}) +target_link_libraries(rtree-bench ${TBB_LIBRARIES}) include_directories(${TBB_INCLUDE_DIR}) -find_package(Lua52) -if(NOT LUA52_FOUND) - find_package(Lua51 REQUIRED) - if(NOT APPLE) - find_package(LuaJIT 5.1) - endif() -else() - if(NOT APPLE) - find_package(LuaJIT 5.2) - endif() -endif() - find_package( Luabind REQUIRED ) +include(check_luabind) + include_directories(${LUABIND_INCLUDE_DIR}) target_link_libraries(osrm-extract ${LUABIND_LIBRARY}) target_link_libraries(osrm-prepare ${LUABIND_LIBRARY}) @@ -258,29 +261,40 @@ include_directories(${ZLIB_INCLUDE_DIRS}) target_link_libraries(osrm-extract ${ZLIB_LIBRARY}) target_link_libraries(osrm-routed ${ZLIB_LIBRARY}) -if(WITH_TOOLS) +if(WITH_TOOLS OR BUILD_TOOLS) message(STATUS "Activating OSRM internal tools") find_package(GDAL) if(GDAL_FOUND) - add_executable(osrm-components Tools/components.cpp) - target_link_libraries(osrm-components ${TBB_LIBRARIES} IMPORT) + add_executable(osrm-components Tools/components.cpp $ $ $ $) + target_link_libraries(osrm-components ${TBB_LIBRARIES}) include_directories(${GDAL_INCLUDE_DIR}) target_link_libraries( osrm-components - ${GDAL_LIBRARIES} ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB) + ${GDAL_LIBRARIES} ${Boost_LIBRARIES}) + install(TARGETS osrm-components DESTINATION bin) else() message(FATAL_ERROR "libgdal and/or development headers not found") endif() - add_executable(osrm-cli Tools/simpleclient.cpp) - target_link_libraries(osrm-cli ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM FINGERPRINT GITDESCRIPTION) + add_executable(osrm-cli Tools/simpleclient.cpp $) + target_link_libraries(osrm-cli ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) target_link_libraries(osrm-cli ${TBB_LIBRARIES}) - add_executable(osrm-io-benchmark Tools/io-benchmark.cpp) - target_link_libraries(osrm-io-benchmark ${Boost_LIBRARIES} GITDESCRIPTION) - add_executable(osrm-unlock-all Tools/unlock_all_mutexes.cpp) - target_link_libraries(osrm-unlock-all ${Boost_LIBRARIES} GITDESCRIPTION) + add_executable(osrm-io-benchmark Tools/io-benchmark.cpp $ $) + target_link_libraries(osrm-io-benchmark ${Boost_LIBRARIES}) + add_executable(osrm-unlock-all Tools/unlock_all_mutexes.cpp $ $) + target_link_libraries(osrm-unlock-all ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) if(UNIX AND NOT APPLE) target_link_libraries(osrm-unlock-all rt) endif() + add_executable(osrm-check-hsgr Tools/check-hsgr.cpp $ $) + target_link_libraries(osrm-check-hsgr ${Boost_LIBRARIES}) + add_executable(osrm-springclean Tools/springclean.cpp $ $ $) + target_link_libraries(osrm-springclean ${Boost_LIBRARIES}) + + install(TARGETS osrm-cli DESTINATION bin) + install(TARGETS osrm-io-benchmark DESTINATION bin) + install(TARGETS osrm-unlock-all DESTINATION bin) + install(TARGETS osrm-check-hsgr DESTINATION bin) + install(TARGETS osrm-springclean DESTINATION bin) endif() file(GLOB InstallGlob Include/osrm/*.h Library/OSRM.h) @@ -311,4 +325,7 @@ endforeach () configure_file(${CMAKE_SOURCE_DIR}/cmake/pkgconfig.in libosrm.pc @ONLY) install(FILES ${PROJECT_BINARY_DIR}/libosrm.pc DESTINATION lib/pkgconfig) -add_subdirectory(mapsme) +if(BUILD_DEBIAN_PACKAGE) + include(CPackDebianConfig) + include(CPack) +endif() diff --git a/3party/osrm/osrm-backend/Contractor/Contractor.h b/3party/osrm/osrm-backend/Contractor/Contractor.h index 514d9649f3..9e1214f630 100644 --- a/3party/osrm/osrm-backend/Contractor/Contractor.h +++ b/3party/osrm/osrm-backend/Contractor/Contractor.h @@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/Range.h" #include "../DataStructures/XORFastHash.h" #include "../DataStructures/XORFastHashStorage.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/StringUtil.h" #include "../Util/TimingUtil.h" #include "../typedefs.h" @@ -92,19 +92,18 @@ class Contractor ContractorHeapData(short h, bool t) : hop(h), target(t) {} }; - typedef DynamicGraph ContractorGraph; - // typedef BinaryHeap< NodeID, NodeID, int, ContractorHeapData, ArrayStorage - // > ContractorHeap; - typedef BinaryHeap> - ContractorHeap; - typedef ContractorGraph::InputEdge ContractorEdge; + using ContractorGraph = DynamicGraph; + // using ContractorHeap = BinaryHeap + // >; + using ContractorHeap = BinaryHeap>; + using ContractorEdge = ContractorGraph::InputEdge; struct ContractorThreadData { ContractorHeap heap; std::vector inserted_edges; std::vector neighbours; - ContractorThreadData(NodeID nodes) : heap(nodes) {} + explicit ContractorThreadData(NodeID nodes) : heap(nodes) {} }; struct NodePriorityData @@ -136,7 +135,7 @@ class Contractor struct ThreadDataContainer { - ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {} + explicit ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {} inline ContractorThreadData* getThreadData() { @@ -151,7 +150,7 @@ class Contractor } int number_of_nodes; - typedef tbb::enumerable_thread_specific> EnumerableThreadData; + using EnumerableThreadData = tbb::enumerable_thread_specific>; EnumerableThreadData data; }; diff --git a/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.cpp b/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.cpp index 590fce8ab5..2d58c90e82 100644 --- a/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.cpp +++ b/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.cpp @@ -29,28 +29,27 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../Algorithms/BFSComponentExplorer.h" #include "../DataStructures/Percent.h" #include "../DataStructures/Range.h" -#include "../Util/ComputeAngle.h" +#include "../Util/compute_angle.hpp" #include "../Util/LuaUtil.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/TimingUtil.h" #include #include +#include #include EdgeBasedGraphFactory::EdgeBasedGraphFactory( const std::shared_ptr &node_based_graph, - const std::shared_ptr &node_based_graph_origin, std::unique_ptr restriction_map, std::vector &barrier_node_list, std::vector &traffic_light_node_list, - std::vector &m_node_info_list, + std::vector &node_info_list, SpeedProfileProperties &speed_profile) : speed_profile(speed_profile), m_number_of_edge_based_nodes(std::numeric_limits::max()), - m_node_info_list(m_node_info_list), m_node_based_graph(node_based_graph), - m_node_based_graph_origin(node_based_graph_origin), + m_node_info_list(node_info_list), m_node_based_graph(node_based_graph), m_restriction_map(std::move(restriction_map)), max_id(0) { @@ -79,35 +78,30 @@ void EdgeBasedGraphFactory::GetEdgeBasedNodes(std::vector &nodes) nodes.swap(m_edge_based_node_list); } -void EdgeBasedGraphFactory::GetEdgeBasedNodeData(osrm::NodeDataVectorT &data) -{ - data.swap(m_edge_based_node_data); -} - void -EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const bool belongs_to_tiny_cc) +EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeID node_v, const bool belongs_to_tiny_cc) { // merge edges together into one EdgeBasedNode - BOOST_ASSERT(u != SPECIAL_NODEID); - BOOST_ASSERT(v != SPECIAL_NODEID); + BOOST_ASSERT(node_u != SPECIAL_NODEID); + BOOST_ASSERT(node_v != SPECIAL_NODEID); // find forward edge id and - const EdgeID e1 = m_node_based_graph->FindEdge(u, v); + const EdgeID e1 = m_node_based_graph->FindEdge(node_u, node_v); BOOST_ASSERT(e1 != SPECIAL_EDGEID); const EdgeData &forward_data = m_node_based_graph->GetEdgeData(e1); // find reverse edge id and - const EdgeID e2 = m_node_based_graph->FindEdge(v, u); + const EdgeID e2 = m_node_based_graph->FindEdge(node_v, node_u); #ifndef NDEBUG - if (e2 == m_node_based_graph->EndEdges(v)) + if (e2 == m_node_based_graph->EndEdges(node_v)) { - SimpleLogger().Write(logWARNING) << "Did not find edge (" << v << "," << u << ")"; + SimpleLogger().Write(logWARNING) << "Did not find edge (" << node_v << "," << node_u << ")"; } #endif BOOST_ASSERT(e2 != SPECIAL_EDGEID); - BOOST_ASSERT(e2 < m_node_based_graph->EndEdges(v)); + BOOST_ASSERT(e2 < m_node_based_graph->EndEdges(node_v)); const EdgeData &reverse_data = m_node_based_graph->GetEdgeData(e2); if (forward_data.edgeBasedNodeID == SPECIAL_NODEID && @@ -157,7 +151,7 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const // BOOST_ASSERT(reverse_data.distance >= temp_sum); } - NodeID current_edge_source_coordinate_id = u; + NodeID current_edge_source_coordinate_id = node_u; if (SPECIAL_NODEID != forward_data.edgeBasedNodeID) { @@ -177,32 +171,32 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const BOOST_ASSERT(current_edge_target_coordinate_id != current_edge_source_coordinate_id); // build edges - m_edge_based_node_list.emplace_back(forward_data.way_id, - reverse_data.way_id, - forward_data.edgeBasedNodeID, + m_edge_based_node_list.emplace_back(forward_data.edgeBasedNodeID, reverse_data.edgeBasedNodeID, current_edge_source_coordinate_id, current_edge_target_coordinate_id, forward_data.nameID, forward_geometry[i].second, - reverse_geometry[i].second, + reverse_geometry[geometry_size - 1 - i].second, forward_dist_prefix_sum[i], reverse_dist_prefix_sum[i], m_geometry_compressor.GetPositionForID(e1), i, - belongs_to_tiny_cc); + belongs_to_tiny_cc, + forward_data.travel_mode, + reverse_data.travel_mode); current_edge_source_coordinate_id = current_edge_target_coordinate_id; BOOST_ASSERT(m_edge_based_node_list.back().IsCompressed()); - BOOST_ASSERT(u != m_edge_based_node_list.back().u || - v != m_edge_based_node_list.back().v); + BOOST_ASSERT(node_u != m_edge_based_node_list.back().u || + node_v != m_edge_based_node_list.back().v); - BOOST_ASSERT(u != m_edge_based_node_list.back().v || - v != m_edge_based_node_list.back().u); + BOOST_ASSERT(node_u != m_edge_based_node_list.back().v || + node_v != m_edge_based_node_list.back().u); } - BOOST_ASSERT(current_edge_source_coordinate_id == v); + BOOST_ASSERT(current_edge_source_coordinate_id == node_v); BOOST_ASSERT(m_edge_based_node_list.back().IsCompressed()); } else @@ -229,12 +223,10 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const BOOST_ASSERT(forward_data.edgeBasedNodeID != SPECIAL_NODEID || reverse_data.edgeBasedNodeID != SPECIAL_NODEID); - m_edge_based_node_list.emplace_back(forward_data.way_id, - reverse_data.way_id, - forward_data.edgeBasedNodeID, + m_edge_based_node_list.emplace_back(forward_data.edgeBasedNodeID, reverse_data.edgeBasedNodeID, - u, - v, + node_u, + node_v, forward_data.nameID, forward_data.distance, reverse_data.distance, @@ -242,7 +234,9 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const 0, SPECIAL_EDGEID, 0, - belongs_to_tiny_cc); + belongs_to_tiny_cc, + forward_data.travel_mode, + reverse_data.travel_mode); BOOST_ASSERT(!m_edge_based_node_list.back().IsCompressed()); } } @@ -279,11 +273,6 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state); TIMER_STOP(generate_edges); - TIMER_START(generate_node_data); - GenerateEdgeBasedNodeData(); - TIMER_STOP(generate_node_data); - - m_geometry_compressor.SerializeInternalVector(geometry_filename); SimpleLogger().Write() << "Timing statistics for edge-expanded graph:"; @@ -291,7 +280,6 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, 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"; - SimpleLogger().Write() << "Generating node data: " << TIMER_SEC(generate_node_data) << "s"; } void EdgeBasedGraphFactory::CompressGeometry() @@ -301,61 +289,61 @@ void EdgeBasedGraphFactory::CompressGeometry() const unsigned original_number_of_nodes = m_node_based_graph->GetNumberOfNodes(); const unsigned original_number_of_edges = m_node_based_graph->GetNumberOfEdges(); - Percent p(original_number_of_nodes); + Percent progress(original_number_of_nodes); unsigned removed_node_count = 0; - for (const NodeID v : osrm::irange(0u, original_number_of_nodes)) + for (const NodeID node_v : osrm::irange(0u, original_number_of_nodes)) { - p.printStatus(v); + progress.printStatus(node_v); // only contract degree 2 vertices - if (2 != m_node_based_graph->GetOutDegree(v)) + if (2 != m_node_based_graph->GetOutDegree(node_v)) { continue; } // don't contract barrier node - if (m_barrier_nodes.end() != m_barrier_nodes.find(v)) + if (m_barrier_nodes.end() != m_barrier_nodes.find(node_v)) { continue; } // check if v is a via node for a turn restriction, i.e. a 'directed' barrier node - if (m_restriction_map->IsViaNode(v)) + if (m_restriction_map->IsViaNode(node_v)) { continue; } const bool reverse_edge_order = - !(m_node_based_graph->GetEdgeData(m_node_based_graph->BeginEdges(v)).forward); - const EdgeID forward_e2 = m_node_based_graph->BeginEdges(v) + reverse_edge_order; + !(m_node_based_graph->GetEdgeData(m_node_based_graph->BeginEdges(node_v)).forward); + const EdgeID forward_e2 = m_node_based_graph->BeginEdges(node_v) + reverse_edge_order; BOOST_ASSERT(SPECIAL_EDGEID != forward_e2); - const EdgeID reverse_e2 = m_node_based_graph->BeginEdges(v) + 1 - reverse_edge_order; + const EdgeID reverse_e2 = m_node_based_graph->BeginEdges(node_v) + 1 - reverse_edge_order; BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2); const EdgeData &fwd_edge_data2 = m_node_based_graph->GetEdgeData(forward_e2); const EdgeData &rev_edge_data2 = m_node_based_graph->GetEdgeData(reverse_e2); - const NodeID w = m_node_based_graph->GetTarget(forward_e2); - BOOST_ASSERT(SPECIAL_NODEID != w); - BOOST_ASSERT(v != w); - const NodeID u = m_node_based_graph->GetTarget(reverse_e2); - BOOST_ASSERT(SPECIAL_NODEID != u); - BOOST_ASSERT(u != v); + const NodeID node_w = m_node_based_graph->GetTarget(forward_e2); + BOOST_ASSERT(SPECIAL_NODEID != node_w); + BOOST_ASSERT(node_v != node_w); + const NodeID node_u = m_node_based_graph->GetTarget(reverse_e2); + BOOST_ASSERT(SPECIAL_NODEID != node_u); + BOOST_ASSERT(node_u != node_v); - const EdgeID forward_e1 = m_node_based_graph->FindEdge(u, v); - BOOST_ASSERT(m_node_based_graph->EndEdges(u) != forward_e1); + const EdgeID forward_e1 = m_node_based_graph->FindEdge(node_u, node_v); + BOOST_ASSERT(m_node_based_graph->EndEdges(node_u) != forward_e1); BOOST_ASSERT(SPECIAL_EDGEID != forward_e1); - BOOST_ASSERT(v == m_node_based_graph->GetTarget(forward_e1)); - const EdgeID reverse_e1 = m_node_based_graph->FindEdge(w, v); + BOOST_ASSERT(node_v == m_node_based_graph->GetTarget(forward_e1)); + const EdgeID reverse_e1 = m_node_based_graph->FindEdge(node_w, node_v); BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1); - BOOST_ASSERT(v == m_node_based_graph->GetTarget(reverse_e1)); + BOOST_ASSERT(node_v == m_node_based_graph->GetTarget(reverse_e1)); const EdgeData &fwd_edge_data1 = m_node_based_graph->GetEdgeData(forward_e1); const EdgeData &rev_edge_data1 = m_node_based_graph->GetEdgeData(reverse_e1); - if ((m_node_based_graph->FindEdge(u, w) != m_node_based_graph->EndEdges(u)) || - (m_node_based_graph->FindEdge(w, u) != m_node_based_graph->EndEdges(w))) + if ((m_node_based_graph->FindEdge(node_u, node_w) != m_node_based_graph->EndEdges(node_u)) || + (m_node_based_graph->FindEdge(node_w, node_u) != m_node_based_graph->EndEdges(node_w))) { continue; } @@ -378,7 +366,7 @@ void EdgeBasedGraphFactory::CompressGeometry() BOOST_ASSERT(0 != forward_weight2); const bool add_traffic_signal_penalty = - (m_traffic_lights.find(v) != m_traffic_lights.end()); + (m_traffic_lights.find(node_v) != m_traffic_lights.end()); // add weight of e2's to e1 m_node_based_graph->GetEdgeData(forward_e1).distance += fwd_edge_data2.distance; @@ -386,43 +374,43 @@ void EdgeBasedGraphFactory::CompressGeometry() if (add_traffic_signal_penalty) { m_node_based_graph->GetEdgeData(forward_e1).distance += - speed_profile.trafficSignalPenalty; + speed_profile.traffic_signal_penalty; m_node_based_graph->GetEdgeData(reverse_e1).distance += - speed_profile.trafficSignalPenalty; + speed_profile.traffic_signal_penalty; } // extend e1's to targets of e2's - m_node_based_graph->SetTarget(forward_e1, w); - m_node_based_graph->SetTarget(reverse_e1, u); + m_node_based_graph->SetTarget(forward_e1, node_w); + m_node_based_graph->SetTarget(reverse_e1, node_u); // remove e2's (if bidir, otherwise only one) - m_node_based_graph->DeleteEdge(v, forward_e2); - m_node_based_graph->DeleteEdge(v, reverse_e2); + m_node_based_graph->DeleteEdge(node_v, forward_e2); + m_node_based_graph->DeleteEdge(node_v, reverse_e2); // update any involved turn restrictions - m_restriction_map->FixupStartingTurnRestriction(u, v, w); - m_restriction_map->FixupArrivingTurnRestriction(u, v, w); + m_restriction_map->FixupStartingTurnRestriction(node_u, node_v, node_w); + m_restriction_map->FixupArrivingTurnRestriction(node_u, node_v, node_w); - m_restriction_map->FixupStartingTurnRestriction(w, v, u); - m_restriction_map->FixupArrivingTurnRestriction(w, v, u); + m_restriction_map->FixupStartingTurnRestriction(node_w, node_v, node_u); + m_restriction_map->FixupArrivingTurnRestriction(node_w, node_v, node_u); // store compressed geometry in container m_geometry_compressor.CompressEdge( forward_e1, forward_e2, - v, - w, + node_v, + node_w, forward_weight1 + - (add_traffic_signal_penalty ? speed_profile.trafficSignalPenalty : 0), + (add_traffic_signal_penalty ? speed_profile.traffic_signal_penalty : 0), forward_weight2); m_geometry_compressor.CompressEdge( reverse_e1, reverse_e2, - v, - u, + node_v, + node_u, reverse_weight1, reverse_weight2 + - (add_traffic_signal_penalty ? speed_profile.trafficSignalPenalty : 0)); + (add_traffic_signal_penalty ? speed_profile.traffic_signal_penalty : 0)); ++removed_node_count; BOOST_ASSERT(m_node_based_graph->GetEdgeData(forward_e1).nameID == @@ -451,7 +439,7 @@ void EdgeBasedGraphFactory::CompressGeometry() } /** - * Writes the id of the edge in the edge expanded graph (into the egde in the node based graph) + * Writes the id of the edge in the edge expanded graph (into the edge in the node based graph) */ void EdgeBasedGraphFactory::RenumberEdges() { @@ -478,104 +466,6 @@ void EdgeBasedGraphFactory::RenumberEdges() m_number_of_edge_based_nodes = numbered_edges_count; } -void EdgeBasedGraphFactory::GenerateEdgeBasedNodeData() -{ - BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() == m_node_based_graph_origin->GetNumberOfNodes()); - - m_edge_based_node_data.resize(m_number_of_edge_based_nodes); - std::vector found; - found.resize(m_number_of_edge_based_nodes, false); - - for (NodeID current_node = 0; current_node < m_node_based_graph->GetNumberOfNodes(); - ++current_node) - { - for (EdgeID current_edge : m_node_based_graph->GetAdjacentEdgeRange(current_node)) - { - EdgeData & edge_data = m_node_based_graph->GetEdgeData(current_edge); - if (!edge_data.forward) - { - continue; - } - - NodeID target = m_node_based_graph->GetTarget(current_edge); - - osrm::NodeData data; - if (m_geometry_compressor.HasEntryForID(current_edge)) - { - const std::vector & via_nodes = m_geometry_compressor.GetBucketReference(current_edge); - assert(via_nodes.size() > 0); - std::vector< std::pair< NodeID, FixedPointCoordinate > > nodes; - if (via_nodes.front().first != current_node) - nodes.emplace_back(current_node, FixedPointCoordinate(m_node_info_list[current_node].lat, m_node_info_list[current_node].lon)); - for (auto n : via_nodes) - nodes.emplace_back(n.first, FixedPointCoordinate(m_node_info_list[n.first].lat, m_node_info_list[n.first].lon)); - if (via_nodes.back().first != target) - nodes.emplace_back(target, FixedPointCoordinate(m_node_info_list[target].lat, m_node_info_list[target].lon)); - - for (uint32_t i = 1; i < nodes.size(); ++i) - { - auto n1 = nodes[i - 1]; - auto n2 = nodes[i]; - - if (n1.first == n2.first) - { - SimpleLogger().Write() << "Error: Equal values " << n1.first << " and " << n2.first; - SimpleLogger().Write() << "i: "<< i << " nodes: " << nodes.size(); - throw std::exception(); - } - - EdgeID e = m_node_based_graph_origin->FindEdge(n1.first, n2.first); - if (e == SPECIAL_EDGEID) - { - SimpleLogger().Write() << "Error: Can't find edge between nodes " << n1.first << " and " << n2.first; - continue; - } - - EdgeData &ed = m_node_based_graph_origin->GetEdgeData(e); - - data.AddSegment(ed.way_id, - m_node_info_list[n1.first].lat / COORDINATE_PRECISION, - m_node_info_list[n1.first].lon / COORDINATE_PRECISION, - m_node_info_list[n2.first].lat / COORDINATE_PRECISION, - m_node_info_list[n2.first].lon / COORDINATE_PRECISION); - } - - } else - { - data.AddSegment(edge_data.way_id, - m_node_info_list[current_node].lat / COORDINATE_PRECISION, - m_node_info_list[current_node].lon / COORDINATE_PRECISION, - m_node_info_list[target].lat / COORDINATE_PRECISION, - m_node_info_list[target].lon / COORDINATE_PRECISION); - } - - if (found[edge_data.edgeBasedNodeID]) - { - if (m_edge_based_node_data[edge_data.edgeBasedNodeID] != data) - { - std::cout << "Error!" << std::endl; - throw std::exception(); - } - } else - { - found[edge_data.edgeBasedNodeID] = true; - m_edge_based_node_data[edge_data.edgeBasedNodeID] = data; - } - } - } - - for (auto v : found) - { - if (!v) - { - std::cout << "Error2" << std::endl; - throw std::exception(); - } - } - - SimpleLogger().Write() << "Edge based node data count: " << m_edge_based_node_data.size(); -} - /** * Creates the nodes in the edge expanded graph from edges in the node-based graph. */ @@ -593,21 +483,17 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() << " many components"; SimpleLogger().Write() << "generating edge-expanded nodes"; - Percent p(m_node_based_graph->GetNumberOfNodes()); + Percent progress(m_node_based_graph->GetNumberOfNodes()); // loop over all edges and generate new set of nodes for (NodeID u = 0, end = m_node_based_graph->GetNumberOfNodes(); u < end; ++u) { BOOST_ASSERT(u != SPECIAL_NODEID); BOOST_ASSERT(u < m_node_based_graph->GetNumberOfNodes()); - p.printIncrement(); + progress.printStatus(u); for (EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u)) { const EdgeData &edge_data = m_node_based_graph->GetEdgeData(e1); - // if (edge_data.edgeBasedNodeID == SPECIAL_NODEID) - // { - // continue; - // } BOOST_ASSERT(e1 != SPECIAL_EDGEID); const NodeID v = m_node_based_graph->GetTarget(e1); @@ -619,7 +505,6 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() } BOOST_ASSERT(u < v); - BOOST_ASSERT(edge_data.type != SHRT_MAX); // Note: edges that end on barrier nodes or on a turn restriction // may actually be in two distinct components. We choose the smallest @@ -670,11 +555,12 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg unsigned skipped_barrier_turns_counter = 0; unsigned compressed = 0; - Percent p(m_node_based_graph->GetNumberOfNodes()); + Percent progress(m_node_based_graph->GetNumberOfNodes()); for (NodeID u = 0, end = m_node_based_graph->GetNumberOfNodes(); u < end; ++u) { - for (EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u)) + progress.printStatus(u); + for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u)) { if (!m_node_based_graph->GetEdgeData(e1).forward) { @@ -739,29 +625,31 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg BOOST_ASSERT(edge_data1.forward); BOOST_ASSERT(edge_data2.forward); - if (edge_data1.way_id == 244396524) - { - SimpleLogger().Write() << " - Id: " << edge_data1.way_id << " n1: " << u << " n2: " << v; - } - - if (edge_data2.way_id == 244396524) - { - SimpleLogger().Write() << " - Id: " << edge_data2.way_id << " n1: " << v << " n2: " << w; - } - // the following is the core of the loop. unsigned distance = edge_data1.distance; if (m_traffic_lights.find(v) != m_traffic_lights.end()) { - distance += speed_profile.trafficSignalPenalty; + distance += speed_profile.traffic_signal_penalty; } - const double angle = GetAngleBetweenThreeFixedPointCoordinates( - m_node_info_list[u], m_node_info_list[v], m_node_info_list[w]); - const int turn_penalty = GetTurnPenalty(angle, lua_state); - TurnInstruction turn_instruction = AnalyzeTurn(u, v, w, angle); + + // unpack last node of first segment if packed + const auto first_coordinate = m_node_info_list[(m_geometry_compressor.HasEntryForID(e1) ? + m_geometry_compressor.GetLastNodeIDOfBucket(e1) : + u)]; + + // unpack first node of second segment if packed + const auto third_coordinate = m_node_info_list[(m_geometry_compressor.HasEntryForID(e2) ? + m_geometry_compressor.GetFirstNodeIDOfBucket(e2) : + w)]; + + const double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( + first_coordinate, m_node_info_list[v], third_coordinate); + + const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); + TurnInstruction turn_instruction = AnalyzeTurn(u, v, w, turn_angle); if (turn_instruction == TurnInstruction::UTurn) { - distance += speed_profile.uTurnPenalty; + distance += speed_profile.u_turn_penalty; } distance += turn_penalty; @@ -776,7 +664,8 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg (edge_is_compressed ? m_geometry_compressor.GetPositionForID(e1) : v), edge_data1.nameID, turn_instruction, - edge_is_compressed); + edge_is_compressed, + edge_data2.travel_mode); ++original_edges_counter; @@ -796,7 +685,6 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg false)); } } - p.printIncrement(); } FlushVectorToStream(edge_data_file, original_edge_data_vector); @@ -830,37 +718,28 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co return 0; } -TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u, - const NodeID v, - const NodeID w, - double angle) +TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, + const NodeID node_v, + const NodeID node_w, + const double angle) const { - if (u == w) + if (node_u == node_w) { return TurnInstruction::UTurn; } - const EdgeID edge1 = m_node_based_graph->FindEdge(u, v); - const EdgeID edge2 = m_node_based_graph->FindEdge(v, w); + const EdgeID edge1 = m_node_based_graph->FindEdge(node_u, node_v); + const EdgeID edge2 = m_node_based_graph->FindEdge(node_v, node_w); const EdgeData &data1 = m_node_based_graph->GetEdgeData(edge1); const EdgeData &data2 = m_node_based_graph->GetEdgeData(edge2); - if (!data1.contraFlow && data2.contraFlow) - { - return TurnInstruction::EnterAgainstAllowedDirection; - } - if (data1.contraFlow && !data2.contraFlow) - { - return TurnInstruction::LeaveAgainstAllowedDirection; - } - // roundabouts need to be handled explicitely if (data1.roundabout && data2.roundabout) { // Is a turn possible? If yes, we stay on the roundabout! - if (1 == m_node_based_graph->GetDirectedOutDegree(v)) + if (1 == m_node_based_graph->GetDirectedOutDegree(node_v)) { // No turn possible. return TurnInstruction::NoTurn; @@ -888,11 +767,7 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u, { // TODO: Here we should also do a small graph exploration to check for // more complex situations - if (0 != data1.nameID) - { - return TurnInstruction::NoTurn; - } - else if (m_node_based_graph->GetOutDegree(v) <= 2) + if (0 != data1.nameID || m_node_based_graph->GetOutDegree(node_v) <= 2) { return TurnInstruction::NoTurn; } diff --git a/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.h b/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.h index 1a06a15c7d..be35a199c4 100644 --- a/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.h +++ b/3party/osrm/osrm-backend/Contractor/EdgeBasedGraphFactory.h @@ -38,7 +38,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/TurnInstructions.h" #include "../DataStructures/NodeBasedGraph.h" #include "../DataStructures/RestrictionMap.h" -#include "../DataStructures/EdgeBasedNodeData.h" #include "GeometryCompressor.h" #include @@ -50,7 +49,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include - struct lua_State; class EdgeBasedGraphFactory @@ -62,7 +60,6 @@ class EdgeBasedGraphFactory struct SpeedProfileProperties; explicit EdgeBasedGraphFactory(const std::shared_ptr &node_based_graph, - const std::shared_ptr &node_based_graph_origin, std::unique_ptr restricion_map, std::vector &barrier_node_list, std::vector &traffic_light_node_list, @@ -77,9 +74,7 @@ class EdgeBasedGraphFactory void GetEdgeBasedNodes(std::vector &nodes); - void GetEdgeBasedNodeData(osrm::NodeDataVectorT &data); - - TurnInstruction AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, double angle) const; + TurnInstruction AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, const double angle) const; int GetTurnPenalty(double angle, lua_State *lua_state) const; @@ -88,17 +83,17 @@ class EdgeBasedGraphFactory struct SpeedProfileProperties { SpeedProfileProperties() - : trafficSignalPenalty(0), uTurnPenalty(0), has_turn_penalty_function(false) + : traffic_signal_penalty(0), u_turn_penalty(0), has_turn_penalty_function(false) { } - int trafficSignalPenalty; - int uTurnPenalty; + int traffic_signal_penalty; + int u_turn_penalty; bool has_turn_penalty_function; } speed_profile; private: - typedef NodeBasedDynamicGraph::EdgeData EdgeData; + using EdgeData = NodeBasedDynamicGraph::EdgeData; unsigned m_number_of_edge_based_nodes; @@ -107,18 +102,15 @@ class EdgeBasedGraphFactory DeallocatingVector m_edge_based_edge_list; std::shared_ptr m_node_based_graph; - std::shared_ptr m_node_based_graph_origin; std::unordered_set m_barrier_nodes; std::unordered_set m_traffic_lights; std::unique_ptr m_restriction_map; - std::vector m_edge_based_node_data; GeometryCompressor m_geometry_compressor; void CompressGeometry(); void RenumberEdges(); - void GenerateEdgeBasedNodeData(); void GenerateEdgeExpandedNodes(); void GenerateEdgeExpandedEdges(const std::string &original_edge_data_filename, lua_State *lua_state); @@ -128,7 +120,7 @@ class EdgeBasedGraphFactory void FlushVectorToStream(std::ofstream &edge_data_file, std::vector &original_edge_data_vector) const; - unsigned max_id; + NodeID max_id; }; #endif /* EDGEBASEDGRAPHFACTORY_H_ */ diff --git a/3party/osrm/osrm-backend/Contractor/GeometryCompressor.cpp b/3party/osrm/osrm-backend/Contractor/GeometryCompressor.cpp index 7c5191002e..be4dc7afd5 100644 --- a/3party/osrm/osrm-backend/Contractor/GeometryCompressor.cpp +++ b/3party/osrm/osrm-backend/Contractor/GeometryCompressor.cpp @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GeometryCompressor.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include #include @@ -225,3 +225,16 @@ GeometryCompressor::GetBucketReference(const EdgeID edge_id) const const unsigned index = m_edge_id_to_list_index_map.at(edge_id); return m_compressed_geometries.at(index); } + + NodeID GeometryCompressor::GetFirstNodeIDOfBucket(const EdgeID edge_id) const + { + const auto &bucket = GetBucketReference(edge_id); + BOOST_ASSERT(bucket.size() >= 2); + return bucket[1].first; + } + NodeID GeometryCompressor::GetLastNodeIDOfBucket(const EdgeID edge_id) const + { + const auto &bucket = GetBucketReference(edge_id); + BOOST_ASSERT(bucket.size() >= 2); + return bucket[bucket.size()-2].first; + } diff --git a/3party/osrm/osrm-backend/Contractor/GeometryCompressor.h b/3party/osrm/osrm-backend/Contractor/GeometryCompressor.h index 7c4fba45cd..f0af3710c0 100644 --- a/3party/osrm/osrm-backend/Contractor/GeometryCompressor.h +++ b/3party/osrm/osrm-backend/Contractor/GeometryCompressor.h @@ -25,6 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#ifndef GEOMETRY_COMPRESSOR_H +#define GEOMETRY_COMPRESSOR_H + #include "../typedefs.h" #include @@ -32,13 +35,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#ifndef GEOMETRY_COMPRESSOR_H -#define GEOMETRY_COMPRESSOR_H - class GeometryCompressor { public: - typedef std::pair CompressedNode; + using CompressedNode = std::pair; GeometryCompressor(); void CompressEdge(const EdgeID surviving_edge_id, @@ -54,6 +54,8 @@ class GeometryCompressor unsigned GetPositionForID(const EdgeID edge_id) const; const std::vector & GetBucketReference(const EdgeID edge_id) const; + NodeID GetFirstNodeIDOfBucket(const EdgeID edge_id) const; + NodeID GetLastNodeIDOfBucket(const EdgeID edge_id) const; private: void IncreaseFreeList(); diff --git a/3party/osrm/osrm-backend/Contractor/Prepare.cpp b/3party/osrm/osrm-backend/Contractor/Prepare.cpp index 28f1e84d60..6dae9fa370 100644 --- a/3party/osrm/osrm-backend/Contractor/Prepare.cpp +++ b/3party/osrm/osrm-backend/Contractor/Prepare.cpp @@ -38,8 +38,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../Util/GitDescription.h" #include "../Util/LuaUtil.h" +#include "../Util/make_unique.hpp" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/StringUtil.h" #include "../Util/TimingUtil.h" #include "../typedefs.h" @@ -108,7 +109,7 @@ int Prepare::Process(int argc, char *argv[]) FingerPrint fingerprint_orig; CheckRestrictionsFile(fingerprint_orig); - boost::filesystem::ifstream in(input_path, std::ios::in | std::ios::binary); + boost::filesystem::ifstream input_stream(input_path, std::ios::in | std::ios::binary); node_filename = input_path.string() + ".nodes"; edge_out = input_path.string() + ".edges"; @@ -116,7 +117,6 @@ int Prepare::Process(int argc, char *argv[]) graph_out = input_path.string() + ".hsgr"; rtree_nodes_path = input_path.string() + ".ramIndex"; rtree_leafs_path = input_path.string() + ".fileIndex"; - node_data_filename = input_path.string() + ".nodeData"; /*** Setup Scripting Environment ***/ // Create a new lua state @@ -135,17 +135,17 @@ int Prepare::Process(int argc, char *argv[]) #ifdef WIN32 #pragma message("Memory consumption on Windows can be higher due to different bit packing") #else - static_assert(sizeof(ImportEdge) == 24, + static_assert(sizeof(ImportEdge) == 20, "changing ImportEdge type has influence on memory consumption!"); #endif NodeID number_of_node_based_nodes = - readBinaryOSRMGraphFromStream(in, + readBinaryOSRMGraphFromStream(input_stream, edge_list, barrier_node_list, traffic_light_list, &internal_to_external_node_map, restriction_list); - in.close(); + input_stream.close(); if (edge_list.empty()) { @@ -162,24 +162,31 @@ int Prepare::Process(int argc, char *argv[]) DeallocatingVector edge_based_edge_list; // init node_based_edge_list, edge_based_edge_list by edgeList - BuildEdgeExpandedGraph(lua_state, - number_of_node_based_nodes, - number_of_edge_based_nodes, - node_based_edge_list, - edge_based_edge_list, - speed_profile); + number_of_edge_based_nodes = BuildEdgeExpandedGraph(lua_state, + number_of_node_based_nodes, + node_based_edge_list, + edge_based_edge_list, + speed_profile); lua_close(lua_state); TIMER_STOP(expansion); BuildRTree(node_based_edge_list); - IteratorbasedCRC32> crc32; - const unsigned node_based_edge_list_CRC32 = - crc32(node_based_edge_list.begin(), node_based_edge_list.end()); + RangebasedCRC32 crc32; + if (crc32.using_hardware()) + { + SimpleLogger().Write() << "using hardware based CRC32 computation"; + } + else + { + SimpleLogger().Write() << "using software based CRC32 computation"; + } + + const unsigned crc32_value = crc32(node_based_edge_list); node_based_edge_list.clear(); node_based_edge_list.shrink_to_fit(); - SimpleLogger().Write() << "CRC32: " << node_based_edge_list_CRC32; + SimpleLogger().Write() << "CRC32: " << crc32_value; WriteNodeMapping(); @@ -188,7 +195,8 @@ int Prepare::Process(int argc, char *argv[]) */ SimpleLogger().Write() << "initializing contractor"; - Contractor *contractor = new Contractor(number_of_edge_based_nodes, edge_based_edge_list); + auto contractor = + osrm::make_unique(number_of_edge_based_nodes, edge_based_edge_list); TIMER_START(contraction); contractor->Run(); @@ -198,31 +206,34 @@ int Prepare::Process(int argc, char *argv[]) DeallocatingVector contracted_edge_list; contractor->GetEdges(contracted_edge_list); - delete contractor; + contractor.reset(); /*** * 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()); - unsigned max_used_node_id = 0; - unsigned contracted_edge_count = contracted_edge_list.size(); + const unsigned contracted_edge_count = contracted_edge_list.size(); SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count << " edges"; boost::filesystem::ofstream hsgr_output_stream(graph_out, std::ios::binary); hsgr_output_stream.write((char *)&fingerprint_orig, sizeof(FingerPrint)); - for (const QueryEdge &edge : contracted_edge_list) + const unsigned max_used_node_id = 1 + [&contracted_edge_list] { - BOOST_ASSERT(UINT_MAX != edge.source); - BOOST_ASSERT(UINT_MAX != edge.target); + unsigned tmp_max = 0; + for (const QueryEdge &edge : contracted_edge_list) + { + BOOST_ASSERT(SPECIAL_NODEID != edge.source); + BOOST_ASSERT(SPECIAL_NODEID != edge.target); + tmp_max = std::max(tmp_max, edge.source); + tmp_max = std::max(tmp_max, edge.target); + } + return tmp_max; + }(); - max_used_node_id = std::max(max_used_node_id, edge.source); - max_used_node_id = std::max(max_used_node_id, edge.target); - } SimpleLogger().Write(logDEBUG) << "input graph has " << number_of_edge_based_nodes << " nodes"; SimpleLogger().Write(logDEBUG) << "contracted graph has " << max_used_node_id << " nodes"; - max_used_node_id += 1; std::vector::NodeArrayEntry> node_array; node_array.resize(number_of_edge_based_nodes + 1); @@ -254,7 +265,7 @@ int Prepare::Process(int argc, char *argv[]) const unsigned node_array_size = node_array.size(); // serialize crc32, aka checksum - hsgr_output_stream.write((char *)&node_based_edge_list_CRC32, sizeof(unsigned)); + hsgr_output_stream.write((char *)&crc32_value, sizeof(unsigned)); // serialize number of nodes hsgr_output_stream.write((char *)&node_array_size, sizeof(unsigned)); // serialize number of edges @@ -462,9 +473,9 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state, std::cerr << lua_tostring(lua_state, -1) << " occured in scripting block" << std::endl; return false; } - speed_profile.trafficSignalPenalty = 10 * lua_tointeger(lua_state, -1); + speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); SimpleLogger().Write(logDEBUG) - << "traffic_signal_penalty: " << speed_profile.trafficSignalPenalty; + << "traffic_signal_penalty: " << speed_profile.traffic_signal_penalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { @@ -472,7 +483,7 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state, return false; } - speed_profile.uTurnPenalty = 10 * lua_tointeger(lua_state, -1); + speed_profile.u_turn_penalty = 10 * lua_tointeger(lua_state, -1); speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function"); return true; @@ -481,30 +492,25 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state, /** \brief Building an edge-expanded graph from node-based input and turn restrictions */ -void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state, - NodeID number_of_node_based_nodes, - unsigned &number_of_edge_based_nodes, - std::vector &node_based_edge_list, - DeallocatingVector &edge_based_edge_list, - EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile) +std::size_t +Prepare::BuildEdgeExpandedGraph(lua_State *lua_state, + NodeID number_of_node_based_nodes, + std::vector &node_based_edge_list, + DeallocatingVector &edge_based_edge_list, + EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile) { SimpleLogger().Write() << "Generating edge-expanded graph representation"; std::shared_ptr node_based_graph = NodeBasedDynamicGraphFromImportEdges(number_of_node_based_nodes, edge_list); std::unique_ptr restriction_map = std::unique_ptr(new RestrictionMap(node_based_graph, restriction_list)); - - std::shared_ptr node_based_graph_origin = - NodeBasedDynamicGraphFromImportEdges(number_of_node_based_nodes, edge_list); - - EdgeBasedGraphFactory *edge_based_graph_factory = - new EdgeBasedGraphFactory(node_based_graph, - node_based_graph_origin, - std::move(restriction_map), - barrier_node_list, - traffic_light_list, - internal_to_external_node_map, - speed_profile); + std::shared_ptr edge_based_graph_factory = + std::make_shared(node_based_graph, + std::move(restriction_map), + barrier_node_list, + traffic_light_list, + internal_to_external_node_map, + speed_profile); edge_list.clear(); edge_list.shrink_to_fit(); @@ -517,7 +523,8 @@ void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state, traffic_light_list.clear(); traffic_light_list.shrink_to_fit(); - number_of_edge_based_nodes = edge_based_graph_factory->GetNumberOfEdgeBasedNodes(); + const std::size_t number_of_edge_based_nodes = + edge_based_graph_factory->GetNumberOfEdgeBasedNodes(); BOOST_ASSERT(number_of_edge_based_nodes != std::numeric_limits::max()); #ifndef WIN32 @@ -528,17 +535,10 @@ void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state, edge_based_graph_factory->GetEdgeBasedEdges(edge_based_edge_list); edge_based_graph_factory->GetEdgeBasedNodes(node_based_edge_list); - // serialize node data - osrm::NodeDataVectorT data; - edge_based_graph_factory->GetEdgeBasedNodeData(data); - - SimpleLogger().Write() << "Serialize node data"; - - osrm::SaveNodeDataToFile(node_data_filename, data); - - delete edge_based_graph_factory; - + edge_based_graph_factory.reset(); node_based_graph.reset(); + + return number_of_edge_based_nodes; } /** @@ -565,10 +565,10 @@ void Prepare::WriteNodeMapping() Saves info to files: '.ramIndex' and '.fileIndex'. */ -void Prepare::BuildRTree(std::vector &edge_based_node_list) +void Prepare::BuildRTree(std::vector &node_based_edge_list) { SimpleLogger().Write() << "building r-tree ..."; - StaticRTree(edge_based_node_list, + StaticRTree(node_based_edge_list, rtree_nodes_path.c_str(), rtree_leafs_path.c_str(), internal_to_external_node_map); diff --git a/3party/osrm/osrm-backend/Contractor/Prepare.h b/3party/osrm/osrm-backend/Contractor/Prepare.h index b7100b0c7e..cd8cbcadd7 100644 --- a/3party/osrm/osrm-backend/Contractor/Prepare.h +++ b/3party/osrm/osrm-backend/Contractor/Prepare.h @@ -18,9 +18,9 @@ class Prepare { public: - typedef QueryEdge::EdgeData EdgeData; - typedef DynamicGraph::InputEdge InputEdge; - typedef StaticGraph::InputEdge StaticEdge; + using EdgeData = QueryEdge::EdgeData; + using InputEdge = DynamicGraph::InputEdge; + using StaticEdge = StaticGraph::InputEdge; explicit Prepare(); Prepare(const Prepare &) = delete; @@ -33,12 +33,11 @@ class Prepare void CheckRestrictionsFile(FingerPrint &fingerprint_orig); bool SetupScriptingEnvironment(lua_State *myLuaState, EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile); - void BuildEdgeExpandedGraph(lua_State *myLuaState, - NodeID nodeBasedNodeNumber, - unsigned &nodeBasedEdgesNumber, - std::vector &nodeBasedEdgeList, - DeallocatingVector &edgeBasedEdgeList, - EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile); + std::size_t BuildEdgeExpandedGraph(lua_State *myLuaState, + NodeID nodeBasedNodeNumber, + std::vector &nodeBasedEdgeList, + DeallocatingVector &edgeBasedEdgeList, + EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile); void WriteNodeMapping(); void BuildRTree(std::vector &node_based_edge_list); @@ -63,7 +62,6 @@ class Prepare std::string graph_out; std::string rtree_nodes_path; std::string rtree_leafs_path; - std::string node_data_filename; }; #endif // PREPARE_H diff --git a/3party/osrm/osrm-backend/DataStructures/BinaryHeap.h b/3party/osrm/osrm-backend/DataStructures/BinaryHeap.h index 6903be1b3f..24a65cbf08 100644 --- a/3party/osrm/osrm-backend/DataStructures/BinaryHeap.h +++ b/3party/osrm/osrm-backend/DataStructures/BinaryHeap.h @@ -100,8 +100,8 @@ class BinaryHeap void operator=(const BinaryHeap &right); public: - typedef Weight WeightType; - typedef Data DataType; + using WeightType = Weight; + using DataType = Data; explicit BinaryHeap(size_t maxID) : node_index(maxID) { Clear(); } diff --git a/3party/osrm/osrm-backend/DataStructures/ConcurrentQueue.h b/3party/osrm/osrm-backend/DataStructures/ConcurrentQueue.h index 9d5b366f9c..a61503a6dd 100644 --- a/3party/osrm/osrm-backend/DataStructures/ConcurrentQueue.h +++ b/3party/osrm/osrm-backend/DataStructures/ConcurrentQueue.h @@ -28,8 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef CONCURRENT_QUEUE_H #define CONCURRENT_QUEUE_H -#include "../typedefs.h" - #include #include #include diff --git a/3party/osrm/osrm-backend/DataStructures/Coordinate.cpp b/3party/osrm/osrm-backend/DataStructures/Coordinate.cpp index 1960d68d68..3bd27df109 100644 --- a/3party/osrm/osrm-backend/DataStructures/Coordinate.cpp +++ b/3party/osrm/osrm-backend/DataStructures/Coordinate.cpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "../Util/MercatorUtil.h" #ifndef NDEBUG -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #endif #include "../Util/StringUtil.h" @@ -159,11 +159,11 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s const FixedPointCoordinate &point) { // initialize values - const float x_value = lat2y(point.lat / COORDINATE_PRECISION); + const float x_value = static_cast(lat2y(point.lat / COORDINATE_PRECISION)); const float y_value = point.lon / COORDINATE_PRECISION; - float a = lat2y(source_coordinate.lat / COORDINATE_PRECISION); + float a = static_cast(lat2y(source_coordinate.lat / COORDINATE_PRECISION)); float b = source_coordinate.lon / COORDINATE_PRECISION; - float c = lat2y(target_coordinate.lat / COORDINATE_PRECISION); + float c = static_cast(lat2y(target_coordinate.lat / COORDINATE_PRECISION)); float d = target_coordinate.lon / COORDINATE_PRECISION; float p, q; if (std::abs(a - c) > std::numeric_limits::epsilon()) @@ -184,7 +184,8 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s bool inverse_ratio = false; // straight line segment on equator - if (std::abs(c) < std::numeric_limits::epsilon() && std::abs(a) < std::numeric_limits::epsilon()) + if (std::abs(c) < std::numeric_limits::epsilon() && + std::abs(a) < std::numeric_limits::epsilon()) { ratio = (q - b) / (d - b); } @@ -228,7 +229,7 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s ratio = 1.0f - ratio; } - //compute the nearest location + // compute the nearest location FixedPointCoordinate nearest_location; BOOST_ASSERT(!std::isnan(ratio)); if (ratio <= 0.f) @@ -258,16 +259,16 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin BOOST_ASSERT(query_location.isValid()); // initialize values - const float x = lat2y(query_location.lat / COORDINATE_PRECISION); - const float y = query_location.lon / COORDINATE_PRECISION; - const float a = lat2y(segment_source.lat / COORDINATE_PRECISION); - const float b = segment_source.lon / COORDINATE_PRECISION; - const float c = lat2y(segment_target.lat / COORDINATE_PRECISION); - const float d = segment_target.lon / COORDINATE_PRECISION; - float p, q /*,mX*/, nY; - if (std::abs(a - c) > std::numeric_limits::epsilon()) + const double x = lat2y(query_location.lat / COORDINATE_PRECISION); + const double y = query_location.lon / COORDINATE_PRECISION; + const double a = lat2y(segment_source.lat / COORDINATE_PRECISION); + const double b = segment_source.lon / COORDINATE_PRECISION; + const double c = lat2y(segment_target.lat / COORDINATE_PRECISION); + const double d = segment_target.lon / COORDINATE_PRECISION; + double p, q /*,mX*/, nY; + if (std::abs(a - c) > std::numeric_limits::epsilon()) { - const float m = (d - b) / (c - a); // slope + const double m = (d - b) / (c - a); // slope // Projection of (x,y) on line joining (a,b) and (c,d) p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m); q = b + m * (p - a); @@ -293,11 +294,11 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin { ratio = (segment_target == query_location ? 1.f : 0.f); } - else if (std::abs(ratio) <= std::numeric_limits::epsilon()) + else if (std::abs(ratio) <= std::numeric_limits::epsilon()) { - ratio = 0.; + ratio = 0.f; } - else if (std::abs(ratio - 1.f) <= std::numeric_limits::epsilon()) + else if (std::abs(ratio - 1.f) <= std::numeric_limits::epsilon()) { ratio = 1.f; } @@ -308,7 +309,7 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin { nearest_location = segment_source; } - else if (ratio >= 1.) + else if (ratio >= 1.f) { nearest_location = segment_target; } @@ -366,7 +367,8 @@ void FixedPointCoordinate::Output(std::ostream &out) const float FixedPointCoordinate::GetBearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate) { - const float lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; + const float lon_diff = + second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; const float lon_delta = DegreeToRadian(lon_diff); const float lat1 = DegreeToRadian(first_coordinate.lat / COORDINATE_PRECISION); const float lat2 = DegreeToRadian(second_coordinate.lat / COORDINATE_PRECISION); @@ -408,9 +410,15 @@ float FixedPointCoordinate::GetBearing(const FixedPointCoordinate &other) const return result; } -float FixedPointCoordinate::DegreeToRadian(const float degree) { return degree * (static_cast(M_PI) / 180.f); } +float FixedPointCoordinate::DegreeToRadian(const float degree) +{ + return degree * (static_cast(M_PI) / 180.f); +} -float FixedPointCoordinate::RadianToDegree(const float radian) { return radian * (180.f * static_cast(M_1_PI)); } +float FixedPointCoordinate::RadianToDegree(const float radian) +{ + return radian * (180.f * static_cast(M_1_PI)); +} // This distance computation does integer arithmetic only and is a lot faster than // the other distance function which are numerically correct('ish). @@ -421,11 +429,11 @@ int FixedPointCoordinate::OrderedPerpendicularDistanceApproximation( const FixedPointCoordinate &segment_target) { // initialize values - const float x = lat2y(input_point.lat / COORDINATE_PRECISION); + const float x = static_cast(lat2y(input_point.lat / COORDINATE_PRECISION)); const float y = input_point.lon / COORDINATE_PRECISION; - const float a = lat2y(segment_source.lat / COORDINATE_PRECISION); + const float a = static_cast(lat2y(segment_source.lat / COORDINATE_PRECISION)); const float b = segment_source.lon / COORDINATE_PRECISION; - const float c = lat2y(segment_target.lat / COORDINATE_PRECISION); + const float c = static_cast(lat2y(segment_target.lat / COORDINATE_PRECISION)); const float d = segment_target.lon / COORDINATE_PRECISION; float p, q; diff --git a/3party/osrm/osrm-backend/DataStructures/DeallocatingVector.h b/3party/osrm/osrm-backend/DataStructures/DeallocatingVector.h index 3aec167d66..422dd5f19d 100644 --- a/3party/osrm/osrm-backend/DataStructures/DeallocatingVector.h +++ b/3party/osrm/osrm-backend/DataStructures/DeallocatingVector.h @@ -165,11 +165,11 @@ class DeallocatingVector std::vector bucket_list; public: - typedef DeallocatingVectorIterator iterator; - typedef DeallocatingVectorIterator const_iterator; + using iterator = DeallocatingVectorIterator; + using const_iterator = DeallocatingVectorIterator; // this forward-only iterator deallocates all buckets that have been visited - typedef DeallocatingVectorRemoveIterator deallocation_iterator; + using deallocation_iterator = DeallocatingVectorRemoveIterator; DeallocatingVector() : current_size(0) { bucket_list.emplace_back(new ElementT[ELEMENTS_PER_BLOCK]); } diff --git a/3party/osrm/osrm-backend/DataStructures/DynamicGraph.h b/3party/osrm/osrm-backend/DataStructures/DynamicGraph.h index 4fc345df04..81b1afe117 100644 --- a/3party/osrm/osrm-backend/DataStructures/DynamicGraph.h +++ b/3party/osrm/osrm-backend/DataStructures/DynamicGraph.h @@ -43,10 +43,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. template class DynamicGraph { public: - typedef EdgeDataT EdgeData; - typedef unsigned NodeIterator; - typedef unsigned EdgeIterator; - typedef osrm::range EdgeRange; + using EdgeData = EdgeDataT; + using NodeIterator = unsigned; + using EdgeIterator = unsigned; + using EdgeRange = osrm::range; class InputEdge { @@ -71,7 +71,7 @@ template class DynamicGraph }; // Constructs an empty graph with a given number of nodes. - explicit DynamicGraph(int32_t nodes) : number_of_nodes(nodes), number_of_edges(0) + explicit DynamicGraph(NodeIterator nodes) : number_of_nodes(nodes), number_of_edges(0) { node_list.reserve(number_of_nodes); node_list.resize(number_of_nodes); @@ -80,7 +80,7 @@ template class DynamicGraph edge_list.resize(number_of_nodes); } - template DynamicGraph(const int32_t nodes, const ContainerT &graph) + template DynamicGraph(const NodeIterator nodes, const ContainerT &graph) { number_of_nodes = nodes; number_of_edges = (EdgeIterator)graph.size(); diff --git a/3party/osrm/osrm-backend/DataStructures/EdgeBasedNode.h b/3party/osrm/osrm-backend/DataStructures/EdgeBasedNode.h index b0a5c7111e..e2ac9acab1 100644 --- a/3party/osrm/osrm-backend/DataStructures/EdgeBasedNode.h +++ b/3party/osrm/osrm-backend/DataStructures/EdgeBasedNode.h @@ -1,10 +1,10 @@ #ifndef EDGE_BASED_NODE_H #define EDGE_BASED_NODE_H -#include "../Util/SimpleLogger.h" +#include "../DataStructures/TravelMode.h" #include "../typedefs.h" -#include "../Include/osrm/Coordinate.h" +#include #include @@ -14,8 +14,6 @@ struct EdgeBasedNode { EdgeBasedNode() : - forward_way_id(-1), - reverse_way_id(-1), forward_edge_based_node_id(SPECIAL_NODEID), reverse_edge_based_node_id(SPECIAL_NODEID), u(SPECIAL_NODEID), @@ -27,12 +25,12 @@ struct EdgeBasedNode reverse_offset(0), packed_geometry_id(SPECIAL_EDGEID), fwd_segment_position( std::numeric_limits::max() ), - is_in_tiny_cc(false) + is_in_tiny_cc(false), + forward_travel_mode(TRAVEL_MODE_INACCESSIBLE), + backward_travel_mode(TRAVEL_MODE_INACCESSIBLE) { } explicit EdgeBasedNode( - unsigned forward_way_id, - unsigned reverse_way_id, NodeID forward_edge_based_node_id, NodeID reverse_edge_based_node_id, NodeID u, @@ -44,10 +42,10 @@ struct EdgeBasedNode int reverse_offset, unsigned packed_geometry_id, unsigned short fwd_segment_position, - bool belongs_to_tiny_component + bool belongs_to_tiny_component, + TravelMode forward_travel_mode, + TravelMode backward_travel_mode ) : - forward_way_id(forward_way_id), - reverse_way_id(reverse_way_id), forward_edge_based_node_id(forward_edge_based_node_id), reverse_edge_based_node_id(reverse_edge_based_node_id), u(u), @@ -59,7 +57,9 @@ struct EdgeBasedNode reverse_offset(reverse_offset), packed_geometry_id(packed_geometry_id), fwd_segment_position(fwd_segment_position), - is_in_tiny_cc(belongs_to_tiny_component) + is_in_tiny_cc(belongs_to_tiny_component), + forward_travel_mode(forward_travel_mode), + backward_travel_mode(backward_travel_mode) { BOOST_ASSERT((forward_edge_based_node_id != SPECIAL_NODEID) || (reverse_edge_based_node_id != SPECIAL_NODEID)); @@ -79,8 +79,6 @@ struct EdgeBasedNode return packed_geometry_id != SPECIAL_EDGEID; } - unsigned forward_way_id; - unsigned reverse_way_id; NodeID forward_edge_based_node_id; // needed for edge-expanded graph NodeID reverse_edge_based_node_id; // needed for edge-expanded graph NodeID u; // indices into the coordinates array @@ -93,6 +91,8 @@ struct EdgeBasedNode unsigned packed_geometry_id; // if set, then the edge represents a packed geometry unsigned short fwd_segment_position; // segment id in a compressed geometry bool is_in_tiny_cc; + TravelMode forward_travel_mode : 4; + TravelMode backward_travel_mode : 4; }; #endif //EDGE_BASED_NODE_H diff --git a/3party/osrm/osrm-backend/DataStructures/EdgeBasedNodeData.h b/3party/osrm/osrm-backend/DataStructures/EdgeBasedNodeData.h deleted file mode 100644 index dbcadfe01b..0000000000 --- a/3party/osrm/osrm-backend/DataStructures/EdgeBasedNodeData.h +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once - -#include -#include -#include - - -namespace osrm -{ - -struct NodeData -{ -#pragma pack (push, 1) - struct SegmentInfo - { - uint64_t wayId; - double lat1, lon1, lat2, lon2; - - SegmentInfo() - : wayId(-1), lat1(-10000), lon1(-10000), lat2(-10000), lon2(-10000) - { - } - - SegmentInfo(uint64_t wayId, double lat1, double lon1, double lat2, double lon2) - : wayId(wayId), lat1(lat1), lon1(lon1), lat2(lat2), lon2(lon2) - { - } - - bool operator != (SegmentInfo const & other) const - { - return wayId != other.wayId || lat1 != other.lat1 || lon1 != other.lon1 || - lat2 != other.lat2 || lon2 != other.lon2; - } - }; -#pragma pack (pop) - - typedef std::vector SegmentInfoVectorT; - SegmentInfoVectorT m_segments; - - NodeData() - { - } - - NodeData(SegmentInfoVectorT & vec) - { - m_segments.swap(vec); - } - - bool operator == (NodeData const & other) const - { - if (m_segments.size() != other.m_segments.size()) - return false; - - for (uint32_t i = 0; i < m_segments.size(); ++i) - if (m_segments[i] != other.m_segments[i]) - return false; - - return true; - } - - bool operator != (NodeData const & other) const - { - return !(*this == other); - } - - void AddSegment(uint64_t wayId, double lat1, double lon1, double lat2, double lon2) - { - m_segments.emplace_back(wayId, lat1, lon1, lat2, lon2); - } - - void SetSegments(SegmentInfoVectorT & segments) - { - m_segments.swap(segments); - } -}; - - -typedef std::vector NodeDataVectorT; - -inline bool SaveNodeDataToFile(std::string const & filename, NodeDataVectorT const & data) -{ - std::ofstream stream; - stream.open(filename); - if (!stream.is_open()) - return false; - - uint32_t count = data.size(); - stream.write((char*)&count, sizeof(count)); - for (auto d : data) - { - uint32_t pc = d.m_segments.size(); - stream.write((char*)&pc, sizeof(pc)); - stream.write((char*)d.m_segments.data(), sizeof(NodeData::SegmentInfo) * pc); - } - stream.close(); - return true; -} - -inline bool LoadNodeDataFromFile(std::string const & filename, NodeDataVectorT & data) -{ - std::ifstream stream; - stream.open(filename); - if (!stream.is_open()) - return false; - - uint32_t count = 0; - stream.read((char*)&count, sizeof(count)); - for (uint32_t i = 0; i < count; ++i) - { - uint32_t pc; - stream.read((char*)&pc, sizeof(pc)); - NodeData::SegmentInfoVectorT segments; - segments.resize(pc); - stream.read((char*)segments.data(), sizeof(NodeData::SegmentInfo) * pc); - - data.emplace_back(segments); - } - stream.close(); - - return true; -} - -} diff --git a/3party/osrm/osrm-backend/DataStructures/FixedPointNumber.h b/3party/osrm/osrm-backend/DataStructures/FixedPointNumber.h new file mode 100644 index 0000000000..77de365aa2 --- /dev/null +++ b/3party/osrm/osrm-backend/DataStructures/FixedPointNumber.h @@ -0,0 +1,216 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef OSRM_FIXED_POINT_NUMBER_H +#define OSRM_FIXED_POINT_NUMBER_H + +#include +#include + +#include +#include +#include +#include + +namespace osrm +{ + +// implements an binary based fixed point number type +template +class FixedPointNumber +{ + static_assert(FractionalBitSize > 0, "FractionalBitSize must be greater than 0"); + static_assert(FractionalBitSize <= 32, "FractionalBitSize must at most 32"); + + typename std::conditional::type m_fixed_point_state; + constexpr static const decltype(m_fixed_point_state) PRECISION = 1 << FractionalBitSize; + + // state signage encapsulates whether the state should either represent a + // signed or an unsigned floating point number + using state_signage = + typename std::conditional::type, + decltype(m_fixed_point_state)>::type; + + public: + FixedPointNumber() : m_fixed_point_state(0) {} + + // the type is either initialized with a floating point value or an + // integral state. Anything else will throw at compile-time. + template + constexpr FixedPointNumber(const T &&input) noexcept + : m_fixed_point_state(static_cast( + std::round(std::forward(input) * PRECISION))) + { + static_assert( + std::is_floating_point::value || std::is_integral::value, + "FixedPointNumber needs to be initialized with floating point or integral value"); + } + + // get max value + template ::value>::type * = nullptr> + constexpr static auto max() noexcept -> T + { + return static_cast(std::numeric_limits::max()) / PRECISION; + } + + // get min value + template ::value>::type * = nullptr> + constexpr static auto min() noexcept -> T + { + return static_cast(1) / PRECISION; + } + + // get lowest value + template ::value>::type * = nullptr> + constexpr static auto lowest() noexcept -> T + { + return static_cast(std::numeric_limits::min()) / PRECISION; + } + + // cast to floating point type T, return value + template ::value>::type * = nullptr> + explicit operator const T() const noexcept + { + // casts to external type (signed or unsigned) and then to float + return static_cast(static_cast(m_fixed_point_state)) / PRECISION; + } + + // warn about cast to integral type T, its disabled for good reason + template ::value>::type * = nullptr> + explicit operator T() const + { + static_assert(std::is_integral::value, + "casts to integral types have been disabled on purpose"); + } + + // compare, ie. sort fixed-point numbers + bool operator<(const FixedPointNumber &other) const noexcept + { + return m_fixed_point_state < other.m_fixed_point_state; + } + + // equality, ie. sort fixed-point numbers + bool operator==(const FixedPointNumber &other) const noexcept + { + return m_fixed_point_state == other.m_fixed_point_state; + } + + bool operator!=(const FixedPointNumber &other) const { return !(*this == other); } + bool operator>(const FixedPointNumber &other) const { return other < *this; } + bool operator<=(const FixedPointNumber &other) const { return !(other < *this); } + bool operator>=(const FixedPointNumber &other) const { return !(*this < other); } + + // arithmetic operators + FixedPointNumber operator+(const FixedPointNumber &other) const noexcept + { + FixedPointNumber tmp = *this; + tmp.m_fixed_point_state += other.m_fixed_point_state; + return tmp; + } + + FixedPointNumber &operator+=(const FixedPointNumber &other) noexcept + { + this->m_fixed_point_state += other.m_fixed_point_state; + return *this; + } + + FixedPointNumber operator-(const FixedPointNumber &other) const noexcept + { + FixedPointNumber tmp = *this; + tmp.m_fixed_point_state -= other.m_fixed_point_state; + return tmp; + } + + FixedPointNumber &operator-=(const FixedPointNumber &other) noexcept + { + this->m_fixed_point_state -= other.m_fixed_point_state; + return *this; + } + + FixedPointNumber operator*(const FixedPointNumber &other) const noexcept + { + int64_t temp = this->m_fixed_point_state; + temp *= other.m_fixed_point_state; + + // rounding! + if (!truncate_results) + { + temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1); + } + temp >>= FractionalBitSize; + FixedPointNumber tmp; + tmp.m_fixed_point_state = static_cast(temp); + return tmp; + } + + FixedPointNumber &operator*=(const FixedPointNumber &other) noexcept + { + int64_t temp = this->m_fixed_point_state; + temp *= other.m_fixed_point_state; + + // rounding! + if (!truncate_results) + { + temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1); + } + temp >>= FractionalBitSize; + this->m_fixed_point_state = static_cast(temp); + return *this; + } + + FixedPointNumber operator/(const FixedPointNumber &other) const noexcept + { + int64_t temp = this->m_fixed_point_state; + temp <<= FractionalBitSize; + temp /= static_cast(other.m_fixed_point_state); + FixedPointNumber tmp; + tmp.m_fixed_point_state = static_cast(temp); + return tmp; + } + + FixedPointNumber &operator/=(const FixedPointNumber &other) noexcept + { + int64_t temp = this->m_fixed_point_state; + temp <<= FractionalBitSize; + temp /= static_cast(other.m_fixed_point_state); + FixedPointNumber tmp; + this->m_fixed_point_state = static_cast(temp); + return *this; + } +}; + +static_assert(4 == sizeof(FixedPointNumber<1>), "FP19 has wrong size != 4"); +} +#endif // OSRM_FIXED_POINT_NUMBER_H diff --git a/3party/osrm/osrm-backend/DataStructures/HashTable.h b/3party/osrm/osrm-backend/DataStructures/HashTable.h index 199c6df86c..8ff4688363 100644 --- a/3party/osrm/osrm-backend/DataStructures/HashTable.h +++ b/3party/osrm/osrm-backend/DataStructures/HashTable.h @@ -34,7 +34,7 @@ template class HashTable { private: - typedef std::pair KeyValPair; + using KeyValPair = std::pair; std::vector table; public: diff --git a/3party/osrm/osrm-backend/DataStructures/ImportEdge.cpp b/3party/osrm/osrm-backend/DataStructures/ImportEdge.cpp index f0716bf7b5..b59d6149c6 100644 --- a/3party/osrm/osrm-backend/DataStructures/ImportEdge.cpp +++ b/3party/osrm/osrm-backend/DataStructures/ImportEdge.cpp @@ -46,24 +46,21 @@ bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const return source < other.source; } -NodeBasedEdge::NodeBasedEdge(unsigned way_id, - NodeID source, +NodeBasedEdge::NodeBasedEdge(NodeID source, NodeID target, NodeID name_id, EdgeWeight weight, bool forward, bool backward, - short type, bool roundabout, bool in_tiny_cc, bool access_restricted, - bool contra_flow, + TravelMode travel_mode, bool is_split) - : way_id(way_id), source(source), target(target), name_id(name_id), weight(weight), type(type), + : source(source), target(target), name_id(name_id), weight(weight), forward(forward), backward(backward), roundabout(roundabout), in_tiny_cc(in_tiny_cc), - access_restricted(access_restricted), contra_flow(contra_flow), is_split(is_split) + access_restricted(access_restricted), is_split(is_split), travel_mode(travel_mode) { - BOOST_ASSERT_MSG(type > 0, "negative edge type"); } bool EdgeBasedEdge::operator<(const EdgeBasedEdge &other) const diff --git a/3party/osrm/osrm-backend/DataStructures/ImportEdge.h b/3party/osrm/osrm-backend/DataStructures/ImportEdge.h index 1ebde38493..4ccbee6d91 100644 --- a/3party/osrm/osrm-backend/DataStructures/ImportEdge.h +++ b/3party/osrm/osrm-backend/DataStructures/ImportEdge.h @@ -28,39 +28,36 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef IMPORT_EDGE_H #define IMPORT_EDGE_H +#include "../DataStructures/TravelMode.h" #include "../typedefs.h" struct NodeBasedEdge { bool operator<(const NodeBasedEdge &e) const; - explicit NodeBasedEdge(unsigned way_id, - NodeID source, + explicit NodeBasedEdge(NodeID source, NodeID target, NodeID name_id, EdgeWeight weight, bool forward, bool backward, - short type, bool roundabout, bool in_tiny_cc, bool access_restricted, - bool contra_flow, + TravelMode travel_mode, bool is_split); - unsigned way_id; NodeID source; NodeID target; NodeID name_id; EdgeWeight weight; - short type; bool forward : 1; bool backward : 1; bool roundabout : 1; bool in_tiny_cc : 1; bool access_restricted : 1; - bool contra_flow : 1; bool is_split : 1; + TravelMode travel_mode : 4; NodeBasedEdge() = delete; }; @@ -89,6 +86,6 @@ struct EdgeBasedEdge bool backward : 1; }; -typedef NodeBasedEdge ImportEdge; +using ImportEdge = NodeBasedEdge; #endif /* IMPORT_EDGE_H */ diff --git a/3party/osrm/osrm-backend/DataStructures/JSONContainer.h b/3party/osrm/osrm-backend/DataStructures/JSONContainer.h index 47dc34b279..350441d12b 100644 --- a/3party/osrm/osrm-backend/DataStructures/JSONContainer.h +++ b/3party/osrm/osrm-backend/DataStructures/JSONContainer.h @@ -25,14 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -// based on https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp +// based on +// https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp #ifndef JSON_CONTAINER_H #define JSON_CONTAINER_H -#include "../Util/StringUtil.h" - -#include +#include "../ThirdParty/variant/variant.hpp" +#include "../Util/cast.hpp" #include #include @@ -42,21 +42,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace JSON { -struct String; -struct Number; struct Object; struct Array; -struct True; -struct False; -struct Null; - -typedef boost::variant, - boost::recursive_wrapper, - boost::recursive_wrapper, - boost::recursive_wrapper, - boost::recursive_wrapper, - boost::recursive_wrapper, - boost::recursive_wrapper > Value; struct String { @@ -73,16 +60,6 @@ struct Number double value; }; -struct Object -{ - std::unordered_map values; -}; - -struct Array -{ - std::vector values; -}; - struct True { }; @@ -95,9 +72,27 @@ struct Null { }; -struct Renderer : boost::static_visitor<> +using Value = mapbox::util::variant, + mapbox::util::recursive_wrapper, + True, + False, + Null>; + +struct Object { - Renderer(std::ostream &_out) : out(_out) {} + std::unordered_map values; +}; + +struct Array +{ + std::vector values; +}; + +struct Renderer : mapbox::util::static_visitor<> +{ + explicit Renderer(std::ostream &_out) : out(_out) {} void operator()(const String &string) const { out << "\"" << string.value << "\""; } @@ -114,7 +109,7 @@ struct Renderer : boost::static_visitor<> while (iterator != object.values.end()) { out << "\"" << (*iterator).first << "\":"; - boost::apply_visitor(Renderer(out), (*iterator).second); + mapbox::util::apply_visitor(Renderer(out), (*iterator).second); if (++iterator != object.values.end()) { out << ","; @@ -130,7 +125,7 @@ struct Renderer : boost::static_visitor<> iterator = array.values.begin(); while (iterator != array.values.end()) { - boost::apply_visitor(Renderer(out), *iterator); + mapbox::util::apply_visitor(Renderer(out), *iterator); if (++iterator != array.values.end()) { out << ","; @@ -149,11 +144,12 @@ struct Renderer : boost::static_visitor<> std::ostream &out; }; -struct ArrayRenderer : boost::static_visitor<> +struct ArrayRenderer : mapbox::util::static_visitor<> { - ArrayRenderer(std::vector &_out) : out(_out) {} + explicit ArrayRenderer(std::vector &_out) : out(_out) {} - void operator()(const String &string) const { + void operator()(const String &string) const + { out.push_back('\"'); out.insert(out.end(), string.value.begin(), string.value.end()); out.push_back('\"'); @@ -161,7 +157,7 @@ struct ArrayRenderer : boost::static_visitor<> void operator()(const Number &number) const { - const std::string number_string = FixedDoubleToString(number.value); + const std::string number_string = cast::double_fixed_to_string(number.value); out.insert(out.end(), number_string.begin(), number_string.end()); } @@ -176,7 +172,7 @@ struct ArrayRenderer : boost::static_visitor<> out.push_back('\"'); out.push_back(':'); - boost::apply_visitor(ArrayRenderer(out), (*iterator).second); + mapbox::util::apply_visitor(ArrayRenderer(out), (*iterator).second); if (++iterator != object.values.end()) { out.push_back(','); @@ -192,7 +188,7 @@ struct ArrayRenderer : boost::static_visitor<> iterator = array.values.begin(); while (iterator != array.values.end()) { - boost::apply_visitor(ArrayRenderer(out), *iterator); + mapbox::util::apply_visitor(ArrayRenderer(out), *iterator); if (++iterator != array.values.end()) { out.push_back(','); @@ -201,17 +197,20 @@ struct ArrayRenderer : boost::static_visitor<> out.push_back(']'); } - void operator()(const True &) const { + void operator()(const True &) const + { const std::string temp("true"); out.insert(out.end(), temp.begin(), temp.end()); } - void operator()(const False &) const { + void operator()(const False &) const + { const std::string temp("false"); out.insert(out.end(), temp.begin(), temp.end()); } - void operator()(const Null &) const { + void operator()(const Null &) const + { const std::string temp("null"); out.insert(out.end(), temp.begin(), temp.end()); } @@ -223,13 +222,13 @@ struct ArrayRenderer : boost::static_visitor<> inline void render(std::ostream &out, const Object &object) { Value value = object; - boost::apply_visitor(Renderer(out), value); + mapbox::util::apply_visitor(Renderer(out), value); } inline void render(std::vector &out, const Object &object) { Value value = object; - boost::apply_visitor(ArrayRenderer(out), value); + mapbox::util::apply_visitor(ArrayRenderer(out), value); } } // namespace JSON diff --git a/3party/osrm/osrm-backend/DataStructures/NodeBasedGraph.h b/3party/osrm/osrm-backend/DataStructures/NodeBasedGraph.h index c9f34196a9..cceb4a0786 100644 --- a/3party/osrm/osrm-backend/DataStructures/NodeBasedGraph.h +++ b/3party/osrm/osrm-backend/DataStructures/NodeBasedGraph.h @@ -1,9 +1,9 @@ -#ifndef __NODE_BASED_GRAPH_H__ -#define __NODE_BASED_GRAPH_H__ +#ifndef NODE_BASED_GRAPH_H_ +#define NODE_BASED_GRAPH_H_ #include "DynamicGraph.h" #include "ImportEdge.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include @@ -12,25 +12,23 @@ struct NodeBasedEdgeData { NodeBasedEdgeData() - : way_id(-1), distance(INVALID_EDGE_WEIGHT), edgeBasedNodeID(SPECIAL_NODEID), - nameID(std::numeric_limits::max()), type(std::numeric_limits::max()), + : distance(INVALID_EDGE_WEIGHT), edgeBasedNodeID(SPECIAL_NODEID), + nameID(std::numeric_limits::max()), isAccessRestricted(false), shortcut(false), forward(false), backward(false), - roundabout(false), ignore_in_grid(false), contraFlow(false) + roundabout(false), ignore_in_grid(false), travel_mode(TRAVEL_MODE_INACCESSIBLE) { } - unsigned way_id; int distance; unsigned edgeBasedNodeID; unsigned nameID; - short type; bool isAccessRestricted : 1; bool shortcut : 1; bool forward : 1; bool backward : 1; bool roundabout : 1; bool ignore_in_grid : 1; - bool contraFlow : 1; + TravelMode travel_mode : 4; void SwapDirectionFlags() { @@ -43,7 +41,7 @@ struct NodeBasedEdgeData { return (forward == other.forward) && (backward == other.backward) && (nameID == other.nameID) && (ignore_in_grid == other.ignore_in_grid) && - (contraFlow == other.contraFlow); + (travel_mode == other.travel_mode); } }; @@ -53,14 +51,14 @@ struct SimpleEdgeData EdgeWeight capacity; }; -typedef DynamicGraph NodeBasedDynamicGraph; -typedef DynamicGraph SimpleNodeBasedDynamicGraph; +using NodeBasedDynamicGraph = DynamicGraph; +using SimpleNodeBasedDynamicGraph = DynamicGraph; // Factory method to create NodeBasedDynamicGraph from ImportEdges inline std::shared_ptr NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector &input_edge_list) { - static_assert(sizeof(NodeBasedEdgeData) == 20, "changing node based edge data size changes memory consumption"); + static_assert(sizeof(NodeBasedEdgeData) == 16, "changing node based edge data size changes memory consumption"); DeallocatingVector edges_list; NodeBasedDynamicGraph::InputEdge edge; @@ -81,8 +79,6 @@ NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector(number_of_nodes, edges_list); + auto graph = std::make_shared(static_cast(number_of_nodes), edges_list); return graph; } @@ -176,7 +172,7 @@ template inline std::shared_ptr SimpleNodeBasedDynamicGraphFromEdges(int number_of_nodes, std::vector &input_edge_list) { - static_assert(sizeof(NodeBasedEdgeData) == 20, "changing node based edge data size changes memory consumption"); + static_assert(sizeof(NodeBasedEdgeData) == 16, "changing node based edge data size changes memory consumption"); tbb::parallel_sort(input_edge_list.begin(), input_edge_list.end()); DeallocatingVector edges_list; @@ -245,4 +241,4 @@ SimpleNodeBasedDynamicGraphFromEdges(int number_of_nodes, std::vector @@ -38,16 +39,18 @@ struct OriginalEdgeData explicit OriginalEdgeData(NodeID via_node, unsigned name_id, TurnInstruction turn_instruction, - bool compressed_geometry) + bool compressed_geometry, + TravelMode travel_mode) : via_node(via_node), name_id(name_id), turn_instruction(turn_instruction), - compressed_geometry(compressed_geometry) + compressed_geometry(compressed_geometry), travel_mode(travel_mode) { } OriginalEdgeData() : via_node(std::numeric_limits::max()), name_id(std::numeric_limits::max()), - turn_instruction(TurnInstruction::NoTurn), compressed_geometry(false) + turn_instruction(TurnInstruction::NoTurn), compressed_geometry(false), + travel_mode(TRAVEL_MODE_INACCESSIBLE) { } @@ -55,6 +58,7 @@ struct OriginalEdgeData unsigned name_id; TurnInstruction turn_instruction; bool compressed_geometry; + TravelMode travel_mode; }; #endif // ORIGINAL_EDGE_DATA_H diff --git a/3party/osrm/osrm-backend/DataStructures/PhantomNodes.h b/3party/osrm/osrm-backend/DataStructures/PhantomNodes.h index 5206ea6abe..7c12790725 100644 --- a/3party/osrm/osrm-backend/DataStructures/PhantomNodes.h +++ b/3party/osrm/osrm-backend/DataStructures/PhantomNodes.h @@ -28,8 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H -#include "../Include/osrm/Coordinate.h" -#include "../Util/SimpleLogger.h" +#include +#include "../DataStructures/TravelMode.h" +#include "../Util/simple_logger.hpp" #include "../typedefs.h" #include @@ -39,7 +40,8 @@ struct PhantomNode PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id, int forward_weight, int reverse_weight, int forward_offset, int reverse_offset, unsigned packed_geometry_id, FixedPointCoordinate &location, - unsigned short fwd_segment_position) : + unsigned short fwd_segment_position, + TravelMode forward_travel_mode, TravelMode backward_travel_mode) : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), @@ -49,7 +51,9 @@ struct PhantomNode reverse_offset(reverse_offset), packed_geometry_id(packed_geometry_id), location(location), - fwd_segment_position(fwd_segment_position) + fwd_segment_position(fwd_segment_position), + forward_travel_mode(forward_travel_mode), + backward_travel_mode(backward_travel_mode) { } PhantomNode() : @@ -61,7 +65,9 @@ struct PhantomNode forward_offset(0), reverse_offset(0), packed_geometry_id(SPECIAL_EDGEID), - fwd_segment_position(0) + fwd_segment_position(0), + forward_travel_mode(TRAVEL_MODE_INACCESSIBLE), + backward_travel_mode(TRAVEL_MODE_INACCESSIBLE) { } NodeID forward_node_id; @@ -74,6 +80,8 @@ struct PhantomNode unsigned packed_geometry_id; FixedPointCoordinate location; unsigned short fwd_segment_position; + TravelMode forward_travel_mode : 4; + TravelMode backward_travel_mode : 4; int GetForwardWeightPlusOffset() const { @@ -134,7 +142,7 @@ struct PhantomNode } }; -typedef std::vector> PhantomNodeArray; +using PhantomNodeArray = std::vector>; struct PhantomNodeLists { diff --git a/3party/osrm/osrm-backend/DataStructures/QueryNode.h b/3party/osrm/osrm-backend/DataStructures/QueryNode.h index 1e7ca9eb90..6ebbce46d7 100644 --- a/3party/osrm/osrm-backend/DataStructures/QueryNode.h +++ b/3party/osrm/osrm-backend/DataStructures/QueryNode.h @@ -30,7 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../typedefs.h" -#include "../Include/osrm/Coordinate.h" +#include #include @@ -38,8 +38,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. struct NodeInfo { - typedef NodeID key_type; // type of NodeID - typedef int value_type; // type of lat,lons + using key_type = NodeID; // type of NodeID + using value_type = int; // type of lat,lons explicit NodeInfo(int lat, int lon, NodeID node_id) : lat(lat), lon(lon), node_id(node_id) {} NodeInfo() diff --git a/3party/osrm/osrm-backend/DataStructures/Range.h b/3party/osrm/osrm-backend/DataStructures/Range.h index 2d08fed8a5..7e2461ce73 100644 --- a/3party/osrm/osrm-backend/DataStructures/Range.h +++ b/3party/osrm/osrm-backend/DataStructures/Range.h @@ -1,6 +1,6 @@ /* -Copyright (c) 2013, Project OSRM, Dennis Luxen, others +Copyright (c) 2013,2014, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, @@ -49,7 +49,7 @@ template class range const range &begin() const { return *this; } const range &end() const { return *this; } Integer front() const { return iter; } - Integer back() const { return last-1; } + Integer back() const { return last - 1; } // Iterator functions bool operator!=(const range &) const { return iter < last; } @@ -57,6 +57,7 @@ template class range Integer operator*() const { return iter; } }; +// convenience function to construct an integer range with type deduction template range irange(Integer first, Integer last) { return range(first, last); diff --git a/3party/osrm/osrm-backend/DataStructures/RangeTable.h b/3party/osrm/osrm-backend/DataStructures/RangeTable.h index 3ac498df21..46333aefb5 100644 --- a/3party/osrm/osrm-backend/DataStructures/RangeTable.h +++ b/3party/osrm/osrm-backend/DataStructures/RangeTable.h @@ -1,5 +1,5 @@ -#ifndef __RANGE_TABLE_H__ -#define __RANGE_TABLE_H__ +#ifndef RANGE_TABLE_H_ +#define RANGE_TABLE_H_ #include "Range.h" #include "SharedMemoryFactory.h" @@ -36,10 +36,10 @@ class RangeTable { public: - typedef std::array BlockT; - typedef typename ShM::vector BlockContainerT; - typedef typename ShM::vector OffsetContainerT; - typedef osrm::range RangeT; + using BlockT = std::array; + using BlockContainerT = typename ShM::vector; + using OffsetContainerT = typename ShM::vector; + using RangeT = osrm::range; friend std::ostream& operator<< <>(std::ostream &out, const RangeTable &table); friend std::istream& operator>> <>(std::istream &in, RangeTable &table); @@ -228,4 +228,4 @@ std::istream& operator>>(std::istream &in, RangeTable predecessors; for (const EdgeID current_edge_id : m_graph->GetAdjacentEdgeRange(node_u)) { - const EdgeData &edge_data = m_graph->GetEdgeData(current_edge_id); const NodeID target = m_graph->GetTarget(current_edge_id); - if (edge_data.backward && (node_v != target)) + if (node_v != target) { predecessors.push_back(target); } @@ -163,11 +160,11 @@ NodeID RestrictionMap::CheckForEmanatingIsOnlyTurn(const NodeID node_u, const No return SPECIAL_NODEID; } - auto restriction_iter = m_restriction_map.find({node_u, node_v}); + const auto restriction_iter = m_restriction_map.find({node_u, node_v}); if (restriction_iter != m_restriction_map.end()) { const unsigned index = restriction_iter->second; - auto &bucket = m_restriction_bucket_list.at(index); + const auto &bucket = m_restriction_bucket_list.at(index); for (const RestrictionTarget &restriction_target : bucket) { if (restriction_target.is_only) @@ -184,8 +181,6 @@ bool RestrictionMap::CheckIfTurnIsRestricted(const NodeID node_u, const NodeID node_v, const NodeID node_w) const { - // return false; - BOOST_ASSERT(node_u != SPECIAL_NODEID); BOOST_ASSERT(node_v != SPECIAL_NODEID); BOOST_ASSERT(node_w != SPECIAL_NODEID); @@ -195,7 +190,7 @@ bool RestrictionMap::CheckIfTurnIsRestricted(const NodeID node_u, return false; } - auto restriction_iter = m_restriction_map.find({node_u, node_v}); + const auto restriction_iter = m_restriction_map.find({node_u, node_v}); if (restriction_iter != m_restriction_map.end()) { const unsigned index = restriction_iter->second; diff --git a/3party/osrm/osrm-backend/DataStructures/RestrictionMap.h b/3party/osrm/osrm-backend/DataStructures/RestrictionMap.h index 580d5e3487..3945a3982b 100644 --- a/3party/osrm/osrm-backend/DataStructures/RestrictionMap.h +++ b/3party/osrm/osrm-backend/DataStructures/RestrictionMap.h @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef __RESTRICTION_MAP_H__ -#define __RESTRICTION_MAP_H__ +#ifndef RESTRICTION_MAP_H_ +#define RESTRICTION_MAP_H_ #include @@ -110,8 +110,8 @@ class RestrictionMap private: bool IsSourceNode(const NodeID node) const; - typedef std::vector EmanatingRestrictionsVector; - typedef NodeBasedDynamicGraph::EdgeData EdgeData; + using EmanatingRestrictionsVector = std::vector; + using EdgeData = NodeBasedDynamicGraph::EdgeData; std::size_t m_count; std::shared_ptr m_graph; @@ -123,4 +123,4 @@ class RestrictionMap std::unordered_set m_no_turn_via_node_set; }; -#endif +#endif //RESTRICTION_MAP_H_ diff --git a/3party/osrm/osrm-backend/DataStructures/RouteParameters.cpp b/3party/osrm/osrm-backend/DataStructures/RouteParameters.cpp index 4357ebd39b..1019a9149e 100644 --- a/3party/osrm/osrm-backend/DataStructures/RouteParameters.cpp +++ b/3party/osrm/osrm-backend/DataStructures/RouteParameters.cpp @@ -33,7 +33,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), - compression(true), deprecatedAPI(false), uturn_default(false), check_sum(-1) + compression(true), deprecatedAPI(false), uturn_default(false), check_sum(-1), num_results(1) { } @@ -45,6 +45,14 @@ void RouteParameters::setZoomLevel(const short level) } } +void RouteParameters::setNumberOfResults(const short number) +{ + if (number > 0 && number <= 100) + { + num_results = number; + } +} + void RouteParameters::setAlternateRouteFlag(const bool flag) { alternate_route = flag; } void RouteParameters::setUTurn(const bool flag) diff --git a/3party/osrm/osrm-backend/DataStructures/SearchEngineData.h b/3party/osrm/osrm-backend/DataStructures/SearchEngineData.h index c7446adc80..d5bfb53f92 100644 --- a/3party/osrm/osrm-backend/DataStructures/SearchEngineData.h +++ b/3party/osrm/osrm-backend/DataStructures/SearchEngineData.h @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SEARCH_ENGINE_DATA_H #define SEARCH_ENGINE_DATA_H -#include +#include #include "../typedefs.h" #include "BinaryHeap.h" @@ -41,8 +41,8 @@ struct HeapData struct SearchEngineData { - typedef BinaryHeap> QueryHeap; - typedef boost::scoped_ptr SearchEngineHeapPtr; + using QueryHeap = BinaryHeap>; + using SearchEngineHeapPtr = boost::thread_specific_ptr; static SearchEngineHeapPtr forwardHeap; static SearchEngineHeapPtr backwardHeap; diff --git a/3party/osrm/osrm-backend/DataStructures/SegmentInformation.h b/3party/osrm/osrm-backend/DataStructures/SegmentInformation.h index f145804491..6e8d683974 100644 --- a/3party/osrm/osrm-backend/DataStructures/SegmentInformation.h +++ b/3party/osrm/osrm-backend/DataStructures/SegmentInformation.h @@ -30,6 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "TurnInstructions.h" +#include "../DataStructures/TravelMode.h" #include "../typedefs.h" #include @@ -43,8 +44,9 @@ struct SegmentInformation float length; short bearing; // more than enough [0..3600] fits into 12 bits TurnInstruction turn_instruction; - bool necessary:1; - bool is_via_location:1; + TravelMode travel_mode; + bool necessary; + bool is_via_location; explicit SegmentInformation(const FixedPointCoordinate &location, const NodeID name_id, @@ -52,9 +54,11 @@ struct SegmentInformation const float length, const TurnInstruction turn_instruction, const bool necessary, - const bool is_via_location) + const bool is_via_location, + const TravelMode travel_mode) : location(location), name_id(name_id), duration(duration), length(length), bearing(0), - turn_instruction(turn_instruction), necessary(necessary), is_via_location(is_via_location) + turn_instruction(turn_instruction), travel_mode(travel_mode), necessary(necessary), + is_via_location(is_via_location) { } @@ -62,9 +66,11 @@ struct SegmentInformation const NodeID name_id, const EdgeWeight duration, const float length, - const TurnInstruction turn_instruction) + const TurnInstruction turn_instruction, + const TravelMode travel_mode) : location(location), name_id(name_id), duration(duration), length(length), bearing(0), - turn_instruction(turn_instruction), necessary(turn_instruction != TurnInstruction::NoTurn), is_via_location(false) + turn_instruction(turn_instruction), travel_mode(travel_mode), + necessary(turn_instruction != TurnInstruction::NoTurn), is_via_location(false) { } }; diff --git a/3party/osrm/osrm-backend/DataStructures/SharedMemoryFactory.h b/3party/osrm/osrm-backend/DataStructures/SharedMemoryFactory.h index d3f9d8e321..0b1f0e1c5f 100644 --- a/3party/osrm/osrm-backend/DataStructures/SharedMemoryFactory.h +++ b/3party/osrm/osrm-backend/DataStructures/SharedMemoryFactory.h @@ -29,21 +29,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SHARED_MEMORY_FACTORY_H #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include #include #include -#if !defined(WIN32) && !defined(__ANDROID__) +#ifndef WIN32 #include #else #include #endif -//#ifdef __linux__ -//#include -//#include -//#endif +#ifdef __linux__ +#include +#include +#endif // #include #include @@ -61,7 +61,7 @@ struct OSRMLockFile } }; -#if !defined(WIN32) && !defined(__ANDROID__) +#ifndef WIN32 class SharedMemory { @@ -196,12 +196,14 @@ class SharedMemory }; #else // Windows - specific code -class SharedMemory : boost::noncopyable +class SharedMemory { + SharedMemory(const SharedMemory&) = delete; // Remove shared memory on destruction - class shm_remove : boost::noncopyable + class shm_remove { private: + shm_remove(const shm_remove&) = delete; char *m_shmid; bool m_initialized; @@ -286,7 +288,6 @@ class SharedMemory : boost::noncopyable private: static void build_key(int id, char *key) { - OSRMLockFile lock_file; sprintf(key, "%s.%d", "osrm.lock", id); } @@ -365,6 +366,6 @@ template class SharedMemoryFactory_tmpl SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete; }; -typedef SharedMemoryFactory_tmpl<> SharedMemoryFactory; +using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; #endif /* SHARED_MEMORY_POINTER_FACTORY_H */ diff --git a/3party/osrm/osrm-backend/DataStructures/SharedMemoryVectorWrapper.h b/3party/osrm/osrm-backend/DataStructures/SharedMemoryVectorWrapper.h index fe4baf3385..bcc30a7f2c 100644 --- a/3party/osrm/osrm-backend/DataStructures/SharedMemoryVectorWrapper.h +++ b/3party/osrm/osrm-backend/DataStructures/SharedMemoryVectorWrapper.h @@ -28,8 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SHARED_MEMORY_VECTOR_WRAPPER_H #define SHARED_MEMORY_VECTOR_WRAPPER_H -#include "../Util/SimpleLogger.h" - #include #include @@ -78,7 +76,7 @@ template class SharedMemoryWrapper void swap(SharedMemoryWrapper &other) { - BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); + // BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); std::swap(m_size, other.m_size); std::swap(m_ptr, other.m_ptr); } @@ -121,7 +119,7 @@ template <> class SharedMemoryWrapper void swap(SharedMemoryWrapper &other) { - BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); + // BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); std::swap(m_size, other.m_size); std::swap(m_ptr, other.m_ptr); } @@ -148,9 +146,9 @@ template <> class SharedMemoryWrapper template struct ShM { - typedef typename std::conditional, - std::vector>::type vector; + std::vector>::type; }; #endif // SHARED_MEMORY_VECTOR_WRAPPER_H diff --git a/3party/osrm/osrm-backend/DataStructures/StaticGraph.h b/3party/osrm/osrm-backend/DataStructures/StaticGraph.h index 850017b0e2..456acfe32e 100644 --- a/3party/osrm/osrm-backend/DataStructures/StaticGraph.h +++ b/3party/osrm/osrm-backend/DataStructures/StaticGraph.h @@ -31,11 +31,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Percent.h" #include "Range.h" #include "SharedMemoryVectorWrapper.h" -#include "../Util/SimpleLogger.h" #include "../typedefs.h" #include +#include + #include #include #include @@ -44,10 +45,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. template class StaticGraph { public: - typedef NodeID NodeIterator; - typedef NodeID EdgeIterator; - typedef EdgeDataT EdgeData; - typedef osrm::range EdgeRange; + using NodeIterator = NodeID; + using EdgeIterator = NodeID; + using EdgeData = EdgeDataT; + using EdgeRange = osrm::range; class InputEdge { @@ -87,7 +88,7 @@ template class StaticGraph StaticGraph(const int nodes, std::vector &graph) { - std::sort(graph.begin(), graph.end()); + tbb::parallel_sort(graph.begin(), graph.end()); number_of_nodes = nodes; number_of_edges = (EdgeIterator)graph.size(); node_array.resize(number_of_nodes + 1); @@ -121,8 +122,8 @@ template class StaticGraph StaticGraph(typename ShM::vector &nodes, typename ShM::vector &edges) { - number_of_nodes = nodes.size() - 1; - number_of_edges = edges.size(); + number_of_nodes = static_cast(nodes.size() - 1); + number_of_edges = static_cast(edges.size()); node_array.swap(nodes); edge_array.swap(edges); diff --git a/3party/osrm/osrm-backend/DataStructures/StaticKDTree.h b/3party/osrm/osrm-backend/DataStructures/StaticKDTree.h index e36eee97a7..4e93884472 100644 --- a/3party/osrm/osrm-backend/DataStructures/StaticKDTree.h +++ b/3party/osrm/osrm-backend/DataStructures/StaticKDTree.h @@ -211,7 +211,7 @@ class StaticKDTree } private: - typedef unsigned Iterator; + using Iterator = unsigned; struct Tree { Iterator left; diff --git a/3party/osrm/osrm-backend/DataStructures/StaticRTree.h b/3party/osrm/osrm-backend/DataStructures/StaticRTree.h index 3009f962df..6e09b4347d 100644 --- a/3party/osrm/osrm-backend/DataStructures/StaticRTree.h +++ b/3party/osrm/osrm-backend/DataStructures/StaticRTree.h @@ -35,10 +35,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "SharedMemoryFactory.h" #include "SharedMemoryVectorWrapper.h" +#include "../ThirdParty/variant/variant.hpp" +#include "../Util/floating_point.hpp" #include "../Util/MercatorUtil.h" -#include "../Util/NumericUtil.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/TimingUtil.h" #include "../typedefs.h" @@ -48,7 +49,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include + +#include +#include #include #include @@ -67,7 +70,6 @@ template IncrementalQueryNodeType; + using IncrementalQueryNodeType = mapbox::util::variant; struct IncrementalQueryCandidate { explicit IncrementalQueryCandidate(const float dist, const IncrementalQueryNodeType &node) @@ -321,23 +323,8 @@ class StaticRTree return other.min_dist < min_dist; } - inline bool RepresentsTreeNode() const - { - return boost::apply_visitor(decide_type_visitor(), node); - } - float min_dist; IncrementalQueryNodeType node; - - private: - class decide_type_visitor : public boost::static_visitor - { - public: - bool operator()(const TreeNode &) const { return true; } - - template - bool operator()(const AnotherType &) const { return false; } - }; }; typename ShM::vector m_search_tree; @@ -366,33 +353,39 @@ class StaticRTree HilbertCode get_hilbert_number; - // generate auxiliary vector of hilbert-valuesß∫ - for (uint64_t element_counter = 0; element_counter != m_element_count; ++element_counter) - { - WrappedInputElement ¤t_wrapper = input_wrapper_vector[element_counter]; - current_wrapper.m_array_index = element_counter; + // generate auxiliary vector of hilbert-values + tbb::parallel_for( + tbb::blocked_range(0, m_element_count), + [&input_data_vector, &input_wrapper_vector, &get_hilbert_number, &coordinate_list]( + const tbb::blocked_range &range) + { + for (uint64_t element_counter = range.begin(); element_counter != range.end(); + ++element_counter) + { + WrappedInputElement ¤t_wrapper = input_wrapper_vector[element_counter]; + current_wrapper.m_array_index = element_counter; - EdgeDataT const ¤t_element = input_data_vector[element_counter]; + EdgeDataT const ¤t_element = input_data_vector[element_counter]; - // Get Hilbert-Value for centroid in mercartor projection - FixedPointCoordinate current_centroid = EdgeDataT::Centroid( - FixedPointCoordinate(coordinate_list.at(current_element.u).lat, - coordinate_list.at(current_element.u).lon), - FixedPointCoordinate(coordinate_list.at(current_element.v).lat, - coordinate_list.at(current_element.v).lon)); - current_centroid.lat = - COORDINATE_PRECISION * lat2y(current_centroid.lat / COORDINATE_PRECISION); - - current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid); - } + // Get Hilbert-Value for centroid in mercartor projection + FixedPointCoordinate current_centroid = EdgeDataT::Centroid( + FixedPointCoordinate(coordinate_list.at(current_element.u).lat, + coordinate_list.at(current_element.u).lon), + FixedPointCoordinate(coordinate_list.at(current_element.v).lat, + coordinate_list.at(current_element.v).lon)); + current_centroid.lat = + COORDINATE_PRECISION * lat2y(current_centroid.lat / COORDINATE_PRECISION); + current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid); + } + }); // open leaf file boost::filesystem::ofstream leaf_node_file(leaf_node_filename, std::ios::binary); leaf_node_file.write((char *)&m_element_count, sizeof(uint64_t)); // sort the hilbert-value representatives - sort(input_wrapper_vector.begin(), input_wrapper_vector.end()); + tbb::parallel_sort(input_wrapper_vector.begin(), input_wrapper_vector.end()); std::vector tree_nodes_in_level; // pack M elements into leaf node and write to leaf file @@ -472,18 +465,22 @@ class StaticRTree // reverse and renumber tree to have root at index 0 std::reverse(m_search_tree.begin(), m_search_tree.end()); - uint32_t search_tree_size = m_search_tree.size(); - for (uint32_t i = 0; i != search_tree_size; ++i) - { - TreeNode ¤t_tree_node = this->m_search_tree[i]; - for (uint32_t j = 0; j < current_tree_node.child_count; ++j) - { - const uint32_t old_id = current_tree_node.children[j]; - const uint32_t new_id = search_tree_size - old_id - 1; - current_tree_node.children[j] = new_id; - } - } + uint32_t search_tree_size = m_search_tree.size(); + tbb::parallel_for(tbb::blocked_range(0, search_tree_size), + [this, &search_tree_size](const tbb::blocked_range &range) + { + for (uint32_t i = range.begin(); i != range.end(); ++i) + { + TreeNode ¤t_tree_node = this->m_search_tree[i]; + for (uint32_t j = 0; j < current_tree_node.child_count; ++j) + { + const uint32_t old_id = current_tree_node.children[j]; + const uint32_t new_id = search_tree_size - old_id - 1; + current_tree_node.children[j] = new_id; + } + } + }); // open tree file boost::filesystem::ofstream tree_node_file(tree_node_filename, std::ios::binary); @@ -688,9 +685,9 @@ class StaticRTree continue; } - if (current_query_node.RepresentsTreeNode()) + if (current_query_node.node.template is()) { - const TreeNode & current_tree_node = boost::get(current_query_node.node); + const TreeNode & current_tree_node = current_query_node.node.template get(); if (current_tree_node.child_is_on_disk) { ++loaded_leafs; @@ -763,7 +760,7 @@ class StaticRTree { ++inspected_segments; // inspecting an actual road segment - const EdgeDataT & current_segment = boost::get(current_query_node.node); + const EdgeDataT & current_segment = current_query_node.node.template get(); // don't collect too many results from small components if (number_of_results_found_in_big_cc == number_of_results && !current_segment.is_in_tiny_cc) @@ -791,7 +788,7 @@ class StaticRTree BOOST_ASSERT(0. <= current_perpendicular_distance); if ((current_perpendicular_distance < current_min_dist) && - !EpsilonCompare(current_perpendicular_distance, current_min_dist)) + !osrm::epsilon_compare(current_perpendicular_distance, current_min_dist)) { // store phantom node in result vector result_phantom_node_vector.emplace_back( @@ -804,7 +801,9 @@ class StaticRTree current_segment.reverse_offset, current_segment.packed_geometry_id, foot_point_coordinate_on_segment, - current_segment.fwd_segment_position); + current_segment.fwd_segment_position, + current_segment.forward_travel_mode, + current_segment.backward_travel_mode); // Hack to fix rounding errors and wandering via nodes. FixUpRoundingIssue(input_coordinate, result_phantom_node_vector.back()); @@ -891,7 +890,7 @@ class StaticRTree if (current_query_node.RepresentsTreeNode()) { - const TreeNode & current_tree_node = boost::get(current_query_node.node); + const TreeNode & current_tree_node = current_query_node.node.template get(); if (current_tree_node.child_is_on_disk) { LeafNode current_leaf_node; @@ -940,7 +939,7 @@ class StaticRTree { ++inspected_segments; // inspecting an actual road segment - const EdgeDataT & current_segment = boost::get(current_query_node.node); + const EdgeDataT & current_segment = current_query_node.node.template get(); // don't collect too many results from small components if (number_of_results_found_in_big_cc == number_of_results && !current_segment.is_in_tiny_cc) @@ -968,7 +967,7 @@ class StaticRTree BOOST_ASSERT(0. <= current_perpendicular_distance); if ((current_perpendicular_distance < current_min_dist) && - !EpsilonCompare(current_perpendicular_distance, current_min_dist)) + !osrm::epsilon_compare(current_perpendicular_distance, current_min_dist)) { // store phantom node in result vector result_phantom_node_vector.emplace_back( @@ -1068,7 +1067,7 @@ class StaticRTree BOOST_ASSERT(0. <= current_perpendicular_distance); if ((current_perpendicular_distance < min_dist) && - !EpsilonCompare(current_perpendicular_distance, min_dist)) + !osrm::epsilon_compare(current_perpendicular_distance, min_dist)) { // found a new minimum min_dist = current_perpendicular_distance; result_phantom_node = {current_edge.forward_edge_based_node_id, @@ -1080,7 +1079,9 @@ class StaticRTree current_edge.reverse_offset, current_edge.packed_geometry_id, nearest, - current_edge.fwd_segment_position}; + current_edge.fwd_segment_position, + current_edge.forward_travel_mode, + current_edge.backward_travel_mode}; nearest_edge = current_edge; } } diff --git a/3party/osrm/osrm-backend/Util/NumericUtil.h b/3party/osrm/osrm-backend/DataStructures/TravelMode.h similarity index 83% rename from 3party/osrm/osrm-backend/Util/NumericUtil.h rename to 3party/osrm/osrm-backend/DataStructures/TravelMode.h index 5853f81869..7ccc24d215 100644 --- a/3party/osrm/osrm-backend/Util/NumericUtil.h +++ b/3party/osrm/osrm-backend/DataStructures/TravelMode.h @@ -1,4 +1,5 @@ /* + Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. @@ -24,16 +25,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef __NUMERIC_UTIL_H__ -#define __NUMERIC_UTIL_H__ +#ifndef TRAVEL_MODE_H +#define TRAVEL_MODE_H -#include +using TravelMode = unsigned char; +static const TravelMode TRAVEL_MODE_INACCESSIBLE = 0; +static const TravelMode TRAVEL_MODE_DEFAULT = 1; -#include - -template inline bool EpsilonCompare(const FloatT d1, const FloatT d2) -{ - return (std::abs(d1 - d2) < std::numeric_limits::epsilon()); -} - -#endif +#endif /* TRAVEL_MODE_H */ diff --git a/3party/osrm/osrm-backend/DataStructures/TurnInstructions.h b/3party/osrm/osrm-backend/DataStructures/TurnInstructions.h index 61de3b11b7..611b574ddd 100644 --- a/3party/osrm/osrm-backend/DataStructures/TurnInstructions.h +++ b/3party/osrm/osrm-backend/DataStructures/TurnInstructions.h @@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. enum class TurnInstruction : unsigned char { NoTurn = 0, GoStraight, TurnSlightRight, TurnRight, TurnSharpRight, UTurn, - TurnSharpLeft, TurnLeft, TurnSlightLeft, ReachViaPoint, HeadOn, EnterRoundAbout, + TurnSharpLeft, TurnLeft, TurnSlightLeft, ReachViaLocation, HeadOn, EnterRoundAbout, LeaveRoundAbout, StayOnRoundAbout, StartAtEndOfStreet, ReachedYourDestination, EnterAgainstAllowedDirection, LeaveAgainstAllowedDirection, InverseAccessRestrictionFlag = 127, diff --git a/3party/osrm/osrm-backend/DataStructures/XORFastHashStorage.h b/3party/osrm/osrm-backend/DataStructures/XORFastHashStorage.h index abdb9ac44e..18de3c52c8 100644 --- a/3party/osrm/osrm-backend/DataStructures/XORFastHashStorage.h +++ b/3party/osrm/osrm-backend/DataStructures/XORFastHashStorage.h @@ -49,14 +49,14 @@ template class XORFastHashStorage HashCell(const HashCell &other) : key(other.key), id(other.id), time(other.time) {} - inline operator Key() const { return key; } + operator Key() const { return key; } - inline void operator=(const Key &key_to_insert) { key = key_to_insert; } + void operator=(const Key &key_to_insert) { key = key_to_insert; } }; explicit XORFastHashStorage(size_t) : positions(2 << 16), current_timestamp(0) {} - inline HashCell &operator[](const NodeID node) + HashCell &operator[](const NodeID node) { unsigned short position = fast_hasher(node); while ((positions[position].time == current_timestamp) && (positions[position].id != node)) @@ -69,7 +69,7 @@ template class XORFastHashStorage return positions[position]; } - inline void Clear() + void Clear() { ++current_timestamp; if (std::numeric_limits::max() == current_timestamp) diff --git a/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.cpp b/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.cpp index 2d66cc197e..715bf69037 100644 --- a/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.cpp +++ b/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.cpp @@ -45,38 +45,71 @@ void DescriptionFactory::SetStartSegment(const PhantomNode &source, const bool t start_phantom = source; const EdgeWeight segment_duration = (traversed_in_reverse ? source.reverse_weight : source.forward_weight); - AppendSegment(source.location, - PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration)); + const TravelMode travel_mode = + (traversed_in_reverse ? source.backward_travel_mode : source.forward_travel_mode); + AppendSegment( + source.location, + PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration, travel_mode)); BOOST_ASSERT(path_description.back().duration == segment_duration); } -void DescriptionFactory::SetEndSegment(const PhantomNode &target, const bool traversed_in_reverse) +void DescriptionFactory::SetEndSegment(const PhantomNode &target, + const bool traversed_in_reverse, + const bool is_via_location) { target_phantom = target; const EdgeWeight segment_duration = (traversed_in_reverse ? target.reverse_weight : target.forward_weight); - path_description.emplace_back( - target.location, target.name_id, segment_duration, 0.f, TurnInstruction::NoTurn, true, true); + const TravelMode travel_mode = + (traversed_in_reverse ? target.backward_travel_mode : target.forward_travel_mode); + path_description.emplace_back(target.location, + target.name_id, + segment_duration, + 0.f, + is_via_location ? TurnInstruction::ReachViaLocation + : TurnInstruction::NoTurn, + true, + true, + travel_mode); BOOST_ASSERT(path_description.back().duration == segment_duration); } void DescriptionFactory::AppendSegment(const FixedPointCoordinate &coordinate, const PathData &path_point) { - if ((1 == path_description.size()) && (path_description.back().location == coordinate)) + // if the start location is on top of a node, the first movement might be zero-length, + // in which case we dont' add a new description, but instead update the existing one + if ((1 == path_description.size()) && (path_description.front().location == coordinate)) { - path_description.back().name_id = path_point.name_id; + if (path_point.segment_duration > 0) + { + path_description.front().name_id = path_point.name_id; + path_description.front().travel_mode = path_point.travel_mode; + } return; } + // make sure mode changes are announced, even when there otherwise is no turn + const TurnInstruction turn = [&]() -> TurnInstruction + { + if (TurnInstruction::NoTurn == path_point.turn_instruction && + path_description.front().travel_mode != path_point.travel_mode && + path_point.segment_duration > 0) + { + return TurnInstruction::GoStraight; + } + return path_point.turn_instruction; + }(); + path_description.emplace_back(coordinate, path_point.name_id, path_point.segment_duration, 0.f, - path_point.turn_instruction); + turn, + path_point.travel_mode); } -JSON::Value DescriptionFactory::AppendEncodedPolylineString(const bool return_encoded) +JSON::Value DescriptionFactory::AppendGeometryString(const bool return_encoded) { if (return_encoded) { diff --git a/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.h b/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.h index d081bae888..ac4c70234f 100644 --- a/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.h +++ b/3party/osrm/osrm-backend/Descriptors/DescriptionFactory.h @@ -80,9 +80,11 @@ class DescriptionFactory void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &data); void BuildRouteSummary(const double distance, const unsigned time); void SetStartSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse); - void SetEndSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse); - JSON::Value AppendEncodedPolylineString(const bool return_encoded); - std::vector const & GetViaIndices() const; + void SetEndSegment(const PhantomNode &start_phantom, + const bool traversed_in_reverse, + const bool is_via_location = false); + JSON::Value AppendGeometryString(const bool return_encoded); + std::vector const &GetViaIndices() const; template void Run(const DataFacadeT *facade, const unsigned zoomLevel) { @@ -198,14 +200,15 @@ class DescriptionFactory { ++necessary_pieces; if (path_description[i].is_via_location) - { //mark the end of a leg + { // mark the end of a leg via_indices.push_back(necessary_pieces); } - const double angle = path_description[i+1].location.GetBearing(path_description[i].location); + const double angle = + path_description[i + 1].location.GetBearing(path_description[i].location); path_description[i].bearing = static_cast(angle * 10); } } - via_indices.push_back(necessary_pieces+1); + via_indices.push_back(necessary_pieces + 1); BOOST_ASSERT(via_indices.size() >= 2); // BOOST_ASSERT(0 != necessary_pieces || path_description.empty()); return; diff --git a/3party/osrm/osrm-backend/Descriptors/GPXDescriptor.h b/3party/osrm/osrm-backend/Descriptors/GPXDescriptor.h index 50efd9ae2d..6f76b3bc87 100644 --- a/3party/osrm/osrm-backend/Descriptors/GPXDescriptor.h +++ b/3party/osrm/osrm-backend/Descriptors/GPXDescriptor.h @@ -30,14 +30,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BaseDescriptor.h" -template class GPXDescriptor : public BaseDescriptor +template class GPXDescriptor final : public BaseDescriptor { private: DescriptorConfig config; FixedPointCoordinate current; - DataFacadeT * facade; + DataFacadeT *facade; - void AddRoutePoint(const FixedPointCoordinate & coordinate, std::vector & output) + void AddRoutePoint(const FixedPointCoordinate &coordinate, std::vector &output) { const std::string route_point_head = " class GPXDescriptor : public BaseDescriptor" " class GPXDescriptor : public BaseDescriptor &path_data_vector : raw_route.unpacked_path_segments) { @@ -90,8 +91,8 @@ template class GPXDescriptor : public BaseDescriptor"); reply.content.insert(reply.content.end(), footer.begin(), footer.end()); diff --git a/3party/osrm/osrm-backend/Descriptors/JSONDescriptor.h b/3party/osrm/osrm-backend/Descriptors/JSONDescriptor.h index f0db43f17a..9e095c151e 100644 --- a/3party/osrm/osrm-backend/Descriptors/JSONDescriptor.h +++ b/3party/osrm/osrm-backend/Descriptors/JSONDescriptor.h @@ -42,7 +42,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -template class JSONDescriptor : public BaseDescriptor +template class JSONDescriptor final : public BaseDescriptor { private: DataFacadeT *facade; @@ -70,13 +70,14 @@ template class JSONDescriptor : public BaseDescriptor GenerateRouteNames; public: - JSONDescriptor(DataFacadeT *facade) : facade(facade), entered_restricted_area_count(0) {} + explicit JSONDescriptor(DataFacadeT *facade) : facade(facade), entered_restricted_area_count(0) {} - void SetConfig(const DescriptorConfig &c) { config = c; } + void SetConfig(const DescriptorConfig &c) final { config = c; } unsigned DescribeLeg(const std::vector route_leg, const PhantomNodes &leg_phantoms, - const bool target_traversed_in_reverse) + const bool target_traversed_in_reverse, + const bool is_via_leg) { unsigned added_element_count = 0; // Get all the coordinates for the computed route @@ -87,13 +88,14 @@ template class JSONDescriptor : public BaseDescriptor class JSONDescriptor : public BaseDescriptor class JSONDescriptor : public BaseDescriptor class JSONDescriptor : public BaseDescriptorGetCoordinateOfNode(path_data.node); alternate_description_factory.AppendSegment(current, path_data); } - alternate_description_factory.SetEndSegment(raw_route.segment_end_coordinates.back().target_phantom, raw_route.alt_source_traversed_in_reverse.back()); + alternate_description_factory.SetEndSegment( + raw_route.segment_end_coordinates.back().target_phantom, + raw_route.alt_source_traversed_in_reverse.back()); alternate_description_factory.Run(facade, config.zoom_level); if (config.geometry) { JSON::Value alternate_geometry_string = - alternate_description_factory.AppendEncodedPolylineString( - config.encode_geometry); + alternate_description_factory.AppendGeometryString(config.encode_geometry); JSON::Array json_alternate_geometries_array; json_alternate_geometries_array.values.push_back(alternate_geometry_string); json_result.values["alternative_geometries"] = json_alternate_geometries_array; @@ -279,10 +283,10 @@ template class JSONDescriptor : public BaseDescriptor(0, raw_route.segment_end_coordinates.size())) { - EncodeObjectToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); + ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); json_location_hint_array.values.push_back(hint); } - EncodeObjectToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint); + ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint); json_location_hint_array.values.push_back(hint); json_hint_object.values["locations"] = json_location_hint_array; json_result.values["hint_data"] = json_hint_object; @@ -326,16 +330,16 @@ template class JSONDescriptor : public BaseDescriptor class JSONDescriptor : public BaseDescriptor(segment.length)) + "m"); - const double bearing_value = (segment.bearing / 10.) ; + cast::integral_to_string(static_cast(segment.length)) + "m"); + const double bearing_value = (segment.bearing / 10.); json_instruction_row.values.push_back(Azimuth::Get(bearing_value)); - json_instruction_row.values.push_back(static_cast(round(bearing_value))); + json_instruction_row.values.push_back( + static_cast(round(bearing_value))); + json_instruction_row.values.push_back(segment.travel_mode); route_segments_list.emplace_back( - segment.name_id, static_cast(segment.length), static_cast(route_segments_list.size())); + segment.name_id, + static_cast(segment.length), + static_cast(route_segments_list.size())); json_instruction_array.values.push_back(json_instruction_row); } } @@ -367,7 +375,7 @@ template class JSONDescriptor : public BaseDescriptor #include diff --git a/3party/osrm/osrm-backend/Extractor/ExtractionContainers.cpp b/3party/osrm/osrm-backend/Extractor/ExtractionContainers.cpp index d9e891cf0f..fda062e935 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractionContainers.cpp +++ b/3party/osrm/osrm-backend/Extractor/ExtractionContainers.cpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "ExtractionContainers.h" #include "ExtractionWay.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/TimingUtil.h" #include "../DataStructures/RangeTable.h" @@ -330,7 +330,6 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, edge_iterator->source_coordinate.lon != std::numeric_limits::min()) { BOOST_ASSERT(edge_iterator->speed != -1); - BOOST_ASSERT(edge_iterator->type >= 0); edge_iterator->target_coordinate.lat = node_iterator->lat; edge_iterator->target_coordinate.lon = node_iterator->lon; @@ -349,7 +348,6 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, short zero = 0; short one = 1; - file_out_stream.write((char *)&edge_iterator->way_id, sizeof(unsigned)); file_out_stream.write((char *)&edge_iterator->start, sizeof(unsigned)); file_out_stream.write((char *)&edge_iterator->target, sizeof(unsigned)); file_out_stream.write((char *)&integer_distance, sizeof(int)); @@ -372,14 +370,16 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, } file_out_stream.write((char *)&integer_weight, sizeof(int)); - file_out_stream.write((char *)&edge_iterator->type, sizeof(short)); file_out_stream.write((char *)&edge_iterator->name_id, sizeof(unsigned)); file_out_stream.write((char *)&edge_iterator->is_roundabout, sizeof(bool)); file_out_stream.write((char *)&edge_iterator->is_in_tiny_cc, sizeof(bool)); file_out_stream.write((char *)&edge_iterator->is_access_restricted, sizeof(bool)); - file_out_stream.write((char *)&edge_iterator->is_contra_flow, sizeof(bool)); - file_out_stream.write((char *)&edge_iterator->is_split, sizeof(bool)); + // cannot take adress of bit field, so use local + const TravelMode travel_mode = edge_iterator->travel_mode; + file_out_stream.write((char *)&travel_mode, sizeof(TravelMode)); + + file_out_stream.write((char *)&edge_iterator->is_split, sizeof(bool)); ++number_of_used_edges; } ++edge_iterator; diff --git a/3party/osrm/osrm-backend/Extractor/ExtractionContainers.h b/3party/osrm/osrm-backend/Extractor/ExtractionContainers.h index a272387ea2..bfb318ba7a 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractionContainers.h +++ b/3party/osrm/osrm-backend/Extractor/ExtractionContainers.h @@ -43,12 +43,12 @@ class ExtractionContainers const static unsigned stxxl_memory = ((sizeof(std::size_t) == 4) ? INT_MAX : UINT_MAX); #endif public: - typedef stxxl::vector STXXLNodeIDVector; - typedef stxxl::vector STXXLNodeVector; - typedef stxxl::vector STXXLEdgeVector; - typedef stxxl::vector STXXLStringVector; - typedef stxxl::vector STXXLRestrictionsVector; - typedef stxxl::vector STXXLWayIDStartEndVector; + using STXXLNodeIDVector = stxxl::vector; + using STXXLNodeVector = stxxl::vector; + using STXXLEdgeVector = stxxl::vector; + using STXXLStringVector = stxxl::vector; + using STXXLRestrictionsVector = stxxl::vector; + using STXXLWayIDStartEndVector = stxxl::vector; STXXLNodeIDVector used_node_id_list; STXXLNodeVector all_nodes_list; @@ -60,7 +60,7 @@ class ExtractionContainers ExtractionContainers(); - virtual ~ExtractionContainers(); + ~ExtractionContainers(); void PrepareData(const std::string &output_file_name, const std::string &restrictions_file_name); diff --git a/3party/osrm/osrm-backend/Extractor/ExtractionHelperFunctions.h b/3party/osrm/osrm-backend/Extractor/ExtractionHelperFunctions.h index a918744f16..b053338fd0 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractionHelperFunctions.h +++ b/3party/osrm/osrm-backend/Extractor/ExtractionHelperFunctions.h @@ -28,10 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTION_HELPER_FUNCTIONS_H #define EXTRACTION_HELPER_FUNCTIONS_H -#include "../Util/StringUtil.h" +#include "../Util/cast.hpp" #include #include +#include #include #include @@ -68,18 +69,18 @@ inline unsigned parseDuration(const std::string &s) { if (1 == result.size()) { - minutes = StringToUint(result[0]); + minutes = cast::string_to_int(result[0]); } if (2 == result.size()) { - minutes = StringToUint(result[1]); - hours = StringToUint(result[0]); + minutes = cast::string_to_int(result[1]); + hours = cast::string_to_int(result[0]); } if (3 == result.size()) { - seconds = StringToUint(result[2]); - minutes = StringToUint(result[1]); - hours = StringToUint(result[0]); + seconds = cast::string_to_int(result[2]); + minutes = cast::string_to_int(result[1]); + hours = cast::string_to_int(result[0]); } return 10 * (3600 * hours + 60 * minutes + seconds); } diff --git a/3party/osrm/osrm-backend/Extractor/ExtractionWay.h b/3party/osrm/osrm-backend/Extractor/ExtractionWay.h index 6c3c93d63e..1a197b6599 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractionWay.h +++ b/3party/osrm/osrm-backend/Extractor/ExtractionWay.h @@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define EXTRACTION_WAY_H #include "../DataStructures/HashTable.h" +#include "../DataStructures/TravelMode.h" #include "../typedefs.h" #include @@ -44,15 +45,15 @@ struct ExtractionWay nameID = INVALID_NAMEID; path.clear(); keyVals.Clear(); - direction = ExtractionWay::notSure; - speed = -1; + forward_speed = -1; backward_speed = -1; duration = -1; - type = -1; access = true; roundabout = false; isAccessRestricted = false; ignoreInGrid = false; + forward_travel_mode = TRAVEL_MODE_DEFAULT; + backward_travel_mode = TRAVEL_MODE_DEFAULT; } enum Directions @@ -60,20 +61,70 @@ struct ExtractionWay oneway, bidirectional, opposite }; + + // These accessor methods exists to support the depreciated "way.direction" access + // in LUA. Since the direction attribute was removed from ExtractionWay, the + // accessors translate to/from the mode attributes. + inline void set_direction(const Directions m) + { + if (Directions::oneway == m) + { + forward_travel_mode = TRAVEL_MODE_DEFAULT; + backward_travel_mode = TRAVEL_MODE_INACCESSIBLE; + } + else if (Directions::opposite == m) + { + forward_travel_mode = TRAVEL_MODE_INACCESSIBLE; + backward_travel_mode = TRAVEL_MODE_DEFAULT; + } + else if (Directions::bidirectional == m) + { + forward_travel_mode = TRAVEL_MODE_DEFAULT; + backward_travel_mode = TRAVEL_MODE_DEFAULT; + } + } + + inline const Directions get_direction() const + { + if (TRAVEL_MODE_INACCESSIBLE != forward_travel_mode && TRAVEL_MODE_INACCESSIBLE != backward_travel_mode) + { + return Directions::bidirectional; + } + else if (TRAVEL_MODE_INACCESSIBLE != forward_travel_mode) + { + return Directions::oneway; + } + else if (TRAVEL_MODE_INACCESSIBLE != backward_travel_mode) + { + return Directions::opposite; + } + else + { + return Directions::notSure; + } + } + + // These accessors exists because it's not possible to take the address of a bitfield, + // and LUA therefore cannot read/write the mode attributes directly. + inline void set_forward_mode(const TravelMode m) { forward_travel_mode = m; } + inline const TravelMode get_forward_mode() const { return forward_travel_mode; } + inline void set_backward_mode(const TravelMode m) { backward_travel_mode = m; } + inline const TravelMode get_backward_mode() const { return backward_travel_mode; } + unsigned id; unsigned nameID; - double speed; + double forward_speed; double backward_speed; double duration; - Directions direction; std::string name; - short type; bool access; bool roundabout; bool isAccessRestricted; bool ignoreInGrid; std::vector path; HashTable keyVals; + TravelMode forward_travel_mode : 4; + TravelMode backward_travel_mode : 4; }; #endif // EXTRACTION_WAY_H diff --git a/3party/osrm/osrm-backend/Extractor/Extractor.cpp b/3party/osrm/osrm-backend/Extractor/Extractor.cpp index dd95685df4..0849768510 100644 --- a/3party/osrm/osrm-backend/Extractor/Extractor.cpp +++ b/3party/osrm/osrm-backend/Extractor/Extractor.cpp @@ -34,9 +34,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "XMLParser.h" #include "../Util/GitDescription.h" +#include "../Util/IniFileUtil.h" #include "../Util/OSRMException.h" -#include "../Util/ProgramOptions.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/TimingUtil.h" #include "../typedefs.h" diff --git a/3party/osrm/osrm-backend/Extractor/ExtractorCallbacks.cpp b/3party/osrm/osrm-backend/Extractor/ExtractorCallbacks.cpp index 8474c40055..16bd77aa65 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractorCallbacks.cpp +++ b/3party/osrm/osrm-backend/Extractor/ExtractorCallbacks.cpp @@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/Restriction.h" #include "../DataStructures/ImportNode.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include @@ -63,7 +63,11 @@ bool ExtractorCallbacks::ProcessRestriction(const InputRestrictionContainer &res /** warning: caller needs to take care of synchronization! */ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way) { - if ((0 >= parsed_way.speed) && (0 >= parsed_way.duration)) + if (((0 >= parsed_way.forward_speed) || + (TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode)) && + ((0 >= parsed_way.backward_speed) || + (TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode)) && + (0 >= parsed_way.duration)) { // Only true if the way is specified by the speed profile return; } @@ -84,10 +88,11 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way) { // TODO: iterate all way segments and set duration corresponding to the length of each // segment - parsed_way.speed = parsed_way.duration / (parsed_way.path.size() - 1); + parsed_way.forward_speed = parsed_way.duration / (parsed_way.path.size() - 1); + parsed_way.backward_speed = parsed_way.duration / (parsed_way.path.size() - 1); } - if (std::numeric_limits::epsilon() >= std::abs(-1. - parsed_way.speed)) + if (std::numeric_limits::epsilon() >= std::abs(-1. - parsed_way.forward_speed)) { SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << parsed_way.id; return; @@ -106,30 +111,34 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way) parsed_way.nameID = string_map_iterator->second; } - if (ExtractionWay::opposite == parsed_way.direction) + if (TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode) { std::reverse(parsed_way.path.begin(), parsed_way.path.end()); - parsed_way.direction = ExtractionWay::oneway; + parsed_way.forward_travel_mode = parsed_way.backward_travel_mode; + parsed_way.backward_travel_mode = TRAVEL_MODE_INACCESSIBLE; } const bool split_edge = - (parsed_way.backward_speed > 0) && (parsed_way.speed != parsed_way.backward_speed); + (parsed_way.forward_speed>0) && (TRAVEL_MODE_INACCESSIBLE != parsed_way.forward_travel_mode) && + (parsed_way.backward_speed>0) && (TRAVEL_MODE_INACCESSIBLE != parsed_way.backward_travel_mode) && + ((parsed_way.forward_speed != parsed_way.backward_speed) || + (parsed_way.forward_travel_mode != parsed_way.backward_travel_mode)); + BOOST_ASSERT(parsed_way.forward_travel_mode>0); for (unsigned n = 0; n < (parsed_way.path.size() - 1); ++n) { external_memory.all_edges_list.push_back(InternalExtractorEdge( - parsed_way.id, parsed_way.path[n], parsed_way.path[n + 1], - parsed_way.type, - (split_edge ? ExtractionWay::oneway : parsed_way.direction), - parsed_way.speed, + ((split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode) ? ExtractionWay::oneway + : ExtractionWay::bidirectional), + parsed_way.forward_speed, parsed_way.nameID, parsed_way.roundabout, parsed_way.ignoreInGrid, (0 < parsed_way.duration), parsed_way.isAccessRestricted, - false, + parsed_way.forward_travel_mode, split_edge)); external_memory.used_node_id_list.push_back(parsed_way.path[n]); } @@ -145,14 +154,14 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way) if (split_edge) { // Only true if the way should be split + BOOST_ASSERT(parsed_way.backward_travel_mode>0); std::reverse(parsed_way.path.begin(), parsed_way.path.end()); + for (std::vector::size_type n = 0; n < parsed_way.path.size() - 1; ++n) { external_memory.all_edges_list.push_back( - InternalExtractorEdge(parsed_way.id, - parsed_way.path[n], + InternalExtractorEdge(parsed_way.path[n], parsed_way.path[n + 1], - parsed_way.type, ExtractionWay::oneway, parsed_way.backward_speed, parsed_way.nameID, @@ -160,7 +169,7 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way) parsed_way.ignoreInGrid, (0 < parsed_way.duration), parsed_way.isAccessRestricted, - (ExtractionWay::oneway == parsed_way.direction), + parsed_way.backward_travel_mode, split_edge)); } external_memory.way_start_end_id_list.push_back( diff --git a/3party/osrm/osrm-backend/Extractor/ExtractorStructs.h b/3party/osrm/osrm-backend/Extractor/ExtractorStructs.h index 51a74c3be5..a3c6f3eaf5 100644 --- a/3party/osrm/osrm-backend/Extractor/ExtractorStructs.h +++ b/3party/osrm/osrm-backend/Extractor/ExtractorStructs.h @@ -83,7 +83,7 @@ struct WayIDStartAndEndEdge struct CmpWayByID { - typedef WayIDStartAndEndEdge value_type; + using value_type = WayIDStartAndEndEdge; bool operator()(const WayIDStartAndEndEdge &a, const WayIDStartAndEndEdge &b) const { return a.wayID < b.wayID; @@ -94,7 +94,7 @@ struct CmpWayByID struct Cmp { - typedef NodeID value_type; + using value_type = NodeID; bool operator()(const NodeID left, const NodeID right) const { return left < right; } value_type max_value() { return 0xffffffff; } value_type min_value() { return 0x0; } @@ -102,7 +102,7 @@ struct Cmp struct CmpNodeByID { - typedef ExternalMemoryNode value_type; + using value_type = ExternalMemoryNode; bool operator()(const ExternalMemoryNode &left, const ExternalMemoryNode &right) const { return left.node_id < right.node_id; diff --git a/3party/osrm/osrm-backend/Extractor/InternalExtractorEdge.h b/3party/osrm/osrm-backend/Extractor/InternalExtractorEdge.h index 32f11089f7..848b24fb34 100644 --- a/3party/osrm/osrm-backend/Extractor/InternalExtractorEdge.h +++ b/3party/osrm/osrm-backend/Extractor/InternalExtractorEdge.h @@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define INTERNAL_EXTRACTOR_EDGE_H #include "../typedefs.h" +#include "../DataStructures/TravelMode.h" #include #include @@ -36,16 +37,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. struct InternalExtractorEdge { InternalExtractorEdge() - : way_id(0), start(0), target(0), type(0), direction(0), speed(0), name_id(0), is_roundabout(false), + : start(0), target(0), direction(0), speed(0), name_id(0), is_roundabout(false), is_in_tiny_cc(false), is_duration_set(false), is_access_restricted(false), - is_contra_flow(false), is_split(false) + travel_mode(TRAVEL_MODE_INACCESSIBLE), is_split(false) { } - explicit InternalExtractorEdge(unsigned id, - NodeID start, + explicit InternalExtractorEdge(NodeID start, NodeID target, - short type, short direction, double speed, unsigned name_id, @@ -53,31 +52,28 @@ struct InternalExtractorEdge bool is_in_tiny_cc, bool is_duration_set, bool is_access_restricted, - bool is_contra_flow, + TravelMode travel_mode, bool is_split) - : way_id(id), start(start), target(target), type(type), direction(direction), speed(speed), + : start(start), target(target), direction(direction), speed(speed), name_id(name_id), is_roundabout(is_roundabout), is_in_tiny_cc(is_in_tiny_cc), is_duration_set(is_duration_set), is_access_restricted(is_access_restricted), - is_contra_flow(is_contra_flow), is_split(is_split) + travel_mode(travel_mode), is_split(is_split) { - BOOST_ASSERT(0 <= type); } // necessary static util functions for stxxl's sorting static InternalExtractorEdge min_value() { - return InternalExtractorEdge(0, 0, 0, 0, 0, 0, 0, false, false, false, false, false, false); + return InternalExtractorEdge(0, 0, 0, 0, 0, false, false, false, false, TRAVEL_MODE_INACCESSIBLE, false); } static InternalExtractorEdge max_value() { return InternalExtractorEdge( - SPECIAL_EDGEID, SPECIAL_NODEID, SPECIAL_NODEID, 0, 0, 0, 0, false, false, false, false, false, false); + SPECIAL_NODEID, SPECIAL_NODEID, 0, 0, 0, false, false, false, false, TRAVEL_MODE_INACCESSIBLE, false); } - unsigned way_id; NodeID start; NodeID target; - short type; short direction; double speed; unsigned name_id; @@ -85,7 +81,7 @@ struct InternalExtractorEdge bool is_in_tiny_cc; bool is_duration_set; bool is_access_restricted; - bool is_contra_flow; + TravelMode travel_mode : 4; bool is_split; FixedPointCoordinate source_coordinate; @@ -94,7 +90,7 @@ struct InternalExtractorEdge struct CmpEdgeByStartID { - typedef InternalExtractorEdge value_type; + using value_type = InternalExtractorEdge; bool operator()(const InternalExtractorEdge &a, const InternalExtractorEdge &b) const { return a.start < b.start; @@ -107,7 +103,7 @@ struct CmpEdgeByStartID struct CmpEdgeByTargetID { - typedef InternalExtractorEdge value_type; + using value_type = InternalExtractorEdge; bool operator()(const InternalExtractorEdge &a, const InternalExtractorEdge &b) const { diff --git a/3party/osrm/osrm-backend/Extractor/PBFParser.cpp b/3party/osrm/osrm-backend/Extractor/PBFParser.cpp index 1abc480798..fd489533f1 100644 --- a/3party/osrm/osrm-backend/Extractor/PBFParser.cpp +++ b/3party/osrm/osrm-backend/Extractor/PBFParser.cpp @@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/Restriction.h" #include "../Util/MachineInfo.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../typedefs.h" #include @@ -49,6 +49,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +#include #include #include diff --git a/3party/osrm/osrm-backend/Extractor/ScriptingEnvironment.cpp b/3party/osrm/osrm-backend/Extractor/ScriptingEnvironment.cpp index e25939fdae..3ecb0c4664 100644 --- a/3party/osrm/osrm-backend/Extractor/ScriptingEnvironment.cpp +++ b/3party/osrm/osrm-backend/Extractor/ScriptingEnvironment.cpp @@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/ImportNode.h" #include "../Util/LuaUtil.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../typedefs.h" #include @@ -76,16 +76,17 @@ void ScriptingEnvironment::initLuaState(lua_State* lua_state) // .def(luabind::constructor<>()) .def_readonly("id", &ExtractionWay::id) .def_readwrite("name", &ExtractionWay::name) - .def_readwrite("speed", &ExtractionWay::speed) + .def_readwrite("forward_speed", &ExtractionWay::forward_speed) .def_readwrite("backward_speed", &ExtractionWay::backward_speed) .def_readwrite("duration", &ExtractionWay::duration) - .def_readwrite("type", &ExtractionWay::type) .def_readwrite("access", &ExtractionWay::access) .def_readwrite("roundabout", &ExtractionWay::roundabout) .def_readwrite("is_access_restricted", &ExtractionWay::isAccessRestricted) .def_readwrite("ignore_in_grid", &ExtractionWay::ignoreInGrid) .def_readwrite("tags", &ExtractionWay::keyVals) - .def_readwrite("direction", &ExtractionWay::direction) + .property("direction", &ExtractionWay::get_direction, &ExtractionWay::set_direction) + .property("forward_mode", &ExtractionWay::get_forward_mode, &ExtractionWay::set_forward_mode) + .property("backward_mode", &ExtractionWay::get_backward_mode, &ExtractionWay::set_backward_mode) .enum_("constants")[ luabind::value("notSure", 0), luabind::value("oneway", 1), diff --git a/3party/osrm/osrm-backend/Extractor/XMLParser.cpp b/3party/osrm/osrm-backend/Extractor/XMLParser.cpp index 273ed66937..a984c76b72 100644 --- a/3party/osrm/osrm-backend/Extractor/XMLParser.cpp +++ b/3party/osrm/osrm-backend/Extractor/XMLParser.cpp @@ -34,7 +34,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/ImportNode.h" #include "../DataStructures/InputReaderFactory.h" #include "../DataStructures/Restriction.h" -#include "../Util/SimpleLogger.h" +#include "../Util/cast.hpp" +#include "../Util/simple_logger.hpp" #include "../Util/StringUtil.h" #include "../typedefs.h" @@ -168,17 +169,17 @@ InputRestrictionContainer XMLParser::ReadXMLRestriction() if (xmlStrEqual(role, (const xmlChar *)"to") && xmlStrEqual(type, (const xmlChar *)"way")) { - restriction.toWay = StringToUint((const char *)ref); + restriction.toWay = cast::string_to_uint((const char *)ref); } if (xmlStrEqual(role, (const xmlChar *)"from") && xmlStrEqual(type, (const xmlChar *)"way")) { - restriction.fromWay = StringToUint((const char *)ref); + restriction.fromWay = cast::string_to_uint((const char *)ref); } if (xmlStrEqual(role, (const xmlChar *)"via") && xmlStrEqual(type, (const xmlChar *)"node")) { - restriction.restriction.viaNode = StringToUint((const char *)ref); + restriction.restriction.viaNode = cast::string_to_uint((const char *)ref); } if (nullptr != type) @@ -231,7 +232,7 @@ ExtractionWay XMLParser::ReadXMLWay() xmlStrEqual(child_name, (const xmlChar *)"way") == 1) { xmlChar *way_id = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id"); - way.id = StringToUint((char *)way_id); + way.id = cast::string_to_uint((char *)way_id); xmlFree(way_id); xmlFree(child_name); break; @@ -265,7 +266,7 @@ ExtractionWay XMLParser::ReadXMLWay() xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref"); if (ref != nullptr) { - way.path.push_back(StringToUint((const char *)ref)); + way.path.push_back(cast::string_to_uint((const char *)ref)); xmlFree(ref); } } @@ -281,19 +282,19 @@ ImportNode XMLParser::ReadXMLNode() xmlChar *attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lat"); if (attribute != nullptr) { - node.lat = static_cast(COORDINATE_PRECISION * StringToDouble((const char *)attribute)); + node.lat = static_cast(COORDINATE_PRECISION * cast::string_to_double((const char *)attribute)); xmlFree(attribute); } attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lon"); if (attribute != nullptr) { - node.lon = static_cast(COORDINATE_PRECISION * StringToDouble((const char *)attribute)); + node.lon = static_cast(COORDINATE_PRECISION * cast::string_to_double((const char *)attribute)); xmlFree(attribute); } attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id"); if (attribute != nullptr) { - node.node_id = StringToUint((const char *)attribute); + node.node_id = cast::string_to_uint((const char *)attribute); xmlFree(attribute); } diff --git a/3party/osrm/osrm-backend/Include/osrm/Coordinate.h b/3party/osrm/osrm-backend/Include/osrm/Coordinate.h index 5426ed3a36..462ac0b63b 100644 --- a/3party/osrm/osrm-backend/Include/osrm/Coordinate.h +++ b/3party/osrm/osrm-backend/Include/osrm/Coordinate.h @@ -30,8 +30,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include //for std::ostream #include +#include -const float COORDINATE_PRECISION = 1000000.f; +constexpr float COORDINATE_PRECISION = 1000000.f; struct FixedPointCoordinate { @@ -40,6 +41,14 @@ struct FixedPointCoordinate FixedPointCoordinate(); FixedPointCoordinate(int lat, int lon); + + template + FixedPointCoordinate(const T &coordinate) : lat(coordinate.lat), lon(coordinate.lon) + { + static_assert(std::is_same::value, "coordinate types incompatible"); + static_assert(std::is_same::value, "coordinate types incompatible"); + } + void Reset(); bool isSet() const; bool isValid() const; diff --git a/3party/osrm/osrm-backend/Include/osrm/Header.h b/3party/osrm/osrm-backend/Include/osrm/Header.h index de0b2abc80..d126c4c989 100644 --- a/3party/osrm/osrm-backend/Include/osrm/Header.h +++ b/3party/osrm/osrm-backend/Include/osrm/Header.h @@ -37,7 +37,7 @@ struct Header { Header& operator=(const Header& other) = default; Header(const std::string & name, const std::string & value) : name(name), value(value) {} - Header(const Header && other) : name(std::move(other.name)), value(std::move(other.value)) {} + Header(Header && other) : name(std::move(other.name)), value(std::move(other.value)) {} void Clear() { diff --git a/3party/osrm/osrm-backend/Include/osrm/RouteParameters.h b/3party/osrm/osrm-backend/Include/osrm/RouteParameters.h index 33a8296c35..62f45148a5 100644 --- a/3party/osrm/osrm-backend/Include/osrm/RouteParameters.h +++ b/3party/osrm/osrm-backend/Include/osrm/RouteParameters.h @@ -41,6 +41,8 @@ struct RouteParameters void setZoomLevel(const short level); + void setNumberOfResults(const short number); + void setAlternateRouteFlag(const bool flag); void setUTurn(const bool flag); @@ -77,6 +79,7 @@ struct RouteParameters bool deprecatedAPI; bool uturn_default; unsigned check_sum; + short num_results; std::string service; std::string output_format; std::string jsonp_parameter; diff --git a/3party/osrm/osrm-backend/Library/OSRM.h b/3party/osrm/osrm-backend/Library/OSRM.h index 16b9977cc0..372e82c391 100644 --- a/3party/osrm/osrm-backend/Library/OSRM.h +++ b/3party/osrm/osrm-backend/Library/OSRM.h @@ -30,6 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include +#include + class OSRM_impl; struct RouteParameters; @@ -41,10 +43,10 @@ class Reply; class OSRM { private: - OSRM_impl *OSRM_pimpl_; + std::unique_ptr OSRM_pimpl_; public: - explicit OSRM(const ServerPaths &paths, const bool use_shared_memory = false); + explicit OSRM(ServerPaths paths, const bool use_shared_memory = false); ~OSRM(); void RunQuery(RouteParameters &route_parameters, http::Reply &reply); }; diff --git a/3party/osrm/osrm-backend/Library/OSRM_impl.cpp b/3party/osrm/osrm-backend/Library/OSRM_impl.cpp index 5c20b5aefd..c5417187be 100644 --- a/3party/osrm/osrm-backend/Library/OSRM_impl.cpp +++ b/3party/osrm/osrm-backend/Library/OSRM_impl.cpp @@ -45,7 +45,9 @@ namespace boost { namespace interprocess { class named_mutex; } } #include "../Server/DataStructures/InternalDataFacade.h" #include "../Server/DataStructures/SharedBarriers.h" #include "../Server/DataStructures/SharedDataFacade.h" -#include "../Util/SimpleLogger.h" +#include "../Util/make_unique.hpp" +#include "../Util/ProgramOptions.h" +#include "../Util/simple_logger.hpp" #include #include @@ -56,16 +58,17 @@ namespace boost { namespace interprocess { class named_mutex; } } #include #include -OSRM_impl::OSRM_impl(const ServerPaths &server_paths, const bool use_shared_memory) - : use_shared_memory(use_shared_memory) +OSRM_impl::OSRM_impl(ServerPaths server_paths, const bool use_shared_memory) { if (use_shared_memory) { - barrier = new SharedBarriers(); + barrier = osrm::make_unique(); query_data_facade = new SharedDataFacade(); } else { + // populate base path + populate_base_path(server_paths); query_data_facade = new InternalDataFacade(server_paths); } @@ -85,10 +88,6 @@ OSRM_impl::~OSRM_impl() { delete plugin_pointer.second; } - if (use_shared_memory) - { - delete barrier; - } } void OSRM_impl::RegisterPlugin(BasePlugin *plugin) @@ -108,7 +107,7 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply) if (plugin_map.end() != iter) { reply.status = http::Reply::ok; - if (use_shared_memory) + if (barrier) { // lock update pending boost::interprocess::scoped_lock pending_lock( @@ -129,7 +128,7 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply) } iter->second->HandleRequest(route_parameters, reply); - if (use_shared_memory) + if (barrier) { // lock query boost::interprocess::scoped_lock query_lock( @@ -154,12 +153,12 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply) // proxy code for compilation firewall -OSRM::OSRM(const ServerPaths &paths, const bool use_shared_memory) - : OSRM_pimpl_(new OSRM_impl(paths, use_shared_memory)) +OSRM::OSRM(ServerPaths paths, const bool use_shared_memory) + : OSRM_pimpl_(osrm::make_unique(paths, use_shared_memory)) { } -OSRM::~OSRM() { delete OSRM_pimpl_; } +OSRM::~OSRM() { OSRM_pimpl_.reset(); } void OSRM::RunQuery(RouteParameters &route_parameters, http::Reply &reply) { diff --git a/3party/osrm/osrm-backend/Library/OSRM_impl.h b/3party/osrm/osrm-backend/Library/OSRM_impl.h index 8ad98bbda5..a4af62cb65 100644 --- a/3party/osrm/osrm-backend/Library/OSRM_impl.h +++ b/3party/osrm/osrm-backend/Library/OSRM_impl.h @@ -36,6 +36,7 @@ struct RouteParameters; #include "../DataStructures/QueryEdge.h" +#include #include #include @@ -45,10 +46,10 @@ template class BaseDataFacade; class OSRM_impl { private: - typedef std::unordered_map PluginMap; + using PluginMap = std::unordered_map; public: - OSRM_impl(const ServerPaths &paths, const bool use_shared_memory); + OSRM_impl(ServerPaths paths, const bool use_shared_memory); OSRM_impl(const OSRM_impl &) = delete; virtual ~OSRM_impl(); void RunQuery(RouteParameters &route_parameters, http::Reply &reply); @@ -56,8 +57,8 @@ class OSRM_impl private: void RegisterPlugin(BasePlugin *plugin); PluginMap plugin_map; - bool use_shared_memory; - SharedBarriers *barrier; + // will only be initialized if shared memory is used + std::unique_ptr barrier; // base class pointer to the objects BaseDataFacade *query_data_facade; }; diff --git a/3party/osrm/osrm-backend/Plugins/DistanceTablePlugin.h b/3party/osrm/osrm-backend/Plugins/DistanceTablePlugin.h index d3e307b54b..715c4f52cf 100644 --- a/3party/osrm/osrm-backend/Plugins/DistanceTablePlugin.h +++ b/3party/osrm/osrm-backend/Plugins/DistanceTablePlugin.h @@ -35,7 +35,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/QueryEdge.h" #include "../DataStructures/SearchEngine.h" #include "../Descriptors/BaseDescriptor.h" -#include "../Util/SimpleLogger.h" +#include "../Util/make_unique.hpp" #include "../Util/StringUtil.h" #include "../Util/TimingUtil.h" @@ -47,22 +47,22 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -template class DistanceTablePlugin : public BasePlugin +template class DistanceTablePlugin final : public BasePlugin { private: - std::shared_ptr> search_engine_ptr; + std::unique_ptr> search_engine_ptr; public: explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade) { - search_engine_ptr = std::make_shared>(facade); + search_engine_ptr = osrm::make_unique>(facade); } virtual ~DistanceTablePlugin() {} - const std::string GetDescriptor() const { return descriptor_string; } + const std::string GetDescriptor() const final { return descriptor_string; } - void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) + void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { // check number of parameters if (2 > route_parameters.coordinates.size()) @@ -77,7 +77,9 @@ template class DistanceTablePlugin : public BasePlugin if (std::any_of(begin(route_parameters.coordinates), end(route_parameters.coordinates), [&](FixedPointCoordinate coordinate) - { return !coordinate.isValid(); })) + { + return !coordinate.isValid(); + })) { reply = http::Reply::StockReply(http::Reply::badRequest); return; @@ -98,7 +100,7 @@ template class DistanceTablePlugin : public BasePlugin !route_parameters.hints[i].empty()) { PhantomNode current_phantom_node; - DecodeObjectFromBase64(route_parameters.hints[i], current_phantom_node); + ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); if (current_phantom_node.isValid(facade->GetNumberOfNodes())) { phantom_node_vector[i].emplace_back(std::move(current_phantom_node)); diff --git a/3party/osrm/osrm-backend/Plugins/HelloWorldPlugin.h b/3party/osrm/osrm-backend/Plugins/HelloWorldPlugin.h index 2d99a1093f..d9b4a8d0e2 100644 --- a/3party/osrm/osrm-backend/Plugins/HelloWorldPlugin.h +++ b/3party/osrm/osrm-backend/Plugins/HelloWorldPlugin.h @@ -30,11 +30,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BasePlugin.h" #include "../DataStructures/JSONContainer.h" -#include "../Util/StringUtil.h" +#include "../Util/cast.hpp" #include -class HelloWorldPlugin : public BasePlugin +class HelloWorldPlugin final : public BasePlugin { private: std::string temp_string; @@ -42,9 +42,9 @@ class HelloWorldPlugin : public BasePlugin public: HelloWorldPlugin() : descriptor_string("hello") {} virtual ~HelloWorldPlugin() {} - const std::string GetDescriptor() const { return descriptor_string; } + const std::string GetDescriptor() const final { return descriptor_string; } - void HandleRequest(const RouteParameters &routeParameters, http::Reply &reply) + void HandleRequest(const RouteParameters &routeParameters, http::Reply &reply) final { reply.status = http::Reply::ok; @@ -52,20 +52,22 @@ class HelloWorldPlugin : public BasePlugin std::string temp_string; json_result.values["title"] = "Hello World"; - temp_string = IntToString(routeParameters.zoom_level); + temp_string = cast::integral_to_string(routeParameters.zoom_level); json_result.values["zoom_level"] = temp_string; - temp_string = UintToString(routeParameters.check_sum); + temp_string = cast::integral_to_string(routeParameters.check_sum); json_result.values["check_sum"] = temp_string; json_result.values["instructions"] = (routeParameters.print_instructions ? "yes" : "no"); json_result.values["geometry"] = (routeParameters.geometry ? "yes" : "no"); json_result.values["compression"] = (routeParameters.compression ? "yes" : "no"); - json_result.values["output_format"] = (!routeParameters.output_format.empty() ? "yes" : "no"); + json_result.values["output_format"] = + (!routeParameters.output_format.empty() ? "yes" : "no"); - json_result.values["jsonp_parameter"] = (!routeParameters.jsonp_parameter.empty() ? "yes" : "no"); + json_result.values["jsonp_parameter"] = + (!routeParameters.jsonp_parameter.empty() ? "yes" : "no"); json_result.values["language"] = (!routeParameters.language.empty() ? "yes" : "no"); - temp_string = UintToString(static_cast(routeParameters.coordinates.size())); + temp_string = cast::integral_to_string(routeParameters.coordinates.size()); json_result.values["location_count"] = temp_string; JSON::Array json_locations; @@ -77,7 +79,7 @@ class HelloWorldPlugin : public BasePlugin json_coordinates.values.push_back(coordinate.lat / COORDINATE_PRECISION); json_coordinates.values.push_back(coordinate.lon / COORDINATE_PRECISION); - json_location.values[UintToString(counter)] = json_coordinates; + json_location.values[cast::integral_to_string(counter)] = json_coordinates; json_locations.values.push_back(json_location); ++counter; } diff --git a/3party/osrm/osrm-backend/Plugins/LocatePlugin.h b/3party/osrm/osrm-backend/Plugins/LocatePlugin.h index 518259d704..1701bbe15a 100644 --- a/3party/osrm/osrm-backend/Plugins/LocatePlugin.h +++ b/3party/osrm/osrm-backend/Plugins/LocatePlugin.h @@ -35,17 +35,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // locates the nearest node in the road network for a given coordinate. -template class LocatePlugin : public BasePlugin +template class LocatePlugin final : public BasePlugin { public: explicit LocatePlugin(DataFacadeT *facade) : descriptor_string("locate"), facade(facade) {} - const std::string GetDescriptor() const { return descriptor_string; } + const std::string GetDescriptor() const final { return descriptor_string; } - void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) + void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { // check number of parameters - if (route_parameters.coordinates.empty() || - !route_parameters.coordinates.front().isValid()) + if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().isValid()) { reply = http::Reply::StockReply(http::Reply::badRequest); return; @@ -63,8 +62,8 @@ template class LocatePlugin : public BasePlugin reply.status = http::Reply::ok; json_result.values["status"] = 0; JSON::Array json_coordinate; - json_coordinate.values.push_back(result.lat/COORDINATE_PRECISION); - json_coordinate.values.push_back(result.lon/COORDINATE_PRECISION); + json_coordinate.values.push_back(result.lat / COORDINATE_PRECISION); + json_coordinate.values.push_back(result.lon / COORDINATE_PRECISION); json_result.values["mapped_coordinate"] = json_coordinate; } diff --git a/3party/osrm/osrm-backend/Plugins/NearestPlugin.h b/3party/osrm/osrm-backend/Plugins/NearestPlugin.h index 27bd01692b..e4fec91c19 100644 --- a/3party/osrm/osrm-backend/Plugins/NearestPlugin.h +++ b/3party/osrm/osrm-backend/Plugins/NearestPlugin.h @@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BasePlugin.h" #include "../DataStructures/JSONContainer.h" #include "../DataStructures/PhantomNodes.h" +#include "../DataStructures/Range.h" #include @@ -38,14 +39,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * This Plugin locates the nearest point on a street in the road network for a given coordinate. */ -template class NearestPlugin : public BasePlugin +template class NearestPlugin final : public BasePlugin { public: explicit NearestPlugin(DataFacadeT *facade) : facade(facade), descriptor_string("nearest") {} - const std::string GetDescriptor() const { return descriptor_string; } + const std::string GetDescriptor() const final { return descriptor_string; } - void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) + void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { // check number of parameters if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().isValid()) @@ -53,12 +54,12 @@ template class NearestPlugin : public BasePlugin reply = http::Reply::StockReply(http::Reply::badRequest); return; } - + auto number_of_results = static_cast(route_parameters.num_results); std::vector phantom_node_vector; facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates.front(), phantom_node_vector, route_parameters.zoom_level, - 1); + static_cast(number_of_results)); JSON::Object json_result; if (phantom_node_vector.empty() || !phantom_node_vector.front().isValid()) @@ -69,17 +70,41 @@ template class NearestPlugin : public BasePlugin { reply.status = http::Reply::ok; json_result.values["status"] = 0; - JSON::Array json_coordinate; - json_coordinate.values.push_back(phantom_node_vector.front().location.lat / - COORDINATE_PRECISION); - json_coordinate.values.push_back(phantom_node_vector.front().location.lon / - COORDINATE_PRECISION); - json_result.values["mapped_coordinate"] = json_coordinate; - std::string temp_string; - facade->GetName(phantom_node_vector.front().name_id, temp_string); - json_result.values["name"] = temp_string; - } + if (number_of_results > 1) + { + JSON::Array results; + + auto vector_length = phantom_node_vector.size(); + for (const auto i : osrm::irange(0, std::min(number_of_results, vector_length))) + { + JSON::Array json_coordinate; + JSON::Object result; + json_coordinate.values.push_back(phantom_node_vector.at(i).location.lat / + COORDINATE_PRECISION); + json_coordinate.values.push_back(phantom_node_vector.at(i).location.lon / + COORDINATE_PRECISION); + result.values["mapped coordinate"] = json_coordinate; + std::string temp_string; + facade->GetName(phantom_node_vector.front().name_id, temp_string); + result.values["name"] = temp_string; + results.values.push_back(result); + } + json_result.values["results"] = results; + } + else + { + JSON::Array json_coordinate; + json_coordinate.values.push_back(phantom_node_vector.front().location.lat / + COORDINATE_PRECISION); + json_coordinate.values.push_back(phantom_node_vector.front().location.lon / + COORDINATE_PRECISION); + json_result.values["mapped_coordinate"] = json_coordinate; + std::string temp_string; + facade->GetName(phantom_node_vector.front().name_id, temp_string); + json_result.values["name"] = temp_string; + } + } JSON::render(reply.content, json_result); } diff --git a/3party/osrm/osrm-backend/Plugins/TimestampPlugin.h b/3party/osrm/osrm-backend/Plugins/TimestampPlugin.h index 63f63b2db0..0047db199b 100644 --- a/3party/osrm/osrm-backend/Plugins/TimestampPlugin.h +++ b/3party/osrm/osrm-backend/Plugins/TimestampPlugin.h @@ -33,15 +33,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -template class TimestampPlugin : public BasePlugin +template class TimestampPlugin final : public BasePlugin { public: explicit TimestampPlugin(const DataFacadeT *facade) : facade(facade), descriptor_string("timestamp") { } - const std::string GetDescriptor() const { return descriptor_string; } - void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) + const std::string GetDescriptor() const final { return descriptor_string; } + void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { reply.status = http::Reply::ok; JSON::Object json_result; diff --git a/3party/osrm/osrm-backend/Plugins/ViaRoutePlugin.h b/3party/osrm/osrm-backend/Plugins/ViaRoutePlugin.h index 491fff08f4..7bd4b70ecd 100644 --- a/3party/osrm/osrm-backend/Plugins/ViaRoutePlugin.h +++ b/3party/osrm/osrm-backend/Plugins/ViaRoutePlugin.h @@ -31,13 +31,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BasePlugin.h" #include "../Algorithms/ObjectToBase64.h" - #include "../DataStructures/QueryEdge.h" #include "../DataStructures/SearchEngine.h" #include "../Descriptors/BaseDescriptor.h" #include "../Descriptors/GPXDescriptor.h" #include "../Descriptors/JSONDescriptor.h" -#include "../Util/SimpleLogger.h" +#include "../Util/make_unique.hpp" +#include "../Util/simple_logger.hpp" #include "../Util/StringUtil.h" #include "../Util/TimingUtil.h" @@ -49,16 +49,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -template class ViaRoutePlugin : public BasePlugin +template class ViaRoutePlugin final : public BasePlugin { private: std::unordered_map descriptor_table; - std::shared_ptr> search_engine_ptr; + std::unique_ptr> search_engine_ptr; public: explicit ViaRoutePlugin(DataFacadeT *facade) : descriptor_string("viaroute"), facade(facade) { - search_engine_ptr = std::make_shared>(facade); + search_engine_ptr = osrm::make_unique>(facade); descriptor_table.emplace("json", 0); descriptor_table.emplace("gpx", 1); @@ -67,16 +67,18 @@ template class ViaRoutePlugin : public BasePlugin virtual ~ViaRoutePlugin() {} - const std::string GetDescriptor() const { return descriptor_string; } + const std::string GetDescriptor() const final { return descriptor_string; } - void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) + void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final { // check number of parameters if (2 > route_parameters.coordinates.size() || std::any_of(begin(route_parameters.coordinates), end(route_parameters.coordinates), [&](FixedPointCoordinate coordinate) - { return !coordinate.isValid(); })) + { + return !coordinate.isValid(); + })) { reply = http::Reply::StockReply(http::Reply::badRequest); return; @@ -97,7 +99,7 @@ template class ViaRoutePlugin : public BasePlugin if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { - DecodeObjectFromBase64(route_parameters.hints[i], phantom_node_vector[i]); + ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], phantom_node_vector[i]); if (phantom_node_vector[i].isValid(facade->GetNumberOfNodes())) { continue; @@ -125,7 +127,8 @@ template class ViaRoutePlugin : public BasePlugin } else { - search_engine_ptr->shortest_path(raw_route.segment_end_coordinates, route_parameters.uturns, raw_route); + search_engine_ptr->shortest_path( + raw_route.segment_end_coordinates, route_parameters.uturns, raw_route); } if (INVALID_EDGE_WEIGHT == raw_route.shortest_path_length) diff --git a/3party/osrm/osrm-backend/README.md b/3party/osrm/osrm-backend/README.md index 442ccf906a..624cc1da77 100644 --- a/3party/osrm/osrm-backend/README.md +++ b/3party/osrm/osrm-backend/README.md @@ -36,6 +36,6 @@ When using the code in a (scientific) publication, please cite | build config | branch | status | |:-------------|:--------|:------------| | Linux | master | [![Build Status](https://travis-ci.org/Project-OSRM/osrm-backend.png?branch=master)](https://travis-ci.org/DennisOSRM/Project-OSRM) | -| Lunux | develop | [![Build Status](https://travis-ci.org/Project-OSRM/osrm-backend.png?branch=develop)](https://travis-ci.org/DennisOSRM/Project-OSRM) | +| Linux | develop | [![Build Status](https://travis-ci.org/Project-OSRM/osrm-backend.png?branch=develop)](https://travis-ci.org/DennisOSRM/Project-OSRM) | | Windows | master/develop | [![Build status](https://ci.appveyor.com/api/projects/status/4iuo3s9gxprmcjjh)](https://ci.appveyor.com/project/DennisOSRM/osrm-backend) | | LUAbind fork | master | [![Build Status](https://travis-ci.org/DennisOSRM/luabind.png?branch=master)](https://travis-ci.org/DennisOSRM/luabind) | diff --git a/3party/osrm/osrm-backend/Rakefile b/3party/osrm/osrm-backend/Rakefile index 006961ebc5..562823b8ae 100644 --- a/3party/osrm/osrm-backend/Rakefile +++ b/3party/osrm/osrm-backend/Rakefile @@ -6,7 +6,7 @@ require 'sys/proctable' BUILD_FOLDER = 'build' DATA_FOLDER = 'sandbox' -PROFILE = 'examples/postgis' +PROFILE = 'bicycle' OSRM_PORT = 5000 PROFILES_FOLDER = '../profiles' @@ -181,3 +181,9 @@ end desc "Stop, reprocess and restart." task :update => [:down,:process,:up] do end + + +desc "Remove test cache files." +task :sweep do + system "rm test/cache/*" +end diff --git a/3party/osrm/osrm-backend/RoutingAlgorithms/AlternativePathRouting.h b/3party/osrm/osrm-backend/RoutingAlgorithms/AlternativePathRouting.h index 897def587c..83875f3d04 100644 --- a/3party/osrm/osrm-backend/RoutingAlgorithms/AlternativePathRouting.h +++ b/3party/osrm/osrm-backend/RoutingAlgorithms/AlternativePathRouting.h @@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BasicRoutingInterface.h" #include "../DataStructures/Range.h" #include "../DataStructures/SearchEngineData.h" +#include "../Util/container.hpp" #include @@ -43,12 +44,12 @@ 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. -template class AlternativeRouting : private BasicRoutingInterface +template class AlternativeRouting final : private BasicRoutingInterface { - typedef BasicRoutingInterface super; - typedef typename DataFacadeT::EdgeData EdgeData; - typedef SearchEngineData::QueryHeap QueryHeap; - typedef std::pair SearchSpaceEdge; + using super = BasicRoutingInterface; + using EdgeData = typename DataFacadeT::EdgeData; + using QueryHeap = SearchEngineData::QueryHeap; + using SearchSpaceEdge = std::pair; struct RankedCandidateNode { @@ -172,7 +173,7 @@ template class AlternativeRouting : private BasicRoutingInte return; } - sort_unique_resize(via_node_candidate_list); + osrm::sort_unique_resize(via_node_candidate_list); std::vector packed_forward_path; std::vector packed_reverse_path; diff --git a/3party/osrm/osrm-backend/RoutingAlgorithms/BasicRoutingInterface.h b/3party/osrm/osrm-backend/RoutingAlgorithms/BasicRoutingInterface.h index c7491bd024..72f1155e54 100644 --- a/3party/osrm/osrm-backend/RoutingAlgorithms/BasicRoutingInterface.h +++ b/3party/osrm/osrm-backend/RoutingAlgorithms/BasicRoutingInterface.h @@ -31,8 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/RawRouteData.h" #include "../DataStructures/SearchEngineData.h" #include "../DataStructures/TurnInstructions.h" -#include "../Util/ContainerUtils.h" -#include "../Util/SimpleLogger.h" +// #include "../Util/simple_logger.hpp.h" #include @@ -98,7 +97,7 @@ template class BasicRoutingInterface // Stalling for (const auto edge : facade->GetAdjacentEdgeRange(node)) { - const EdgeData &data = facade->GetEdgeData(edge, node); + const EdgeData &data = facade->GetEdgeData(edge); const bool reverse_flag = ((!forward_direction) ? data.forward : data.backward); if (reverse_flag) { @@ -119,7 +118,7 @@ template class BasicRoutingInterface for (const auto edge : facade->GetAdjacentEdgeRange(node)) { - const EdgeData &data = facade->GetEdgeData(edge, node); + const EdgeData &data = facade->GetEdgeData(edge); bool forward_directionFlag = (forward_direction ? data.forward : data.backward); if (forward_directionFlag) { @@ -164,7 +163,6 @@ template class BasicRoutingInterface recursion_stack.emplace(packed_path[i - 1], packed_path[i]); } - unpacked_path.emplace_back(packed_path[0], INVALID_EDGE_WEIGHT, TurnInstruction::NoTurn, INVALID_EDGE_WEIGHT); std::pair edge; while (!recursion_stack.empty()) { @@ -181,17 +179,14 @@ template class BasicRoutingInterface // facade->FindEdge does not suffice here in case of shortcuts. // The above explanation unclear? Think! EdgeID smaller_edge_id = SPECIAL_EDGEID; - NodeID smaller_node_id = SPECIAL_NODEID; int edge_weight = std::numeric_limits::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { - auto const & edgeData = facade->GetEdgeData(edge_id, edge.first); - const int weight = edgeData.distance; + const int weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && - edgeData.forward) + facade->GetEdgeData(edge_id).forward) { smaller_edge_id = edge_id; - smaller_node_id = edge.first; edge_weight = weight; } } @@ -207,20 +202,18 @@ template class BasicRoutingInterface { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { - auto const & edgeData = facade->GetEdgeData(edge_id, edge.second); - const int weight = edgeData.distance; + const int weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && - edgeData.backward) + facade->GetEdgeData(edge_id).backward) { smaller_edge_id = edge_id; - smaller_node_id = edge.second; edge_weight = weight; } } } BOOST_ASSERT_MSG(edge_weight != INVALID_EDGE_WEIGHT, "edge id invalid"); - const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id); + const EdgeData &ed = facade->GetEdgeData(smaller_edge_id); if (ed.shortcut) { // unpack const NodeID middle_node_id = ed.id; @@ -230,91 +223,91 @@ template class BasicRoutingInterface } else { - unpacked_path.emplace_back(edge.second, - INVALID_EDGE_WEIGHT, - TurnInstruction::NoTurn, - ed.distance); -// 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); + 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); -// if (!facade->EdgeIsCompressed(ed.id)) -// { -// BOOST_ASSERT(!facade->EdgeIsCompressed(ed.id)); -// unpacked_path.emplace_back(facade->GetGeometryIndexForEdgeID(ed.id), -// name_index, -// turn_instruction, -// ed.distance); -// } -// else -// { -// std::vector id_vector; -// facade->GetUncompressedGeometry(facade->GetGeometryIndexForEdgeID(ed.id), -// id_vector); -// const std::size_t start_index = -// (unpacked_path.empty() -// ? ((start_traversed_in_reverse) -// ? id_vector.size() - -// phantom_node_pair.source_phantom.fwd_segment_position - 1 -// : phantom_node_pair.source_phantom.fwd_segment_position) -// : 0); -// const std::size_t end_index = id_vector.size(); + if (!facade->EdgeIsCompressed(ed.id)) + { + BOOST_ASSERT(!facade->EdgeIsCompressed(ed.id)); + unpacked_path.emplace_back(facade->GetGeometryIndexForEdgeID(ed.id), + name_index, + turn_instruction, + ed.distance, + travel_mode); + } + else + { + std::vector id_vector; + facade->GetUncompressedGeometry(facade->GetGeometryIndexForEdgeID(ed.id), + id_vector); -// BOOST_ASSERT(start_index >= 0); -// BOOST_ASSERT(start_index <= end_index); -// for (std::size_t i = start_index; i < end_index; ++i) -// { -// unpacked_path.emplace_back(id_vector[i], name_index, TurnInstruction::NoTurn, 0); -// } -// unpacked_path.back().turn_instruction = turn_instruction; -// unpacked_path.back().segment_duration = ed.distance; -// } + const std::size_t start_index = + (unpacked_path.empty() + ? ((start_traversed_in_reverse) + ? id_vector.size() - + phantom_node_pair.source_phantom.fwd_segment_position - 1 + : phantom_node_pair.source_phantom.fwd_segment_position) + : 0); + const std::size_t end_index = id_vector.size(); + + BOOST_ASSERT(start_index >= 0); + BOOST_ASSERT(start_index <= end_index); + 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); + } + unpacked_path.back().turn_instruction = turn_instruction; + unpacked_path.back().segment_duration = ed.distance; + } } } -// if (SPECIAL_EDGEID != phantom_node_pair.target_phantom.packed_geometry_id) -// { -// std::vector id_vector; -// facade->GetUncompressedGeometry(phantom_node_pair.target_phantom.packed_geometry_id, -// id_vector); -// const bool is_local_path = (phantom_node_pair.source_phantom.packed_geometry_id == -// phantom_node_pair.target_phantom.packed_geometry_id) && -// unpacked_path.empty(); + if (SPECIAL_EDGEID != phantom_node_pair.target_phantom.packed_geometry_id) + { + std::vector id_vector; + facade->GetUncompressedGeometry(phantom_node_pair.target_phantom.packed_geometry_id, + id_vector); + const bool is_local_path = (phantom_node_pair.source_phantom.packed_geometry_id == + phantom_node_pair.target_phantom.packed_geometry_id) && + unpacked_path.empty(); -// std::size_t start_index = 0; -// if (is_local_path) -// { -// start_index = phantom_node_pair.source_phantom.fwd_segment_position; -// if (target_traversed_in_reverse) -// { -// start_index = -// id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position; -// } -// } + std::size_t start_index = 0; + if (is_local_path) + { + start_index = phantom_node_pair.source_phantom.fwd_segment_position; + if (target_traversed_in_reverse) + { + start_index = + id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position; + } + } -// std::size_t end_index = phantom_node_pair.target_phantom.fwd_segment_position; -// if (target_traversed_in_reverse) -// { -// std::reverse(id_vector.begin(), id_vector.end()); -// end_index = -// id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position; -// } + std::size_t end_index = phantom_node_pair.target_phantom.fwd_segment_position; + if (target_traversed_in_reverse) + { + std::reverse(id_vector.begin(), id_vector.end()); + end_index = + id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position; + } -// if (start_index > end_index) -// { -// start_index = std::min(start_index, id_vector.size()-1); -// } + if (start_index > end_index) + { + start_index = std::min(start_index, id_vector.size()-1); + } -// SimpleLogger().Write() << "start_index: " << start_index << ", end_index: " << end_index; -// for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i)) -// { -// BOOST_ASSERT(i < id_vector.size()); -// unpacked_path.emplace_back(PathData{id_vector[i], -// phantom_node_pair.target_phantom.name_id, -// TurnInstruction::NoTurn, -// 0}); -// } -// } + for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i)) + { + 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, + 0, + phantom_node_pair.target_phantom.forward_travel_mode}); + } + } // there is no equivalent to a node-based node in an edge-expanded graph. // two equivalent routes may start (or end) at different node-based edges @@ -349,17 +342,14 @@ template class BasicRoutingInterface recursion_stack.pop(); EdgeID smaller_edge_id = SPECIAL_EDGEID; - NodeID smaller_node_id = SPECIAL_NODEID; int edge_weight = std::numeric_limits::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { - auto const & edgeData = facade->GetEdgeData(edge_id, edge.first); - const int weight = edgeData.distance; + const int weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && - edgeData.forward) + facade->GetEdgeData(edge_id).forward) { smaller_edge_id = edge_id; - smaller_node_id = edge.first; edge_weight = weight; } } @@ -368,20 +358,18 @@ template class BasicRoutingInterface { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { - auto const & edgeData = facade->GetEdgeData(edge_id, edge.second); - const int weight = edgeData.distance; + const int weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && - edgeData.backward) + facade->GetEdgeData(edge_id).backward) { smaller_edge_id = edge_id; - smaller_node_id = edge.second; edge_weight = weight; } } } BOOST_ASSERT_MSG(edge_weight != std::numeric_limits::max(), "edge weight invalid"); - const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id); + const EdgeData &ed = facade->GetEdgeData(smaller_edge_id); if (ed.shortcut) { // unpack const NodeID middle_node_id = ed.id; diff --git a/3party/osrm/osrm-backend/RoutingAlgorithms/ManyToManyRouting.h b/3party/osrm/osrm-backend/RoutingAlgorithms/ManyToManyRouting.h index 7819c676d6..6761c25ca8 100644 --- a/3party/osrm/osrm-backend/RoutingAlgorithms/ManyToManyRouting.h +++ b/3party/osrm/osrm-backend/RoutingAlgorithms/ManyToManyRouting.h @@ -39,10 +39,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -template class ManyToManyRouting : public BasicRoutingInterface +template class ManyToManyRouting final : public BasicRoutingInterface { - typedef BasicRoutingInterface super; - typedef SearchEngineData::QueryHeap QueryHeap; + using super = BasicRoutingInterface; + using QueryHeap = SearchEngineData::QueryHeap; SearchEngineData &engine_working_data; struct NodeBucket @@ -54,7 +54,7 @@ template class ManyToManyRouting : public BasicRoutingInterf { } }; - typedef std::unordered_map> SearchSpaceWithBuckets; + using SearchSpaceWithBuckets = std::unordered_map>; public: ManyToManyRouting(DataFacadeT *facade, SearchEngineData &engine_working_data) diff --git a/3party/osrm/osrm-backend/RoutingAlgorithms/ShortestPathRouting.h b/3party/osrm/osrm-backend/RoutingAlgorithms/ShortestPathRouting.h index 997cc644ef..4670eedf57 100644 --- a/3party/osrm/osrm-backend/RoutingAlgorithms/ShortestPathRouting.h +++ b/3party/osrm/osrm-backend/RoutingAlgorithms/ShortestPathRouting.h @@ -35,10 +35,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/SearchEngineData.h" #include "../typedefs.h" -template class ShortestPathRouting : public BasicRoutingInterface +template class ShortestPathRouting final : public BasicRoutingInterface { - typedef BasicRoutingInterface super; - typedef SearchEngineData::QueryHeap QueryHeap; + using super = BasicRoutingInterface; + using QueryHeap = SearchEngineData::QueryHeap; SearchEngineData &engine_working_data; public: diff --git a/3party/osrm/osrm-backend/Server/APIGrammar.h b/3party/osrm/osrm-backend/Server/APIGrammar.h index ddf53ce719..83a5cd03b3 100644 --- a/3party/osrm/osrm-backend/Server/APIGrammar.h +++ b/3party/osrm/osrm-backend/Server/APIGrammar.h @@ -40,7 +40,7 @@ struct APIGrammar : qi::grammar explicit APIGrammar(HandlerT * h) : APIGrammar::base_type(api_call), handler(h) { api_call = qi::lit('/') >> string[boost::bind(&HandlerT::setService, handler, ::_1)] >> *(query) >> -(uturns); - query = ('?') >> (+(zoom | output | jsonp | checksum | location | hint | u | cmp | language | instruction | geometry | alt_route | old_API)); + query = ('?') >> (+(zoom | output | jsonp | checksum | location | hint | u | cmp | language | instruction | geometry | alt_route | old_API | num_results) ) ; zoom = (-qi::lit('&')) >> qi::lit('z') >> '=' >> qi::short_[boost::bind(&HandlerT::setZoomLevel, handler, ::_1)]; output = (-qi::lit('&')) >> qi::lit("output") >> '=' >> string[boost::bind(&HandlerT::setOutputFormat, handler, ::_1)]; @@ -56,6 +56,7 @@ struct APIGrammar : qi::grammar language = (-qi::lit('&')) >> qi::lit("hl") >> '=' >> string[boost::bind(&HandlerT::setLanguage, handler, ::_1)]; alt_route = (-qi::lit('&')) >> qi::lit("alt") >> '=' >> qi::bool_[boost::bind(&HandlerT::setAlternateRouteFlag, handler, ::_1)]; old_API = (-qi::lit('&')) >> qi::lit("geomformat") >> '=' >> string[boost::bind(&HandlerT::setDeprecatedAPIFlag, handler, ::_1)]; + num_results = (-qi::lit('&')) >> qi::lit("num_results") >> '=' >> qi::short_[boost::bind(&HandlerT::setNumberOfResults, handler, ::_1)]; string = +(qi::char_("a-zA-Z")); stringwithDot = +(qi::char_("a-zA-Z0-9_.-")); @@ -65,7 +66,7 @@ struct APIGrammar : qi::grammar qi::rule api_call, query; qi::rule service, zoom, output, string, jsonp, checksum, location, hint, stringwithDot, stringwithPercent, language, instruction, geometry, - cmp, alt_route, u, uturns, old_API ; + cmp, alt_route, u, uturns, old_API, num_results; HandlerT * handler; }; diff --git a/3party/osrm/osrm-backend/Server/DataStructures/BaseDataFacade.h b/3party/osrm/osrm-backend/Server/DataStructures/BaseDataFacade.h index 11e5dc30d3..f4a4fe18b0 100644 --- a/3party/osrm/osrm-backend/Server/DataStructures/BaseDataFacade.h +++ b/3party/osrm/osrm-backend/Server/DataStructures/BaseDataFacade.h @@ -39,7 +39,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../../Util/StringUtil.h" #include "../../typedefs.h" -#include "../../Include/osrm/Coordinate.h" +#include #include @@ -62,7 +62,7 @@ template class BaseDataFacade virtual NodeID GetTarget(const EdgeID e) const = 0; - virtual EdgeDataT &GetEdgeData(const EdgeID e) = 0; + // virtual EdgeDataT &GetEdgeData(const EdgeID e) = 0; virtual EdgeDataT GetEdgeData(const EdgeID e, NodeID node) { @@ -70,8 +70,6 @@ template class BaseDataFacade return edge; } - // virtual const EdgeDataT &GetEdgeData( const EdgeID e ) const = 0; - virtual EdgeID BeginEdges(const NodeID n) const = 0; virtual EdgeID EndEdges(const NodeID n) const = 0; @@ -98,6 +96,8 @@ template class BaseDataFacade virtual TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const = 0; + virtual TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; + virtual bool LocateClosestEndPointForCoordinate(const FixedPointCoordinate &input_coordinate, FixedPointCoordinate &result, const unsigned zoom_level = 18) = 0; @@ -106,10 +106,11 @@ template class BaseDataFacade PhantomNode &resulting_phantom_node, const unsigned zoom_level) = 0; - virtual bool IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate, - std::vector &resulting_phantom_node_vector, - const unsigned zoom_level, - const unsigned number_of_results) = 0; + virtual bool + IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate, + std::vector &resulting_phantom_node_vector, + const unsigned zoom_level, + const unsigned number_of_results) = 0; virtual unsigned GetCheckSum() const = 0; diff --git a/3party/osrm/osrm-backend/Server/DataStructures/InternalDataFacade.h b/3party/osrm/osrm-backend/Server/DataStructures/InternalDataFacade.h index 1c622e67ff..93c212d004 100644 --- a/3party/osrm/osrm-backend/Server/DataStructures/InternalDataFacade.h +++ b/3party/osrm/osrm-backend/Server/DataStructures/InternalDataFacade.h @@ -42,7 +42,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../../Util/BoostFileSystemFix.h" #include "../../Util/GraphLoader.h" #include "../../Util/ProgramOptions.h" -#include "../../Util/SimpleLogger.h" +#include "../../Util/simple_logger.hpp" #include @@ -66,13 +66,14 @@ template class InternalDataFacade : public BaseDataFacade::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_egde_is_compressed; + ShM::vector m_edge_is_compressed; ShM::vector m_geometry_indices; ShM::vector m_geometry_list; - boost::thread_specific_ptr::vector, false>> - m_static_rtree; + boost::thread_specific_ptr< + StaticRTree::vector, false>> m_static_rtree; boost::filesystem::path ram_index_path; boost::filesystem::path file_index_path; RangeTable<16, false> m_name_table; @@ -145,7 +146,8 @@ template class InternalDataFacade : public BaseDataFacade class InternalDataFacade : public BaseDataFacade class InternalDataFacade : public BaseDataFacadeempty(), "coordinates must be loaded before r-tree"); m_static_rtree.reset( - new StaticRTree(ram_index_path, file_index_path, m_coordinate_list) - ); + new StaticRTree(ram_index_path, file_index_path, m_coordinate_list)); } void LoadStreetNames(const boost::filesystem::path &names_file) @@ -289,7 +291,7 @@ template class InternalDataFacade : public BaseDataFacade class InternalDataFacade : public BaseDataFacadeGetNumberOfNodes(); } + unsigned GetNumberOfNodes() const final { return m_query_graph->GetNumberOfNodes(); } - unsigned GetNumberOfEdges() const { return m_query_graph->GetNumberOfEdges(); } + unsigned GetNumberOfEdges() const final { return m_query_graph->GetNumberOfEdges(); } - unsigned GetOutDegree(const NodeID n) const { return m_query_graph->GetOutDegree(n); } + unsigned GetOutDegree(const NodeID n) const final { return m_query_graph->GetOutDegree(n); } - NodeID GetTarget(const EdgeID e) const { return m_query_graph->GetTarget(e); } + NodeID GetTarget(const EdgeID e) const final { return m_query_graph->GetTarget(e); } - EdgeDataT &GetEdgeData(const EdgeID e) { return m_query_graph->GetEdgeData(e); } + // EdgeDataT &GetEdgeData(const EdgeID e) final { return m_query_graph->GetEdgeData(e); } - const EdgeDataT &GetEdgeData(const EdgeID e) const { return m_query_graph->GetEdgeData(e); } + EdgeDataT &GetEdgeData(const EdgeID e) const final { return m_query_graph->GetEdgeData(e); } - EdgeID BeginEdges(const NodeID n) const { return m_query_graph->BeginEdges(n); } + EdgeID BeginEdges(const NodeID n) const final { return m_query_graph->BeginEdges(n); } - EdgeID EndEdges(const NodeID n) const { return m_query_graph->EndEdges(n); } + EdgeID EndEdges(const NodeID n) const final { return m_query_graph->EndEdges(n); } - EdgeRange GetAdjacentEdgeRange(const NodeID node) const + EdgeRange GetAdjacentEdgeRange(const NodeID node) const final { return m_query_graph->GetAdjacentEdgeRange(node); }; // searches for a specific edge - EdgeID FindEdge(const NodeID from, const NodeID to) const + EdgeID FindEdge(const NodeID from, const NodeID to) const final { return m_query_graph->FindEdge(from, to); } - EdgeID FindEdgeInEitherDirection(const NodeID from, const NodeID to) const + EdgeID FindEdgeInEitherDirection(const NodeID from, const NodeID to) const final { return m_query_graph->FindEdgeInEitherDirection(from, to); } - EdgeID FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const + EdgeID FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const final { return m_query_graph->FindEdgeIndicateIfReverse(from, to, result); } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const + FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const final { return m_coordinate_list->at(id); }; - bool EdgeIsCompressed(const unsigned id) const { return m_egde_is_compressed.at(id); } + bool EdgeIsCompressed(const unsigned id) const { return m_edge_is_compressed.at(id); } - TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const + TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const final { return m_turn_instruction_list.at(id); } + TravelMode GetTravelModeForEdgeID(const unsigned id) const + { + return m_travel_mode_list.at(id); + } + bool LocateClosestEndPointForCoordinate(const FixedPointCoordinate &input_coordinate, FixedPointCoordinate &result, - const unsigned zoom_level = 18) + const unsigned zoom_level = 18) final { if (!m_static_rtree.get()) { @@ -372,7 +379,7 @@ template class InternalDataFacade : public BaseDataFacade class InternalDataFacade : public BaseDataFacade &resulting_phantom_node_vector, const unsigned zoom_level, - const unsigned number_of_results) + const unsigned number_of_results) final { if (!m_static_rtree.get()) { @@ -398,14 +405,14 @@ template class InternalDataFacade : public BaseDataFacade class InternalDataFacade : public BaseDataFacade &result_nodes) - const + virtual void GetUncompressedGeometry(const unsigned id, + std::vector &result_nodes) const final { const unsigned begin = m_geometry_indices.at(id); const unsigned end = m_geometry_indices.at(id + 1); @@ -440,7 +447,7 @@ template class InternalDataFacade : public BaseDataFacade #include @@ -55,8 +56,9 @@ template class SharedDataFacade : public BaseDataFacade::BlockT NameIndexBlock; typedef typename QueryGraph::InputEdge InputEdge; typedef typename super::RTreeLeaf RTreeLeaf; - typedef typename StaticRTree::vector, true>::TreeNode - RTreeNode; + using SharedRTree = StaticRTree::vector, true>; + using TimeStampedRTreePair = std::pair>; + using RTreeNode = typename SharedRTree::TreeNode; SharedDataLayout *data_layout; char *shared_memory; @@ -67,24 +69,23 @@ template class SharedDataFacade : public BaseDataFacade m_query_graph; - std::shared_ptr m_layout_memory; - std::shared_ptr m_large_memory; + std::unique_ptr m_query_graph; + 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_egde_is_compressed; + ShM::vector m_edge_is_compressed; ShM::vector m_geometry_indices; ShM::vector m_geometry_list; - boost::thread_specific_ptr::vector, true>> - m_static_rtree; + boost::thread_specific_ptr>> m_static_rtree; boost::filesystem::path file_index_path; std::shared_ptr> m_name_table; @@ -112,18 +113,16 @@ template class SharedDataFacade : public BaseDataFacadeGetBlockPtr(shared_memory, SharedDataLayout::R_SEARCH_TREE); - m_static_rtree.reset( - new StaticRTree::vector, true>( + m_static_rtree.reset(new TimeStampedRTreePair(CURRENT_TIMESTAMP, + osrm::make_unique( tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE], file_index_path, - m_coordinate_list) - ); + m_coordinate_list))); } void LoadGraph() { - m_number_of_nodes = data_layout->num_entries[SharedDataLayout::GRAPH_NODE_LIST]; GraphNode *graph_nodes_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GRAPH_NODE_LIST); @@ -142,9 +141,16 @@ template class SharedDataFacade : public BaseDataFacadeGetBlockPtr( shared_memory, SharedDataLayout::COORDINATE_LIST); - m_coordinate_list = std::make_shared::vector>( + m_coordinate_list = osrm::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( + 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( shared_memory, SharedDataLayout::TURN_INSTRUCTION); typename ShM::vector turn_instruction_list( @@ -183,8 +189,8 @@ template class SharedDataFacade : public BaseDataFacadeGetBlockPtr(shared_memory, SharedDataLayout::NAME_CHAR_LIST); typename ShM::vector names_char_list( names_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_CHAR_LIST]); - m_name_table = std::make_shared>( - name_offsets, name_blocks, names_char_list.size()); + m_name_table = osrm::make_unique>( + name_offsets, name_blocks, static_cast(names_char_list.size())); m_names_char_list.swap(names_char_list); } @@ -193,10 +199,10 @@ template class SharedDataFacade : public BaseDataFacadeGetBlockPtr( shared_memory, SharedDataLayout::GEOMETRIES_INDICATORS); - typename ShM::vector egde_is_compressed( + typename ShM::vector edge_is_compressed( geometries_compressed_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDICATORS]); - m_egde_is_compressed.swap(egde_is_compressed); + m_edge_is_compressed.swap(edge_is_compressed); unsigned *geometries_index_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_INDEX); @@ -218,7 +224,6 @@ template class SharedDataFacade : public BaseDataFacadePtr(); - CURRENT_LAYOUT = LAYOUT_NONE; CURRENT_DATA = DATA_NONE; CURRENT_TIMESTAMP = 0; @@ -271,7 +276,7 @@ template class SharedDataFacade : public BaseDataFacadesize(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { - if(!GetCoordinateOfNode(i).isValid()) + if (!GetCoordinateOfNode(i).isValid()) { SimpleLogger().Write() << "coordinate " << i << " not valid"; } @@ -280,55 +285,54 @@ template class SharedDataFacade : public BaseDataFacadeGetNumberOfNodes(); } + unsigned GetNumberOfNodes() const final { return m_query_graph->GetNumberOfNodes(); } - unsigned GetNumberOfEdges() const { return m_query_graph->GetNumberOfEdges(); } + unsigned GetNumberOfEdges() const final { return m_query_graph->GetNumberOfEdges(); } - unsigned GetOutDegree(const NodeID n) const { return m_query_graph->GetOutDegree(n); } + unsigned GetOutDegree(const NodeID n) const final { return m_query_graph->GetOutDegree(n); } - NodeID GetTarget(const EdgeID e) const { return m_query_graph->GetTarget(e); } + NodeID GetTarget(const EdgeID e) const final { return m_query_graph->GetTarget(e); } - EdgeDataT &GetEdgeData(const EdgeID e) { return m_query_graph->GetEdgeData(e); } + EdgeDataT &GetEdgeData(const EdgeID e) const final { return m_query_graph->GetEdgeData(e); } - // const EdgeDataT &GetEdgeData( const EdgeID e ) const { - // return m_query_graph->GetEdgeData(e); - // } + EdgeID BeginEdges(const NodeID n) const final { return m_query_graph->BeginEdges(n); } - EdgeID BeginEdges(const NodeID n) const { return m_query_graph->BeginEdges(n); } + EdgeID EndEdges(const NodeID n) const final { return m_query_graph->EndEdges(n); } - EdgeID EndEdges(const NodeID n) const { return m_query_graph->EndEdges(n); } - - EdgeRange GetAdjacentEdgeRange(const NodeID node) const + EdgeRange GetAdjacentEdgeRange(const NodeID node) const final { return m_query_graph->GetAdjacentEdgeRange(node); }; // searches for a specific edge - EdgeID FindEdge(const NodeID from, const NodeID to) const + EdgeID FindEdge(const NodeID from, const NodeID to) const final { return m_query_graph->FindEdge(from, to); } - EdgeID FindEdgeInEitherDirection(const NodeID from, const NodeID to) const + EdgeID FindEdgeInEitherDirection(const NodeID from, const NodeID to) const final { return m_query_graph->FindEdgeInEitherDirection(from, to); } - EdgeID FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const + EdgeID FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const final { return m_query_graph->FindEdgeIndicateIfReverse(from, to, result); } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const + FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const final { return m_coordinate_list->at(id); }; - virtual bool EdgeIsCompressed(const unsigned id) const { return m_egde_is_compressed.at(id); } + virtual bool EdgeIsCompressed(const unsigned id) const final + { + return m_edge_is_compressed.at(id); + } - virtual void GetUncompressedGeometry(const unsigned id, std::vector &result_nodes) - const + virtual void GetUncompressedGeometry(const unsigned id, + std::vector &result_nodes) const final { const unsigned begin = m_geometry_indices.at(id); const unsigned end = m_geometry_indices.at(id + 1); @@ -338,39 +342,44 @@ template class SharedDataFacade : public BaseDataFacadefirst) { LoadRTree(); } - return m_static_rtree->LocateClosestEndPointForCoordinate( + return m_static_rtree->second->LocateClosestEndPointForCoordinate( input_coordinate, result, zoom_level); } bool FindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate, PhantomNode &resulting_phantom_node, - const unsigned zoom_level) + const unsigned zoom_level) final { - if (!m_static_rtree.get()) + if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first) { LoadRTree(); } - return m_static_rtree->FindPhantomNodeForCoordinate( + return m_static_rtree->second->FindPhantomNodeForCoordinate( input_coordinate, resulting_phantom_node, zoom_level); } @@ -378,25 +387,25 @@ template class SharedDataFacade : public BaseDataFacade &resulting_phantom_node_vector, const unsigned zoom_level, - const unsigned number_of_results) + const unsigned number_of_results) final { - if (!m_static_rtree.get()) + if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first) { LoadRTree(); } - return m_static_rtree->IncrementalFindPhantomNodeForCoordinate( + return m_static_rtree->second->IncrementalFindPhantomNodeForCoordinate( input_coordinate, resulting_phantom_node_vector, zoom_level, number_of_results); } - unsigned GetCheckSum() const { return m_check_sum; } + unsigned GetCheckSum() const final { return m_check_sum; } - unsigned GetNameIndexFromEdgeID(const unsigned id) const + unsigned GetNameIndexFromEdgeID(const unsigned id) const final { return m_name_ID_list.at(id); }; - void GetName(const unsigned name_id, std::string &result) const + void GetName(const unsigned name_id, std::string &result) const final { if (UINT_MAX == name_id) { @@ -415,7 +424,7 @@ template class SharedDataFacade : public BaseDataFacade #include // Added at the start and end of each block as sanity check -constexpr char CANARY[] = "OSRM"; +static const char CANARY[] = "OSRM"; struct SharedDataLayout { @@ -50,6 +50,7 @@ struct SharedDataLayout GRAPH_EDGE_LIST, COORDINATE_LIST, TURN_INSTRUCTION, + TRAVEL_MODE, R_SEARCH_TREE, GEOMETRIES_INDEX, GEOMETRIES_LIST, @@ -82,6 +83,7 @@ struct SharedDataLayout SimpleLogger().Write(logDEBUG) << "timestamp_length: " << num_entries[TIMESTAMP]; SimpleLogger().Write(logDEBUG) << "coordinate_list_size: " << num_entries[COORDINATE_LIST]; SimpleLogger().Write(logDEBUG) << "turn_instruction_list_size: " << num_entries[TURN_INSTRUCTION]; + SimpleLogger().Write(logDEBUG) << "travel_mode_list_size: " << num_entries[TRAVEL_MODE]; SimpleLogger().Write(logDEBUG) << "r_search_tree_size: " << num_entries[R_SEARCH_TREE]; SimpleLogger().Write(logDEBUG) << "geometries_indicators: " << num_entries[GEOMETRIES_INDICATORS] << "/" << ((num_entries[GEOMETRIES_INDICATORS] / 8) + 1); @@ -98,6 +100,7 @@ struct SharedDataLayout SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " << ": " << GetBlockSize(GRAPH_EDGE_LIST ); SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " << ": " << GetBlockSize(COORDINATE_LIST ); SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " << ": " << GetBlockSize(TURN_INSTRUCTION ); + SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " << ": " << GetBlockSize(TRAVEL_MODE ); SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " << ": " << GetBlockSize(R_SEARCH_TREE ); SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " << ": " << GetBlockSize(GEOMETRIES_INDEX ); SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " << ": " << GetBlockSize(GEOMETRIES_LIST ); diff --git a/3party/osrm/osrm-backend/Server/Http/Reply.cpp b/3party/osrm/osrm-backend/Server/Http/Reply.cpp index b3247ece8c..e2cf0aecf8 100644 --- a/3party/osrm/osrm-backend/Server/Http/Reply.cpp +++ b/3party/osrm/osrm-backend/Server/Http/Reply.cpp @@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "../../Util/StringUtil.h" +#include "../../Util/cast.hpp" namespace http { @@ -38,7 +38,7 @@ void Reply::SetSize(const unsigned size) { if ("Content-Length" == h.name) { - h.value = UintToString(size); + h.value = cast::integral_to_string(size); } } } @@ -87,8 +87,7 @@ Reply Reply::StockReply(Reply::status_type status) const std::string status_string = reply.ToString(status); reply.content.insert(reply.content.end(), status_string.begin(), status_string.end()); reply.headers.emplace_back("Access-Control-Allow-Origin", "*"); - reply.headers.emplace_back("Content-Length", - UintToString(static_cast(reply.content.size()))); + reply.headers.emplace_back("Content-Length", cast::integral_to_string(reply.content.size())); reply.headers.emplace_back("Content-Type", "text/html"); return reply; } diff --git a/3party/osrm/osrm-backend/Server/RequestHandler.cpp b/3party/osrm/osrm-backend/Server/RequestHandler.cpp index 36a2808e8a..b358d8d2da 100644 --- a/3party/osrm/osrm-backend/Server/RequestHandler.cpp +++ b/3party/osrm/osrm-backend/Server/RequestHandler.cpp @@ -25,13 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "APIGrammar.h" #include "RequestHandler.h" + +#include "APIGrammar.h" #include "Http/Request.h" #include "../DataStructures/JSONContainer.h" #include "../Library/OSRM.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/StringUtil.h" #include "../typedefs.h" @@ -61,17 +62,17 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply // req.agent << ( 0 == req.agent.length() ? "- " :" ") << request; time_t ltime; - struct tm *Tm; + struct tm *time_stamp; ltime = time(nullptr); - Tm = localtime(<ime); + time_stamp = localtime(<ime); // log timestamp - SimpleLogger().Write() << (Tm->tm_mday < 10 ? "0" : "") << Tm->tm_mday << "-" - << (Tm->tm_mon + 1 < 10 ? "0" : "") << (Tm->tm_mon + 1) << "-" - << 1900 + Tm->tm_year << " " << (Tm->tm_hour < 10 ? "0" : "") - << Tm->tm_hour << ":" << (Tm->tm_min < 10 ? "0" : "") << Tm->tm_min - << ":" << (Tm->tm_sec < 10 ? "0" : "") << Tm->tm_sec << " " + 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" : "") + << time_stamp->tm_hour << ":" << (time_stamp->tm_min < 10 ? "0" : "") << time_stamp->tm_min + << ":" << (time_stamp->tm_sec < 10 ? "0" : "") << time_stamp->tm_sec << " " << req.endpoint.to_string() << " " << req.referrer << (0 == req.referrer.length() ? "- " : " ") << req.agent << (0 == req.agent.length() ? "- " : " ") << request; @@ -87,11 +88,11 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply { reply = http::Reply::StockReply(http::Reply::badRequest); reply.content.clear(); - const unsigned position = static_cast(std::distance(request.begin(), iter)); + const auto position = std::distance(request.begin(), iter); JSON::Object json_result; json_result.values["status"] = 400; std::string message = "Query string malformed close to position "; - message += UintToString(position); + message += cast::integral_to_string(position); json_result.values["status_message"] = message; JSON::render(reply.content, json_result); return; @@ -112,8 +113,7 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply } // set headers - reply.headers.emplace_back("Content-Length", - UintToString(static_cast(reply.content.size()))); + reply.headers.emplace_back("Content-Length", cast::integral_to_string(reply.content.size())); if ("gpx" == route_parameters.output_format) { // gpx file reply.headers.emplace_back("Content-Type", "application/gpx+xml; charset=UTF-8"); diff --git a/3party/osrm/osrm-backend/Server/RequestHandler.h b/3party/osrm/osrm-backend/Server/RequestHandler.h index 462c34ffc2..7263dad4ef 100644 --- a/3party/osrm/osrm-backend/Server/RequestHandler.h +++ b/3party/osrm/osrm-backend/Server/RequestHandler.h @@ -44,7 +44,7 @@ class RequestHandler { public: - typedef APIGrammar APIGrammarParser; + using APIGrammarParser = APIGrammar; RequestHandler(); RequestHandler(const RequestHandler &) = delete; diff --git a/3party/osrm/osrm-backend/Server/RequestParser.cpp b/3party/osrm/osrm-backend/Server/RequestParser.cpp index cad05b97d3..6e9cddf5ee 100644 --- a/3party/osrm/osrm-backend/Server/RequestParser.cpp +++ b/3party/osrm/osrm-backend/Server/RequestParser.cpp @@ -25,9 +25,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "Http/Request.h" #include "RequestParser.h" +#include "Http/Request.h" + namespace http { @@ -264,18 +265,21 @@ RequestParser::consume(Request &req, char input, http::CompressionType *compress return false; default: // expecting_newline_3: return (input == '\n'); - // default: - // return false; + // default: + // return false; } } -inline bool RequestParser::isChar(int c) { return c >= 0 && c <= 127; } +inline bool RequestParser::isChar(int character) { return character >= 0 && character <= 127; } -inline bool RequestParser::isCTL(int c) { return (c >= 0 && c <= 31) || (c == 127); } - -inline bool RequestParser::isTSpecial(int c) +inline bool RequestParser::isCTL(int character) { - switch (c) + return (character >= 0 && character <= 31) || (character == 127); +} + +inline bool RequestParser::isTSpecial(int character) +{ + switch (character) { case '(': case ')': @@ -302,5 +306,5 @@ inline bool RequestParser::isTSpecial(int c) } } -inline bool RequestParser::isDigit(int c) { return c >= '0' && c <= '9'; } +inline bool RequestParser::isDigit(int character) { return character >= '0' && character <= '9'; } } diff --git a/3party/osrm/osrm-backend/Server/Server.h b/3party/osrm/osrm-backend/Server/Server.h index d5dab1ff3f..8e0b101302 100644 --- a/3party/osrm/osrm-backend/Server/Server.h +++ b/3party/osrm/osrm-backend/Server/Server.h @@ -28,14 +28,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SERVER_H #define SERVER_H -#include "../Util/StringUtil.h" - #include "Connection.h" #include "RequestHandler.h" +#include "../Util/cast.hpp" +#include "../Util/make_unique.hpp" +#include "../Util/simple_logger.hpp" + #include #include +#include + #include #include #include @@ -44,11 +48,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class Server { public: + + // Note: returns a shared instead of a unique ptr as it is captured in a lambda somewhere else + 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(); + 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); + } + 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(new http::Connection(io_service, request_handler)), request_handler() + new_connection(std::make_shared(io_service, request_handler)), request_handler() { - const std::string port_string = IntToString(port); + const std::string port_string = cast::integral_to_string(port); boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(address, port_string); @@ -63,9 +77,6 @@ class Server boost::bind(&Server::HandleAccept, this, boost::asio::placeholders::error)); } - // Server() = delete; - // Server(const Server &) = delete; - void Run() { std::vector> threads; @@ -75,9 +86,9 @@ class Server boost::bind(&boost::asio::io_service::run, &io_service)); threads.push_back(thread); } - for (unsigned i = 0; i < threads.size(); ++i) + for (auto thread : threads) { - threads[i]->join(); + thread->join(); } } @@ -91,7 +102,7 @@ class Server if (!e) { new_connection->start(); - new_connection.reset(new http::Connection(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)); diff --git a/3party/osrm/osrm-backend/ThirdParty/variant/recursive_wrapper.hpp b/3party/osrm/osrm-backend/ThirdParty/variant/recursive_wrapper.hpp new file mode 100644 index 0000000000..54b27634a3 --- /dev/null +++ b/3party/osrm/osrm-backend/ThirdParty/variant/recursive_wrapper.hpp @@ -0,0 +1,127 @@ +#ifndef MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP +#define MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP + +#include + +namespace mapbox { namespace util { + +template +class recursive_wrapper +{ +public: + using type = T; +private: + + T* p_; + +public: + + ~recursive_wrapper(); + recursive_wrapper(); + + recursive_wrapper(recursive_wrapper const& operand); + recursive_wrapper(T const& operand); + recursive_wrapper(recursive_wrapper&& operand); + recursive_wrapper(T&& operand); + +private: + + void assign(const T& rhs); + +public: + + inline recursive_wrapper& operator=(recursive_wrapper const& rhs) + { + assign( rhs.get() ); + return *this; + } + + inline recursive_wrapper& operator=(T const& rhs) + { + assign( rhs ); + return *this; + } + + inline void swap(recursive_wrapper& operand) noexcept + { + T* temp = operand.p_; + operand.p_ = p_; + p_ = temp; + } + + + recursive_wrapper& operator=(recursive_wrapper&& rhs) noexcept + { + swap(rhs); + return *this; + } + + recursive_wrapper& operator=(T&& rhs) + { + get() = std::move(rhs); + return *this; + } + + +public: + + T& get() { return *get_pointer(); } + const T& get() const { return *get_pointer(); } + T* get_pointer() { return p_; } + const T* get_pointer() const { return p_; } + operator T const&() const { return this->get(); } + operator T&() { return this->get(); } +}; + +template +recursive_wrapper::~recursive_wrapper() +{ + delete p_; +} + +template +recursive_wrapper::recursive_wrapper() + : p_(new T) +{ +} + +template +recursive_wrapper::recursive_wrapper(recursive_wrapper const& operand) + : p_(new T( operand.get() )) +{ +} + +template +recursive_wrapper::recursive_wrapper(T const& operand) + : p_(new T(operand)) +{ +} + +template +recursive_wrapper::recursive_wrapper(recursive_wrapper&& operand) + : p_(operand.p_) +{ + operand.p_ = nullptr; +} + +template +recursive_wrapper::recursive_wrapper(T&& operand) + : p_(new T( std::move(operand) )) +{ +} + +template +void recursive_wrapper::assign(const T& rhs) +{ + this->get() = rhs; +} + +template +inline void swap(recursive_wrapper& lhs, recursive_wrapper& rhs) noexcept +{ + lhs.swap(rhs); +} + +}} + +#endif // MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP diff --git a/3party/osrm/osrm-backend/ThirdParty/variant/variant.hpp b/3party/osrm/osrm-backend/ThirdParty/variant/variant.hpp new file mode 100644 index 0000000000..3b5659425a --- /dev/null +++ b/3party/osrm/osrm-backend/ThirdParty/variant/variant.hpp @@ -0,0 +1,740 @@ +#ifndef MAPBOX_UTIL_VARIANT_HPP +#define MAPBOX_UTIL_VARIANT_HPP + +#include +#include +#include +#include // runtime_error +#include // operator new +#include // size_t +#include +#include + +#include "recursive_wrapper.hpp" + +#ifdef _MSC_VER + // http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx + #ifdef NDEBUG + #define VARIANT_INLINE __forceinline + #else + #define VARIANT_INLINE __declspec(noinline) + #endif +#else + #ifdef NDEBUG + #define VARIANT_INLINE inline __attribute__((always_inline)) + #else + #define VARIANT_INLINE __attribute__((noinline)) + #endif +#endif + +#define VARIANT_MAJOR_VERSION 0 +#define VARIANT_MINOR_VERSION 1 +#define VARIANT_PATCH_VERSION 0 + +// translates to 100 +#define VARIANT_VERSION (VARIANT_MAJOR_VERSION*100000) + (VARIANT_MINOR_VERSION*100) + (VARIANT_PATCH_VERSION) + +namespace mapbox { namespace util { namespace detail { + +static constexpr std::size_t invalid_value = std::size_t(-1); + +template +struct direct_type; + +template +struct direct_type +{ + static constexpr std::size_t index = std::is_same::value + ? sizeof...(Types) : direct_type::index; +}; + +template +struct direct_type +{ + static constexpr std::size_t index = invalid_value; +}; + +template +struct convertible_type; + +template +struct convertible_type +{ + static constexpr std::size_t index = std::is_convertible::value + ? sizeof...(Types) : convertible_type::index; +}; + +template +struct convertible_type +{ + static constexpr std::size_t index = invalid_value; +}; + +template +struct value_traits +{ + static constexpr std::size_t direct_index = direct_type::index; + static constexpr std::size_t index = + (direct_index == invalid_value) ? convertible_type::index : direct_index; +}; + +template +struct is_valid_type; + +template +struct is_valid_type +{ + static constexpr bool value = std::is_convertible::value + || is_valid_type::value; +}; + +template +struct is_valid_type : std::false_type {}; + +template +struct select_type +{ + static_assert(N < sizeof...(Types), "index out of bounds"); +}; + +template +struct select_type +{ + using type = typename select_type::type; +}; + +template +struct select_type<0, T, Types...> +{ + using type = T; +}; + +} // namespace detail + +// static visitor +template +struct static_visitor +{ + using result_type = R; +protected: + static_visitor() {} + ~static_visitor() {} +}; + + +template +struct static_max; + +template +struct static_max +{ + static const std::size_t value = arg; +}; + +template +struct static_max +{ + static const std::size_t value = arg1 >= arg2 ? static_max::value : + static_max::value; +}; + +template +struct variant_helper; + +template +struct variant_helper +{ + VARIANT_INLINE static void destroy(const std::size_t id, void * data) + { + if (id == sizeof...(Types)) + { + reinterpret_cast(data)->~T(); + } + else + { + variant_helper::destroy(id, data); + } + } + + VARIANT_INLINE static void move(const std::size_t old_id, void * old_value, void * new_value) + { + if (old_id == sizeof...(Types)) + { + new (new_value) T(std::move(*reinterpret_cast(old_value))); + //std::memcpy(new_value, old_value, sizeof(T)); + // ^^ DANGER: this should only be considered for relocatable types e.g built-in types + // Also, I don't see any measurable performance benefit just yet + } + else + { + variant_helper::move(old_id, old_value, new_value); + } + } + + VARIANT_INLINE static void copy(const std::size_t old_id, const void * old_value, void * new_value) + { + if (old_id == sizeof...(Types)) + { + new (new_value) T(*reinterpret_cast(old_value)); + } + else + { + variant_helper::copy(old_id, old_value, new_value); + } + } +}; + +template<> struct variant_helper<> +{ + VARIANT_INLINE static void destroy(const std::size_t, void *) {} + VARIANT_INLINE static void move(const std::size_t, void *, void *) {} + VARIANT_INLINE static void copy(const std::size_t, const void *, void *) {} +}; + +namespace detail { + +template +struct unwrapper +{ + T const& operator() (T const& obj) const + { + return obj; + } + + T& operator() (T & obj) const + { + return obj; + } +}; + + +template +struct unwrapper> +{ + auto operator() (recursive_wrapper const& obj) const + -> typename recursive_wrapper::type const& + { + return obj.get(); + } +}; + + +template +struct dispatcher; + +template +struct dispatcher +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const& v, F f) + { + if (v.get_type_index() == sizeof...(Types)) + { + return f(unwrapper()(v. template get())); + } + else + { + return dispatcher::apply_const(v, f); + } + } + + VARIANT_INLINE static result_type apply(V & v, F f) + { + if (v.get_type_index() == sizeof...(Types)) + { + return f(unwrapper()(v. template get())); + } + else + { + return dispatcher::apply(v, f); + } + } +}; + +template +struct dispatcher +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const&, F) + { + throw std::runtime_error(std::string("unary dispatch: FAIL ") + typeid(V).name()); + } + + VARIANT_INLINE static result_type apply(V &, F) + { + throw std::runtime_error(std::string("unary dispatch: FAIL ") + typeid(V).name()); + } +}; + + +template +struct binary_dispatcher_rhs; + +template +struct binary_dispatcher_rhs +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f) + { + if (rhs.get_type_index() == sizeof...(Types)) // call binary functor + { + return f(unwrapper()(lhs. template get()), + unwrapper()(rhs. template get())); + } + else + { + return binary_dispatcher_rhs::apply_const(lhs, rhs, f); + } + } + + VARIANT_INLINE static result_type apply(V & lhs, V & rhs, F f) + { + if (rhs.get_type_index() == sizeof...(Types)) // call binary functor + { + return f(unwrapper()(lhs. template get()), + unwrapper()(rhs. template get())); + } + else + { + return binary_dispatcher_rhs::apply(lhs, rhs, f); + } + } + +}; + +template +struct binary_dispatcher_rhs +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const&, V const&, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } + VARIANT_INLINE static result_type apply(V &, V &, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } +}; + + +template +struct binary_dispatcher_lhs; + +template +struct binary_dispatcher_lhs +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f) + { + if (lhs.get_type_index() == sizeof...(Types)) // call binary functor + { + return f(lhs. template get(), rhs. template get()); + } + else + { + return binary_dispatcher_lhs::apply_const(lhs, rhs, f); + } + } + + VARIANT_INLINE static result_type apply(V & lhs, V & rhs, F f) + { + if (lhs.get_type_index() == sizeof...(Types)) // call binary functor + { + return f(lhs. template get(), rhs. template get()); + } + else + { + return binary_dispatcher_lhs::apply(lhs, rhs, f); + } + } + +}; + +template +struct binary_dispatcher_lhs +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const&, V const&, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } + + VARIANT_INLINE static result_type apply(V &, V &, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } +}; + +template +struct binary_dispatcher; + +template +struct binary_dispatcher +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const& v0, V const& v1, F f) + { + if (v0.get_type_index() == sizeof...(Types)) + { + if (v0.get_type_index() == v1.get_type_index()) + { + return f(v0. template get(), v1. template get()); // call binary functor + } + else + { + return binary_dispatcher_rhs::apply_const(v0, v1, f); + } + } + else if (v1.get_type_index() == sizeof...(Types)) + { + return binary_dispatcher_lhs::apply_const(v0, v1, f); + } + return binary_dispatcher::apply_const(v0, v1, f); + } + + VARIANT_INLINE static result_type apply(V & v0, V & v1, F f) + { + if (v0.get_type_index() == sizeof...(Types)) + { + if (v0.get_type_index() == v1.get_type_index()) + { + return f(v0. template get(), v1. template get()); // call binary functor + } + else + { + return binary_dispatcher_rhs::apply(v0, v1, f); + } + } + else if (v1.get_type_index() == sizeof...(Types)) + { + return binary_dispatcher_lhs::apply(v0, v1, f); + } + return binary_dispatcher::apply(v0, v1, f); + } +}; + +template +struct binary_dispatcher +{ + using result_type = typename F::result_type; + VARIANT_INLINE static result_type apply_const(V const&, V const&, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } + + VARIANT_INLINE static result_type apply(V &, V &, F) + { + throw std::runtime_error("binary dispatch: FAIL"); + } +}; + +// comparator functors +struct equal_comp +{ + template + bool operator()(T const& lhs, T const& rhs) const + { + return lhs == rhs; + } +}; + +struct less_comp +{ + template + bool operator()(T const& lhs, T const& rhs) const + { + return lhs < rhs; + } +}; + +template +class comparer : public static_visitor +{ +public: + explicit comparer(Variant const& lhs) noexcept + : lhs_(lhs) {} + comparer& operator=(comparer const&) = delete; + // visitor + template + bool operator()(T const& rhs_content) const + { + T const& lhs_content = lhs_.template get(); + return Comp()(lhs_content, rhs_content); + } +private: + Variant const& lhs_; +}; + +// operator<< helper +template +class printer : public static_visitor<> +{ +public: + explicit printer(Out & out) + : out_(out) {} + printer& operator=(printer const&) = delete; + +// visitor + template + void operator()(T const& operand) const + { + out_ << operand; + } +private: + Out & out_; +}; + +} // namespace detail + +struct no_init {}; + +template +class variant +{ +private: + + static const std::size_t data_size = static_max::value; + static const std::size_t data_align = static_max::value; + + using data_type = typename std::aligned_storage::type; + using helper_type = variant_helper; + + std::size_t type_index; + data_type data; + +public: + + + VARIANT_INLINE variant() + : type_index(sizeof...(Types) - 1) + { + new (&data) typename detail::select_type<0, Types...>::type(); + } + + VARIANT_INLINE variant(no_init) + : type_index(detail::invalid_value) {} + + // http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers + template ::type, Types...>::value>::type> + VARIANT_INLINE variant(T && val) noexcept + : type_index(detail::value_traits::type, Types...>::index) + { + constexpr std::size_t index = sizeof...(Types) - detail::value_traits::type, Types...>::index - 1; + using target_type = typename detail::select_type::type; + new (&data) target_type(std::forward(val)); // nothrow + } + + VARIANT_INLINE variant(variant const& old) + : type_index(old.type_index) + { + helper_type::copy(old.type_index, &old.data, &data); + } + + VARIANT_INLINE variant(variant&& old) noexcept + : type_index(old.type_index) + { + helper_type::move(old.type_index, &old.data, &data); + } + + friend void swap(variant & first, variant & second) + { + using std::swap; //enable ADL + swap(first.type_index, second.type_index); + swap(first.data, second.data); + } + + VARIANT_INLINE variant& operator=(variant other) + { + swap(*this, other); + return *this; + } + + // conversions + // move-assign + template + VARIANT_INLINE variant& operator=(T && rhs) noexcept + { + variant temp(std::forward(rhs)); + swap(*this, temp); + return *this; + } + + // copy-assign + template + VARIANT_INLINE variant& operator=(T const& rhs) + { + variant temp(rhs); + swap(*this, temp); + return *this; + } + + template + VARIANT_INLINE bool is() const + { + return (type_index == detail::direct_type::index); + } + + VARIANT_INLINE bool valid() const + { + return (type_index != detail::invalid_value); + } + + template + VARIANT_INLINE void set(Args&&... args) + { + helper_type::destroy(type_index, &data); + new (&data) T(std::forward(args)...); + type_index = detail::direct_type::index; + } + + template + VARIANT_INLINE T& get() + { + if (type_index == detail::direct_type::index) + { + return *reinterpret_cast(&data); + } + else + { + throw std::runtime_error("in get()"); + } + } + + template + VARIANT_INLINE T const& get() const + { + if (type_index == detail::direct_type::index) + { + return *reinterpret_cast(&data); + } + else + { + throw std::runtime_error("in get()"); + } + } + + VARIANT_INLINE std::size_t get_type_index() const + { + return type_index; + } + + // visitor + // unary + template + auto VARIANT_INLINE + static visit(V const& v, F f) + -> decltype(detail::dispatcher::apply_const(v, f)) + { + return detail::dispatcher::apply_const(v, f); + } + // non-const + template + auto VARIANT_INLINE + static visit(V & v, F f) + -> decltype(detail::dispatcher::apply(v, f)) + { + return detail::dispatcher::apply(v, f); + } + + // binary + // const + template + auto VARIANT_INLINE + static binary_visit(V const& v0, V const& v1, F f) + -> decltype(detail::binary_dispatcher::apply_const(v0, v1, f)) + { + return detail::binary_dispatcher::apply_const(v0, v1, f); + } + // non-const + template + auto VARIANT_INLINE + static binary_visit(V& v0, V& v1, F f) + -> decltype(detail::binary_dispatcher::apply(v0, v1, f)) + { + return detail::binary_dispatcher::apply(v0, v1, f); + } + + ~variant() noexcept + { + helper_type::destroy(type_index, &data); + } + + // comparison operators + // equality + VARIANT_INLINE bool operator==(variant const& rhs) const + { + if (this->get_type_index() != rhs.get_type_index()) + return false; + detail::comparer visitor(*this); + return visit(rhs, visitor); + } + // less than + VARIANT_INLINE bool operator<(variant const& rhs) const + { + if (this->get_type_index() != rhs.get_type_index()) + { + return this->get_type_index() < rhs.get_type_index(); + // ^^ borrowed from boost::variant + } + detail::comparer visitor(*this); + return visit(rhs, visitor); + } +}; + +// unary visitor interface + +// const +template +auto VARIANT_INLINE static apply_visitor(F f, V const& v) -> decltype(V::visit(v, f)) +{ + return V::visit(v, f); +} +// non-const +template +auto VARIANT_INLINE static apply_visitor(F f, V & v) -> decltype(V::visit(v, f)) +{ + return V::visit(v, f); +} + +// binary visitor interface +// const +template +auto VARIANT_INLINE static apply_visitor(F f, V const& v0, V const& v1) -> decltype(V::binary_visit(v0, v1, f)) +{ + return V::binary_visit(v0, v1, f); +} +// non-const +template +auto VARIANT_INLINE static apply_visitor(F f, V & v0, V & v1) -> decltype(V::binary_visit(v0, v1, f)) +{ + return V::binary_visit(v0, v1, f); +} + +// getter interface +template +ResultType & get(T & var) +{ + return var.template get(); +} + +template +ResultType const& get(T const& var) +{ + return var.template get(); +} + + +// operator<< +template +VARIANT_INLINE std::basic_ostream& +operator<< (std::basic_ostream& out, variant const& rhs) +{ + detail::printer> visitor(out); + apply_visitor(visitor, rhs); + return out; +} + +}} + +#endif // MAPBOX_UTIL_VARIANT_HPP diff --git a/3party/osrm/osrm-backend/Tools/check-hsgr.cpp b/3party/osrm/osrm-backend/Tools/check-hsgr.cpp index f784659741..b3b157ad11 100644 --- a/3party/osrm/osrm-backend/Tools/check-hsgr.cpp +++ b/3party/osrm/osrm-backend/Tools/check-hsgr.cpp @@ -24,13 +24,13 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../DataStructures/DeallocatingVector.h" #include "../DataStructures/Percent.h" #include "../DataStructures/QueryEdge.h" #include "../DataStructures/Range.h" #include "../DataStructures/StaticGraph.h" #include "../Util/GraphLoader.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" +#include "../Util/OSRMException.h" #include #include @@ -38,69 +38,68 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -typedef QueryEdge::EdgeData EdgeData; -typedef StaticGraph QueryGraph; +using EdgeData = QueryEdge::EdgeData; +using QueryGraph = StaticGraph; int main(int argc, char *argv[]) { LogPolicy::GetInstance().Unmute(); - if (argc != 2) - { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; - return 1; - } - try { + if (argc != 2) + { + 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(); unsigned m_check_sum = 0; - unsigned m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); - SimpleLogger().Write() << "announced " << m_number_of_nodes + unsigned m_number_of_nodes = + readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); + SimpleLogger().Write() << "expecting " << m_number_of_nodes << " nodes, checksum: " << 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() << " edges"; - std::shared_ptr 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 p(m_query_graph->GetNumberOfNodes()); - for (const auto u : osrm::irange(0u, m_query_graph->GetNumberOfNodes())) + Percent progress(m_query_graph->GetNumberOfNodes()); + for (const auto node_u : osrm::irange(0u, m_query_graph->GetNumberOfNodes())) { - for (const auto eid : m_query_graph->GetAdjacentEdgeRange(u)) + for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) { const EdgeData &data = m_query_graph->GetEdgeData(eid); if (!data.shortcut) { continue; } - const unsigned v = m_query_graph->GetTarget(eid); - const EdgeID first_edge_id = m_query_graph->FindEdgeInEitherDirection(u, data.id); - if (SPECIAL_EDGEID == first_edge_id) + const unsigned node_v = m_query_graph->GetTarget(eid); + const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); + if (SPECIAL_EDGEID == edge_id_1) { - SimpleLogger().Write(logWARNING) << "cannot find first segment of edge (" << u - << "," << data.id << "," << v << "), eid: " << eid; - BOOST_ASSERT(false); - return 1; + throw OSRMException("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)); } - const EdgeID second_edge_id = m_query_graph->FindEdgeInEitherDirection(data.id, v); - if (SPECIAL_EDGEID == second_edge_id) + const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); + if (SPECIAL_EDGEID == edge_id_2) { - SimpleLogger().Write(logWARNING) << "cannot find second segment of edge (" << u - << "," << data.id << "," << v << "), eid: " << eid; - BOOST_ASSERT(false); - return 1; + throw OSRMException("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)); } } - p.printIncrement(); + progress.printStatus(node_u); } m_query_graph.reset(); SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; diff --git a/3party/osrm/osrm-backend/Tools/components.cpp b/3party/osrm/osrm-backend/Tools/components.cpp index 74e9fd3281..b60077bd0d 100644 --- a/3party/osrm/osrm-backend/Tools/components.cpp +++ b/3party/osrm/osrm-backend/Tools/components.cpp @@ -29,7 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../Algorithms/StronglyConnectedComponents.h" #include "../Util/GraphLoader.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/FingerPrint.h" #include @@ -44,16 +44,17 @@ std::vector trafficlight_ID_list; int main(int argc, char *argv[]) { - // enable logging LogPolicy::GetInstance().Unmute(); - if (argc < 3) - { - SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; - return -1; - } - try { + // enable logging + if (argc < 3) + { + SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] + << " "; + return -1; + } + SimpleLogger().Write() << "Using restrictions from file: " << argv[2]; std::ifstream restriction_ifstream(argv[2], std::ios::binary); const FingerPrint fingerprint_orig; @@ -71,15 +72,15 @@ int main(int argc, char *argv[]) { throw OSRMException("Could not access files"); } - uint32_t usable_restriction_count = 0; - restriction_ifstream.read((char *)&usable_restriction_count, sizeof(uint32_t)); - restrictions_vector.resize(usable_restriction_count); + uint32_t usable_restrictions = 0; + restriction_ifstream.read((char *)&usable_restrictions, sizeof(uint32_t)); + restrictions_vector.resize(usable_restrictions); // load restrictions - if (usable_restriction_count>0) + if (usable_restrictions > 0) { restriction_ifstream.read((char *)&(restrictions_vector[0]), - usable_restriction_count * sizeof(TurnRestriction)); + usable_restrictions * sizeof(TurnRestriction)); } restriction_ifstream.close(); @@ -99,7 +100,7 @@ int main(int argc, char *argv[]) restrictions_vector); input_stream.close(); - BOOST_ASSERT_MSG(restrictions_vector.size() == usable_restriction_count, + BOOST_ASSERT_MSG(restrictions_vector.size() == usable_restrictions, "size of restrictions_vector changed"); SimpleLogger().Write() << restrictions_vector.size() << " restrictions, " @@ -109,13 +110,12 @@ int main(int argc, char *argv[]) // Building an edge-expanded graph from node-based input an turn // restrictions SimpleLogger().Write() << "Starting SCC graph traversal"; - std::shared_ptr tarjan = - std::make_shared(number_of_nodes, - edge_list, - bollard_ID_list, - trafficlight_ID_list, - restrictions_vector, - coordinate_list); + std::shared_ptr tarjan = std::make_shared(number_of_nodes, + edge_list, + bollard_ID_list, + trafficlight_ID_list, + restrictions_vector, + coordinate_list); edge_list.clear(); edge_list.shrink_to_fit(); diff --git a/3party/osrm/osrm-backend/Tools/io-benchmark.cpp b/3party/osrm/osrm-backend/Tools/io-benchmark.cpp index 6304aaec05..b438000558 100644 --- a/3party/osrm/osrm-backend/Tools/io-benchmark.cpp +++ b/3party/osrm/osrm-backend/Tools/io-benchmark.cpp @@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../Util/GitDescription.h" #include "../Util/OSRMException.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/TimingUtil.h" #include @@ -71,32 +71,30 @@ void RunStatistics(std::vector &timings_vector, Statistics &stats) int main(int argc, char *argv[]) { LogPolicy::GetInstance().Unmute(); - - SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " - << "compiled at " << __DATE__ << ", " __TIME__; - -#ifdef __FreeBSD__ - SimpleLogger().Write() << "Not supported on FreeBSD"; - return 0; -#endif -#ifdef WIN32 - SimpleLogger().Write() << "Not supported on Windows"; - return 0; -#else - - - if (1 == argc) - { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; - return -1; - } - - boost::filesystem::path test_path = boost::filesystem::path(argv[1]); - test_path /= "osrm.tst"; - SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); - + boost::filesystem::path test_path; try { + SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; + +#ifdef __FreeBSD__ + SimpleLogger().Write() << "Not supported on FreeBSD"; + return 0; +#endif +#ifdef WIN32 + SimpleLogger().Write() << "Not supported on Windows"; + return 0; +#else + + if (1 == argc) + { + 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(); + // create files for testing if (2 == argc) { @@ -118,27 +116,26 @@ int main(int argc, char *argv[]) fclose(fd); #endif #ifdef __linux__ - int f = + int file_desc = open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU); - if (-1 == f) + if (-1 == file_desc) { throw OSRMException("Could not open random data file"); } TIMER_START(write_1gb); - int ret = write(f, random_array, number_of_elements * sizeof(unsigned)); + int ret = write(file_desc, random_array, number_of_elements * sizeof(unsigned)); if (0 > ret) { throw OSRMException("could not write random data file"); } TIMER_STOP(write_1gb); - close(f); + close(file_desc); #endif delete[] random_array; SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) << "s"; SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) - << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) - << "MB/sec"; + << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) << "MB/sec"; SimpleLogger().Write(logDEBUG) << "finished creation of random data. Flush disk cache now!"; @@ -164,8 +161,8 @@ int main(int argc, char *argv[]) #ifdef __linux__ char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned)); - int f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); - if (-1 == f) + 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); return -1; @@ -179,17 +176,16 @@ int main(int argc, char *argv[]) fd = fopen(test_path.string().c_str(), "r"); #endif #ifdef __linux__ - int ret = read(f, raw_array, number_of_elements * sizeof(unsigned)); + int ret = read(file_desc, raw_array, number_of_elements * sizeof(unsigned)); SimpleLogger().Write(logDEBUG) << "read " << ret << " bytes, error: " << strerror(errno); - close(f); - f = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); + close(file_desc); + file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); 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(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec"; @@ -200,7 +196,7 @@ int main(int argc, char *argv[]) fseek(fd, 0, SEEK_SET); #endif #ifdef __linux__ - lseek(f, 0, SEEK_SET); + 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; @@ -220,11 +216,11 @@ int main(int argc, char *argv[]) #endif #ifdef __linux__ - int ret1 = lseek(f, current_offset, SEEK_SET); - int ret2 = read(f, (char *)single_block, 4096); + int ret1 = lseek(file_desc, current_offset, SEEK_SET); + int ret2 = read(file_desc, (char *)single_block, 4096); #endif TIMER_STOP(random_access); - if (((off_t) - 1) == ret1) + if (((off_t)-1) == ret1) { SimpleLogger().Write(logWARNING) << "offset: " << current_offset; SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); @@ -261,7 +257,7 @@ int main(int argc, char *argv[]) fseek(fd, 0, SEEK_SET); #endif #ifdef __linux__ - lseek(f, 0, SEEK_SET); + lseek(file_desc, 0, SEEK_SET); #endif // read every 100th block @@ -280,12 +276,12 @@ int main(int argc, char *argv[]) #endif #ifdef __linux__ - int ret1 = lseek(f, current_offset, SEEK_SET); + int ret1 = lseek(file_desc, current_offset, SEEK_SET); - int ret2 = read(f, (char *)single_block, 4096); + int ret2 = read(file_desc, (char *)single_block, 4096); #endif TIMER_STOP(read_every_100); - if (((off_t) - 1) == ret1) + if (((off_t)-1) == ret1) { SimpleLogger().Write(logWARNING) << "offset: " << current_offset; SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); @@ -306,7 +302,7 @@ int main(int argc, char *argv[]) // free(single_block); #endif #ifdef __linux__ - close(f); + close(file_desc); #endif // Do statistics SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; diff --git a/3party/osrm/osrm-backend/Tools/simpleclient.cpp b/3party/osrm/osrm-backend/Tools/simpleclient.cpp index 68d4b1d6b7..b6714566a2 100644 --- a/3party/osrm/osrm-backend/Tools/simpleclient.cpp +++ b/3party/osrm/osrm-backend/Tools/simpleclient.cpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../Library/OSRM.h" #include "../Util/GitDescription.h" #include "../Util/ProgramOptions.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include #include @@ -80,8 +80,7 @@ int main(int argc, const char *argv[]) return 0; } - SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " - << "compiled at " << __DATE__ << ", " __TIME__; + SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; OSRM routing_machine(server_paths, use_shared_memory); diff --git a/3party/osrm/osrm-backend/Tools/springclean.cpp b/3party/osrm/osrm-backend/Tools/springclean.cpp new file mode 100644 index 0000000000..f528d3da38 --- /dev/null +++ b/3party/osrm/osrm-backend/Tools/springclean.cpp @@ -0,0 +1,102 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include + +#include "../DataStructures/SharedMemoryFactory.h" +#include "../Server/DataStructures/SharedDataType.h" +#include "../Util/GitDescription.h" +#include "../Util/simple_logger.hpp" + +void delete_region(const SharedDataType region) +{ + if (SharedMemory::RegionExists(region) && !SharedMemory::Remove(region)) + { + const std::string name = [&] + { + switch (region) + { + case CURRENT_REGIONS: + return "CURRENT_REGIONS"; + case LAYOUT_1: + return "LAYOUT_1"; + case DATA_1: + return "DATA_1"; + case LAYOUT_2: + return "LAYOUT_2"; + case DATA_2: + return "DATA_2"; + case LAYOUT_NONE: + return "LAYOUT_NONE"; + default: // DATA_NONE: + return "DATA_NONE"; + } + }(); + + 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"; + delete_region(DATA_1); + delete_region(LAYOUT_1); + delete_region(DATA_2); + delete_region(LAYOUT_2); + delete_region(CURRENT_REGIONS); +} + +int main() +{ + LogPolicy::GetInstance().Unmute(); + try + { + SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << "\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 " << + "by osrm-datastore? [type 'Y' to confirm]"; + + const auto letter = getchar(); + if (letter != 'Y') + { + SimpleLogger().Write() << "aborted."; + return 0; + } + springclean(); + } + catch (const std::exception &e) + { + SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + } + return 0; +} diff --git a/3party/osrm/osrm-backend/Tools/unlock_all_mutexes.cpp b/3party/osrm/osrm-backend/Tools/unlock_all_mutexes.cpp index 4d4156fa52..d448a2049c 100644 --- a/3party/osrm/osrm-backend/Tools/unlock_all_mutexes.cpp +++ b/3party/osrm/osrm-backend/Tools/unlock_all_mutexes.cpp @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../Util/GitDescription.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Server/DataStructures/SharedBarriers.h" #include @@ -36,8 +36,7 @@ int main() LogPolicy::GetInstance().Unmute(); try { - SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " - << "compiled at " << __DATE__ << ", " __TIME__; + SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; SimpleLogger().Write() << "Releasing all locks"; SharedBarriers barrier; barrier.pending_update_mutex.unlock(); diff --git a/3party/osrm/osrm-backend/UnitTests/DataStructures/StaticRTreeTest.cpp b/3party/osrm/osrm-backend/UnitTests/DataStructures/StaticRTreeTest.cpp index 8e7511daa0..46dbc4e4bb 100644 --- a/3party/osrm/osrm-backend/UnitTests/DataStructures/StaticRTreeTest.cpp +++ b/3party/osrm/osrm-backend/UnitTests/DataStructures/StaticRTreeTest.cpp @@ -1,7 +1,7 @@ #include "../../DataStructures/StaticRTree.h" #include "../../DataStructures/QueryNode.h" #include "../../DataStructures/EdgeBasedNode.h" -#include "../../Util/NumericUtil.h" +#include "../../Util/floating_point.hpp" #include "../../typedefs.h" #include @@ -97,7 +97,7 @@ class LinearSearchNN coords->at(e.u), coords->at(e.v), input_coordinate, nearest, current_ratio); if ((current_perpendicular_distance < min_dist) && - !EpsilonCompare(current_perpendicular_distance, min_dist)) + !osrm::epsilon_compare(current_perpendicular_distance, min_dist)) { // found a new minimum min_dist = current_perpendicular_distance; result_phantom_node = {e.forward_edge_based_node_id, @@ -109,7 +109,9 @@ class LinearSearchNN e.reverse_offset, e.packed_geometry_id, nearest, - e.fwd_segment_position}; + e.fwd_segment_position, + e.forward_travel_mode, + e.backward_travel_mode}; nearest_edge = e; } } diff --git a/3party/osrm/osrm-backend/Util/BoostFileSystemFix.h b/3party/osrm/osrm-backend/Util/BoostFileSystemFix.h index 1e1e98e0e1..d7049cc2e1 100644 --- a/3party/osrm/osrm-backend/Util/BoostFileSystemFix.h +++ b/3party/osrm/osrm-backend/Util/BoostFileSystemFix.h @@ -29,11 +29,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define BOOST_FILE_SYSTEM_FIX_H #include "OSRMException.h" -#include "SimpleLogger.h" -#include +// #include #include -#include +// #include // This is one big workaround for latest boost renaming woes. @@ -51,7 +50,7 @@ namespace filesystem // exists. The validate() function must be defined in the same namespace // as the target type, (boost::filesystem::path in this case), otherwise // it is not called -// inline void validate( +// void validate( // boost::any & v, // const std::vector & values, // boost::filesystem::path *, @@ -60,8 +59,6 @@ namespace filesystem // boost::program_options::validators::check_first_occurrence(v); // const std::string & input_string = // boost::program_options::validators::get_single_string(values); -// // SimpleLogger().Write() << "validator called for " << input_string; -// // SimpleLogger().Write() << "validator called for " << input_string; // if(boost::filesystem::is_regular_file(input_string)) { // v = boost::any(boost::filesystem::path(input_string)); // } else { @@ -71,7 +68,7 @@ namespace filesystem // adapted from: // http://stackoverflow.com/questions/1746136/how-do-i-normalize-a-pathname-using-boostfilesystem -inline boost::filesystem::path +boost::filesystem::path portable_canonical(const boost::filesystem::path &relative_path, const boost::filesystem::path ¤t_path = boost::filesystem::current_path()) { @@ -118,15 +115,15 @@ portable_canonical(const boost::filesystem::path &relative_path, #if BOOST_FILESYSTEM_VERSION < 3 -inline path temp_directory_path() +path temp_directory_path() { char *buffer; - buffer = tmpnam(NULL); + buffer = tmpnam(nullptr); return path(buffer); } -inline path unique_path(const path &) { return temp_directory_path(); } +path unique_path(const path &) { return temp_directory_path(); } #endif } @@ -136,7 +133,7 @@ inline path unique_path(const path &) { return temp_directory_path(); } #define BOOST_FILESYSTEM_VERSION 3 #endif -inline void AssertPathExists(const boost::filesystem::path &path) +void AssertPathExists(const boost::filesystem::path &path) { if (!boost::filesystem::is_regular_file(path)) { diff --git a/3party/osrm/osrm-backend/Util/DataStoreOptions.h b/3party/osrm/osrm-backend/Util/DataStoreOptions.h index 7a76bfb6ae..f67b12d727 100644 --- a/3party/osrm/osrm-backend/Util/DataStoreOptions.h +++ b/3party/osrm/osrm-backend/Util/DataStoreOptions.h @@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "GitDescription.h" #include "IniFileUtil.h" #include "OSRMException.h" -#include "SimpleLogger.h" +#include "simple_logger.hpp" #include @@ -43,7 +43,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include // generate boost::program_options object for the routing part -inline bool GenerateDataStoreOptions(const int argc, const char *argv[], ServerPaths &paths, bool & springclean) +bool GenerateDataStoreOptions(const int argc, const char *argv[], ServerPaths &paths) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); @@ -122,11 +122,6 @@ inline bool GenerateDataStoreOptions(const int argc, const char *argv[], ServerP return false; } - if (option_variables.count("springclean")) - { - springclean = true; - return true; - } boost::program_options::notify(option_variables); const bool parameter_present = (paths.find("hsgrdata") != paths.end() && diff --git a/3party/osrm/osrm-backend/Util/FingerPrint.cpp.in b/3party/osrm/osrm-backend/Util/FingerPrint.cpp.in index d074a2079e..c3bf0c035f 100644 --- a/3party/osrm/osrm-backend/Util/FingerPrint.cpp.in +++ b/3party/osrm/osrm-backend/Util/FingerPrint.cpp.in @@ -45,8 +45,7 @@ FingerPrint::FingerPrint() : magic_number(1297240911) md5_prepare[32] = md5_tree[32] = md5_graph[32] = md5_objects[32] = '\0'; boost::uuids::name_generator gen(named_uuid); - std::string temp_string(__DATE__); - temp_string += __TIME__; + std::string temp_string; std::memcpy(md5_prepare, MD5PREPARE, strlen(MD5PREPARE)); temp_string += md5_prepare; diff --git a/3party/osrm/osrm-backend/Util/GraphLoader.h b/3party/osrm/osrm-backend/Util/GraphLoader.h index 636994642a..94cb190379 100644 --- a/3party/osrm/osrm-backend/Util/GraphLoader.h +++ b/3party/osrm/osrm-backend/Util/GraphLoader.h @@ -33,7 +33,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../DataStructures/ImportEdge.h" #include "../DataStructures/QueryNode.h" #include "../DataStructures/Restriction.h" -#include "../Util/SimpleLogger.h" +#include "../Util/simple_logger.hpp" #include "../Util/FingerPrint.h" #include "../typedefs.h" @@ -41,6 +41,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +#include + #include #include @@ -124,26 +126,22 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream, edge_list.reserve(m); EdgeWeight weight; - short type; NodeID nameID; int length; - bool is_roundabout, ignore_in_grid, is_access_restricted, is_contra_flow, is_split; - unsigned way_id; - + bool is_roundabout, ignore_in_grid, is_access_restricted, is_split; + TravelMode travel_mode; for (EdgeID i = 0; i < m; ++i) { - input_stream.read((char *)&way_id, sizeof(unsigned)); input_stream.read((char *)&source, sizeof(unsigned)); input_stream.read((char *)&target, sizeof(unsigned)); input_stream.read((char *)&length, sizeof(int)); input_stream.read((char *)&dir, sizeof(short)); input_stream.read((char *)&weight, sizeof(int)); - input_stream.read((char *)&type, sizeof(short)); input_stream.read((char *)&nameID, sizeof(unsigned)); input_stream.read((char *)&is_roundabout, sizeof(bool)); input_stream.read((char *)&ignore_in_grid, sizeof(bool)); input_stream.read((char *)&is_access_restricted, sizeof(bool)); - input_stream.read((char *)&is_contra_flow, sizeof(bool)); + input_stream.read((char *)&travel_mode, sizeof(TravelMode)); input_stream.read((char *)&is_split, sizeof(bool)); BOOST_ASSERT_MSG(length > 0, "loaded null length edge"); @@ -161,8 +159,6 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream, forward = false; } - BOOST_ASSERT(type >= 0); - // translate the external NodeIDs to internal IDs auto internal_id_iter = ext_to_int_id_map.find(source); if (ext_to_int_id_map.find(source) == ext_to_int_id_map.end()) @@ -190,22 +186,20 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream, std::swap(forward, backward); } - edge_list.emplace_back(way_id, - source, + edge_list.emplace_back(source, target, nameID, weight, forward, backward, - type, is_roundabout, ignore_in_grid, is_access_restricted, - is_contra_flow, + travel_mode, is_split); } - std::sort(edge_list.begin(), edge_list.end()); + tbb::parallel_sort(edge_list.begin(), edge_list.end()); for (unsigned i = 1; i < edge_list.size(); ++i) { if ((edge_list[i - 1].target == edge_list[i].target) && @@ -304,34 +298,29 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream, edge_list.reserve(m); EdgeWeight weight; - short type; NodeID nameID; int length; - unsigned way_id; - bool is_roundabout, ignore_in_grid, is_access_restricted, is_contra_flow, is_split; + bool is_roundabout, ignore_in_grid, is_access_restricted, is_split; + TravelMode travel_mode; for (EdgeID i = 0; i < m; ++i) { - input_stream.read((char *)&way_id, sizeof(unsigned)); input_stream.read((char *)&source, sizeof(unsigned)); input_stream.read((char *)&target, sizeof(unsigned)); input_stream.read((char *)&length, sizeof(int)); input_stream.read((char *)&dir, sizeof(short)); input_stream.read((char *)&weight, sizeof(int)); - input_stream.read((char *)&type, sizeof(short)); input_stream.read((char *)&nameID, sizeof(unsigned)); input_stream.read((char *)&is_roundabout, sizeof(bool)); input_stream.read((char *)&ignore_in_grid, sizeof(bool)); input_stream.read((char *)&is_access_restricted, sizeof(bool)); - input_stream.read((char *)&is_contra_flow, sizeof(bool)); + input_stream.read((char *)&travel_mode, sizeof(TravelMode)); input_stream.read((char *)&is_split, sizeof(bool)); BOOST_ASSERT_MSG(length > 0, "loaded null length edge"); BOOST_ASSERT_MSG(weight > 0, "loaded null weight"); BOOST_ASSERT_MSG(0 <= dir && dir <= 2, "loaded bogus direction"); - BOOST_ASSERT(type >= 0); - // translate the external NodeIDs to internal IDs auto internal_id_iter = ext_to_int_id_map.find(source); if (ext_to_int_id_map.find(source) == ext_to_int_id_map.end()) @@ -362,7 +351,7 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream, target); } - std::sort(edge_list.begin(), edge_list.end()); + tbb::parallel_sort(edge_list.begin(), edge_list.end()); for (unsigned i = 1; i < edge_list.size(); ++i) { if ((edge_list[i - 1].target == edge_list[i].target) && diff --git a/3party/osrm/osrm-backend/Util/MachineInfo.h b/3party/osrm/osrm-backend/Util/MachineInfo.h index c5cb0522b6..a9a88a1ec0 100644 --- a/3party/osrm/osrm-backend/Util/MachineInfo.h +++ b/3party/osrm/osrm-backend/Util/MachineInfo.h @@ -33,7 +33,7 @@ enum Endianness BigEndian = 2 }; // Function is optimized to a single 'mov eax,1' on GCC, clang and icc using -O3 -inline Endianness GetMachineEndianness() +Endianness GetMachineEndianness() { int i(1); char *p = (char *)&i; @@ -45,7 +45,7 @@ inline Endianness GetMachineEndianness() } // Reverses Network Byte Order into something usable, compiles down to a bswap-mov combination -inline unsigned SwapEndian(unsigned x) +unsigned SwapEndian(unsigned x) { if (GetMachineEndianness() == LittleEndian) { diff --git a/3party/osrm/osrm-backend/Util/MercatorUtil.h b/3party/osrm/osrm-backend/Util/MercatorUtil.h index 31d1139bef..b4a15b779c 100644 --- a/3party/osrm/osrm-backend/Util/MercatorUtil.h +++ b/3party/osrm/osrm-backend/Util/MercatorUtil.h @@ -30,14 +30,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -inline float y2lat(const float a) +inline double y2lat(const double a) { - return 180.f * static_cast(M_1_PI) * (2.f * std::atan(std::exp(a * static_cast(M_PI) / 180.f)) - static_cast(M_PI_2)); + return 180. * M_1_PI * (2. * std::atan(std::exp(a * M_PI / 180.)) - M_PI_2); } -inline float lat2y(const float a) +inline double lat2y(const double a) { - return 180.f * static_cast(M_1_PI) * std::log(std::tan(static_cast(M_PI_4) + a * (static_cast(M_PI) / 180.f) / 2.f)); + return 180. * M_1_PI * std::log(std::tan(M_PI_4 + a * (M_PI / 180.) / 2.)); } #endif // MERCATOR_UTIL_H diff --git a/3party/osrm/osrm-backend/Util/ProgramOptions.h b/3party/osrm/osrm-backend/Util/ProgramOptions.h index c6e5448a69..bde9766a65 100644 --- a/3party/osrm/osrm-backend/Util/ProgramOptions.h +++ b/3party/osrm/osrm-backend/Util/ProgramOptions.h @@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "GitDescription.h" #include "IniFileUtil.h" #include "OSRMException.h" -#include "SimpleLogger.h" +#include "simple_logger.hpp" #include @@ -45,6 +45,104 @@ const static unsigned INIT_OK_START_ENGINE = 0; const static unsigned INIT_OK_DO_NOT_START_ENGINE = 1; const static unsigned INIT_FAILED = -1; +inline void populate_base_path(ServerPaths &server_paths) +{ + // populate the server_path object + auto path_iterator = server_paths.find("base"); + + // if a base path has been set, we populate it. + if (path_iterator != server_paths.end()) + { + const std::string base_string = path_iterator->second.string(); + SimpleLogger().Write() << "populating base path: " << base_string; + + server_paths["hsgrdata"] = base_string + ".hsgr"; + BOOST_ASSERT(server_paths.find("hsgrdata") != server_paths.end()); + server_paths["nodesdata"] = base_string + ".nodes"; + BOOST_ASSERT(server_paths.find("nodesdata") != server_paths.end()); + server_paths["edgesdata"] = base_string + ".edges"; + BOOST_ASSERT(server_paths.find("edgesdata") != server_paths.end()); + server_paths["geometries"] = base_string + ".geometry"; + BOOST_ASSERT(server_paths.find("geometries") != server_paths.end()); + server_paths["ramindex"] = base_string + ".ramIndex"; + BOOST_ASSERT(server_paths.find("ramindex") != server_paths.end()); + server_paths["fileindex"] = base_string + ".fileIndex"; + BOOST_ASSERT(server_paths.find("fileindex") != server_paths.end()); + server_paths["namesdata"] = base_string + ".names"; + BOOST_ASSERT(server_paths.find("namesdata") != server_paths.end()); + server_paths["timestamp"] = base_string + ".timestamp"; + BOOST_ASSERT(server_paths.find("timestamp") != server_paths.end()); + } + + // check if files are give and whether they exist at all + path_iterator = server_paths.find("hsgrdata"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + if (path_iterator == server_paths.end()) + { + SimpleLogger().Write() << "hsgrdata unset"; + } + if (!boost::filesystem::is_regular_file(path_iterator->second)) + { + SimpleLogger().Write() << "not a regular file"; + } + + throw OSRMException(".hsgr not found: " + path_iterator->second.string()); + } + + path_iterator = server_paths.find("nodesdata"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".nodes not found"); + } + + path_iterator = server_paths.find("edgesdata"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".edges not found"); + } + + path_iterator = server_paths.find("geometries"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".geometry not found"); + } + + path_iterator = server_paths.find("ramindex"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".ramIndex not found"); + } + + path_iterator = server_paths.find("fileindex"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".fileIndex not found"); + } + + path_iterator = server_paths.find("namesdata"); + if (path_iterator == server_paths.end() || + !boost::filesystem::is_regular_file(path_iterator->second)) + { + throw OSRMException(".namesIndex not found"); + } + + SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; + SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"]; + SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"]; + SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"]; + SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"]; + SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"]; + SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"]; + SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"]; +} + // generate boost::program_options object for the routing part inline unsigned GenerateServerProgramOptions(const int argc, const char *argv[], @@ -55,7 +153,6 @@ inline unsigned GenerateServerProgramOptions(const int argc, bool &use_shared_memory, bool &trial) { - // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( @@ -169,94 +266,6 @@ inline unsigned GenerateServerProgramOptions(const int argc, if (!use_shared_memory && option_variables.count("base")) { - path_iterator = paths.find("base"); - BOOST_ASSERT(paths.end() != path_iterator); - std::string base_string = path_iterator->second.string(); - - path_iterator = paths.find("hsgrdata"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".hsgr"; - } - else - { - throw OSRMException(base_string + ".hsgr not found"); - } - - path_iterator = paths.find("nodesdata"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".nodes"; - } - else - { - throw OSRMException(base_string + ".nodes not found"); - } - - path_iterator = paths.find("edgesdata"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".edges"; - } - else - { - throw OSRMException(base_string + ".edges not found"); - } - - path_iterator = paths.find("geometries"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".geometry"; - } - else - { - throw OSRMException(base_string + ".geometry not found"); - } - - path_iterator = paths.find("ramindex"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".ramIndex"; - } - else - { - throw OSRMException(base_string + ".ramIndex not found"); - } - - path_iterator = paths.find("fileindex"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".fileIndex"; - } - else - { - throw OSRMException(base_string + ".fileIndex not found"); - } - - path_iterator = paths.find("namesdata"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".names"; - } - else - { - throw OSRMException(base_string + ".namesIndex not found"); - } - - path_iterator = paths.find("timestamp"); - if (path_iterator != paths.end() && - !boost::filesystem::is_regular_file(path_iterator->second)) - { - path_iterator->second = base_string + ".timestamp"; - } - return INIT_OK_START_ENGINE; } if (use_shared_memory && !option_variables.count("base")) diff --git a/3party/osrm/osrm-backend/Util/SimpleLogger.h b/3party/osrm/osrm-backend/Util/SimpleLogger.h deleted file mode 100644 index 648b65db66..0000000000 --- a/3party/osrm/osrm-backend/Util/SimpleLogger.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - -Copyright (c) 2013, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef SIMPLE_LOGGER_H -#define SIMPLE_LOGGER_H - -#include - -#include - -#ifdef _MSC_VER -#include -#define isatty _isatty -#define fileno _fileno -#else -#include -#endif - -#include -#include -#include -#include -#include - -enum LogLevel -{ logINFO, - logWARNING, - logDEBUG }; - -const char COL_RESET[] = "\x1b[0m"; -const char RED[] = "\x1b[31m"; -const char GREEN[] = "\x1b[32m"; -const char YELLOW[] = "\x1b[33m"; -const char BLUE[] = "\x1b[34m"; -const char MAGENTA[] = "\x1b[35m"; -const char CYAN[] = "\x1b[36m"; - -class LogPolicy -{ - public: - void Unmute() { m_is_mute = false; } - - void Mute() { m_is_mute = true; } - - bool IsMute() const { return m_is_mute; } - - static LogPolicy &GetInstance() - { - static LogPolicy runningInstance; - return runningInstance; - } - - LogPolicy(const LogPolicy &) = delete; - - private: - LogPolicy() : m_is_mute(true) {} - std::atomic m_is_mute; -}; - -class SimpleLogger -{ - public: - SimpleLogger() : level(logINFO) {} - - std::mutex& get_mutex() - { - static std::mutex m; - return m; - } - - - std::ostringstream &Write(LogLevel l = logINFO) - { - std::lock_guard lock(get_mutex()); - try - { - level = l; - os << "["; - switch (level) - { - case logINFO: - os << "info"; - break; - case logWARNING: - os << "warn"; - break; - case logDEBUG: -#ifndef NDEBUG - os << "debug"; -#endif - break; - default: - BOOST_ASSERT_MSG(false, "should not happen"); - break; - } - os << "] "; - } - catch (...) {} - return os; - } - - virtual ~SimpleLogger() - { - std::lock_guard lock(get_mutex()); - if (!LogPolicy::GetInstance().IsMute()) - { - const bool is_terminal = ( 0 != isatty(fileno(stdout)) ? true : false); - switch (level) - { - case logINFO: - std::cout << os.str() << (is_terminal ? COL_RESET : "") << std::endl; - break; - case logWARNING: - std::cerr << (is_terminal ? RED : "") << os.str() << (is_terminal ? COL_RESET : "") - << std::endl; - break; - case logDEBUG: -#ifndef NDEBUG - std::cout << (is_terminal ? YELLOW : "") << os.str() - << (is_terminal ? COL_RESET : "") << std::endl; -#endif - break; - default: - BOOST_ASSERT_MSG(false, "should not happen"); - break; - } - } - } - - private: - LogLevel level; - std::ostringstream os; -}; - -#endif /* SIMPLE_LOGGER_H */ diff --git a/3party/osrm/osrm-backend/Util/StdHashExtensions.h b/3party/osrm/osrm-backend/Util/StdHashExtensions.h index 50cd337ee2..0d310d3c39 100644 --- a/3party/osrm/osrm-backend/Util/StdHashExtensions.h +++ b/3party/osrm/osrm-backend/Util/StdHashExtensions.h @@ -32,32 +32,36 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // this is largely inspired by boost's hash combine as can be found in // "The C++ Standard Library" 2nd Edition. Nicolai M. Josuttis. 2012. + +namespace { + template -inline void hash_combine(std::size_t &seed, const T& val) +void hash_combine(std::size_t &seed, const T& val) { seed ^= std::hash()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } template -inline void hash_val(std::size_t &seed, const T& val) +void hash_val(std::size_t &seed, const T& val) { hash_combine(seed, val); } template -inline void hash_val(std::size_t &seed, const T& val, const Types& ... args) +void hash_val(std::size_t &seed, const T& val, const Types& ... args) { hash_combine(seed, val); hash_val(seed, args ...); } template -inline std::size_t hash_val( const Types&... args) +std::size_t hash_val(const Types&... args) { std::size_t seed = 0; hash_val(seed, args...); return seed; } +} namespace std { diff --git a/3party/osrm/osrm-backend/Util/StringUtil.h b/3party/osrm/osrm-backend/Util/StringUtil.h index 94705d8100..3c9375ca73 100644 --- a/3party/osrm/osrm-backend/Util/StringUtil.h +++ b/3party/osrm/osrm-backend/Util/StringUtil.h @@ -29,13 +29,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define STRINGUTIL_H #include -#include -#include #include #include #include -#include #include // precision: position after decimal point @@ -74,151 +71,6 @@ template static inline char *printInt(char *buffer, return buffer; } -// convert scoped enums to integers -template -auto as_integer(Enumeration const value) - -> typename std::underlying_type::type -{ - return static_cast::type>(value); -} - -static inline std::string IntToString(const int value) -{ - std::string output; - std::back_insert_iterator sink(output); - boost::spirit::karma::generate(sink, boost::spirit::karma::int_, value); - return output; -} - -static inline std::string UintToString(const unsigned value) -{ - std::string output; - std::back_insert_iterator sink(output); - boost::spirit::karma::generate(sink, boost::spirit::karma::uint_, value); - return output; -} - -static inline void int64ToString(const int64_t value, std::string &output) -{ - output.clear(); - std::back_insert_iterator sink(output); - boost::spirit::karma::generate(sink, boost::spirit::karma::long_long, value); -} - -static inline int StringToInt(const std::string &input) -{ - auto first_digit = input.begin(); - // Delete any trailing white-spaces - while (first_digit != input.end() && std::isspace(*first_digit)) - { - ++first_digit; - } - int value = 0; - boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::int_, value); - return value; -} - -static inline unsigned StringToUint(const std::string &input) -{ - auto first_digit = input.begin(); - // Delete any trailing white-spaces - while (first_digit != input.end() && (std::isspace(*first_digit) || '-' == *first_digit)) - { - ++first_digit; - } - unsigned value = 0; - boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::uint_, value); - return value; -} - -static inline uint64_t StringToInt64(const std::string &input) -{ - auto first_digit = input.begin(); - // Delete any trailing white-spaces - while (first_digit != input.end() && std::isspace(*first_digit)) - { - ++first_digit; - } - uint64_t value = 0; - boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::long_long, value); - return value; -} - -// source: http://tinodidriksen.com/2011/05/28/cpp-convert-string-to-double-speed/ -static inline double StringToDouble(const char *p) -{ - double r = 0.0; - bool neg = false; - if (*p == '-') - { - neg = true; - ++p; - } - while (*p >= '0' && *p <= '9') - { - r = (r * 10.0) + (*p - '0'); - ++p; - } - if (*p == '.') - { - double f = 0.0; - int n = 0; - ++p; - while (*p >= '0' && *p <= '9') - { - f = (f * 10.0) + (*p - '0'); - ++p; - ++n; - } - r += f / std::pow(10.0, n); - } - if (neg) - { - r = -r; - } - return r; -} - -template -struct scientific_policy : boost::spirit::karma::real_policies -{ - // we want the numbers always to be in fixed format - static int floatfield(T n) { return boost::spirit::karma::real_policies::fmtflags::fixed; } - static unsigned int precision(T) { return 6; } -}; -typedef -boost::spirit::karma::real_generator > -science_type; - -static inline std::string FixedDoubleToString(const double value) -{ - std::string output; - std::back_insert_iterator sink(output); - boost::spirit::karma::generate(sink, science_type(), value); - if (output.size() >= 2 && output[output.size()-2] == '.' && output[output.size()-1] == '0') - { - output.resize(output.size()-2); - } - return output; -} - -static inline std::string DoubleToString(const double value) -{ - std::string output; - std::back_insert_iterator sink(output); - boost::spirit::karma::generate(sink, value); - return output; -} - -static inline void doubleToStringWithTwoDigitsBehindComma(const double value, std::string &output) -{ - // The largest 32-bit integer is 4294967295, that is 10 chars - // On the safe side, add 1 for sign, and 1 for trailing zero - char buffer[12]; - sprintf(buffer, "%g", value); - output = buffer; -} - inline void replaceAll(std::string &s, const std::string &sub, const std::string &other) { boost::replace_all(s, sub, other); @@ -265,8 +117,8 @@ inline std::string EscapeJSONString(const std::string &input) } static std::string originals[] = {"&", "\"", "<", ">", "'", "[", "]", "\\"}; -static std::string entities[] = {"&", """, "<", ">", - "'", "&91;", "&93;", " \"}; +static std::string entities[] = { + "&", """, "<", ">", "'", "&91;", "&93;", " \"}; inline std::size_t URIDecode(const std::string &input, std::string &output) { @@ -294,6 +146,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); } +// TODO: remove after switch to libosmium inline bool StringStartsWith(const std::string &input, const std::string &prefix) { return boost::starts_with(input, prefix); diff --git a/3party/osrm/osrm-backend/Util/TrigonometryTables.h b/3party/osrm/osrm-backend/Util/TrigonometryTables.h index d14540482d..64076a23c3 100644 --- a/3party/osrm/osrm-backend/Util/TrigonometryTables.h +++ b/3party/osrm/osrm-backend/Util/TrigonometryTables.h @@ -722,7 +722,7 @@ constexpr unsigned short atan_table[4096] = { // max value is pi/4 constexpr double SCALING_FACTOR = 4. / M_PI * 0xFFFF; -inline double atan2_lookup(double y, double x) +double atan2_lookup(double y, double x) { if (std::abs(x) < std::numeric_limits::epsilon()) { diff --git a/3party/osrm/osrm-backend/Util/cast.hpp b/3party/osrm/osrm-backend/Util/cast.hpp new file mode 100644 index 0000000000..7807eda9ac --- /dev/null +++ b/3party/osrm/osrm-backend/Util/cast.hpp @@ -0,0 +1,188 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef CAST_HPP +#define CAST_HPP + +#include +#include + +#include +#include + +struct cast +{ + // convert scoped enums to integers + template + static auto enum_to_underlying(Enumeration const value) -> typename std::underlying_type::type + { + return static_cast::type>(value); + } + + template + static typename std::enable_if::value, std::string>::type + integral_to_string(const Number value) + { + std::string output; + std::back_insert_iterator sink(output); + + if (8 == sizeof(Number)) + { + boost::spirit::karma::generate(sink, boost::spirit::karma::long_long, value); + } + else + { + if (std::is_signed::value) + { + boost::spirit::karma::generate(sink, boost::spirit::karma::int_, value); + } + else + { + boost::spirit::karma::generate(sink, boost::spirit::karma::uint_, value); + } + } + return output; + } + + static int string_to_int(const std::string &input) + { + auto first_digit = input.begin(); + // Delete any trailing white-spaces + while (first_digit != input.end() && std::isspace(*first_digit)) + { + ++first_digit; + } + int value = 0; + boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::int_, value); + return value; + } + + static unsigned string_to_uint(const std::string &input) + { + auto first_digit = input.begin(); + // Delete any trailing white-spaces + while (first_digit != input.end() && (std::isspace(*first_digit) || '-' == *first_digit)) + { + ++first_digit; + } + unsigned value = 0; + boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::uint_, value); + return value; + } + + static uint64_t string_to_uint64(const std::string &input) + { + auto first_digit = input.begin(); + // Delete any trailing white-spaces + while (first_digit != input.end() && std::isspace(*first_digit)) + { + ++first_digit; + } + uint64_t value = 0; + boost::spirit::qi::parse(first_digit, input.end(), boost::spirit::long_long, value); + return value; + } + + // source: http://tinodidriksen.com/2011/05/28/cpp-convert-string-to-double-speed/ + static double string_to_double(const char *p) + { + double r = 0.0; + bool neg = false; + if (*p == '-') + { + neg = true; + ++p; + } + while (*p >= '0' && *p <= '9') + { + r = (r * 10.0) + (*p - '0'); + ++p; + } + if (*p == '.') + { + double f = 0.0; + int n = 0; + ++p; + while (*p >= '0' && *p <= '9') + { + f = (f * 10.0) + (*p - '0'); + ++p; + ++n; + } + r += f / std::pow(10.0, n); + } + if (neg) + { + r = -r; + } + return r; + } + + template struct scientific_policy : boost::spirit::karma::real_policies + { + // we want the numbers always to be in fixed format + static int floatfield(T n) + { + return boost::spirit::karma::real_policies::fmtflags::fixed; + } + static unsigned int precision(T) { return 6; } + }; + typedef boost::spirit::karma::real_generator> science_type; + + static std::string double_fixed_to_string(const double value) + { + std::string output; + std::back_insert_iterator sink(output); + boost::spirit::karma::generate(sink, science_type(), value); + if (output.size() >= 2 && output[output.size() - 2] == '.' && + output[output.size() - 1] == '0') + { + output.resize(output.size() - 2); + } + return output; + } + + static std::string double_to_string(const double value) + { + std::string output; + std::back_insert_iterator sink(output); + boost::spirit::karma::generate(sink, value); + return output; + } + + static void double_with_two_digits_to_string(const double value, + std::string &output) + { + // The largest 32-bit integer is 4294967295, that is 10 chars + // On the safe side, add 1 for sign, and 1 for trailing zero + char buffer[12]; + sprintf(buffer, "%g", value); + output = buffer; + } +}; + +#endif // CAST_HPP diff --git a/3party/osrm/osrm-backend/Util/ComputeAngle.h b/3party/osrm/osrm-backend/Util/compute_angle.cpp similarity index 77% rename from 3party/osrm/osrm-backend/Util/ComputeAngle.h rename to 3party/osrm/osrm-backend/Util/compute_angle.cpp index 02f678a075..b6350e445f 100644 --- a/3party/osrm/osrm-backend/Util/ComputeAngle.h +++ b/3party/osrm/osrm-backend/Util/compute_angle.cpp @@ -25,33 +25,27 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef COMPUTE_ANGLE_H -#define COMPUTE_ANGLE_H +#include "compute_angle.hpp" #include "TrigonometryTables.h" #include "../Util/MercatorUtil.h" #include -#include #include -/* Get angle of line segment (A,C)->(C,B), atan2 magic, formerly cosine theorem*/ -template -inline static double GetAngleBetweenThreeFixedPointCoordinates(const CoordinateT &A, - const CoordinateT &C, - const CoordinateT &B) +double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &A, + const FixedPointCoordinate &C, + const FixedPointCoordinate &B) { const double v1x = (A.lon - C.lon) / COORDINATE_PRECISION; const double v1y = lat2y(A.lat / COORDINATE_PRECISION) - lat2y(C.lat / COORDINATE_PRECISION); const double v2x = (B.lon - C.lon) / COORDINATE_PRECISION; const double v2y = lat2y(B.lat / COORDINATE_PRECISION) - lat2y(C.lat / COORDINATE_PRECISION); - double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180 / M_PI; - while (angle < 0) + double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; + while (angle < 0.) { - angle += 360; + angle += 360.; } return angle; } - -#endif // COMPUTE_ANGLE_H diff --git a/3party/osrm/osrm-backend/Util/compute_angle.hpp b/3party/osrm/osrm-backend/Util/compute_angle.hpp new file mode 100644 index 0000000000..72c861a45d --- /dev/null +++ b/3party/osrm/osrm-backend/Util/compute_angle.hpp @@ -0,0 +1,41 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef COMPUTE_ANGLE_HPP +#define COMPUTE_ANGLE_HPP + +struct FixedPointCoordinate; +struct NodeInfo; + +struct ComputeAngle +{ + /* Get angle of line segment (A,C)->(C,B), atan2 magic, formerly cosine theorem*/ + static double OfThreeFixedPointCoordinates(const FixedPointCoordinate &A, + const FixedPointCoordinate &C, + const FixedPointCoordinate &B); +}; +#endif // COMPUTE_ANGLE_HPP diff --git a/3party/osrm/osrm-backend/Util/ContainerUtils.h b/3party/osrm/osrm-backend/Util/container.hpp similarity index 81% rename from 3party/osrm/osrm-backend/Util/ContainerUtils.h rename to 3party/osrm/osrm-backend/Util/container.hpp index ae61a15b09..86e9de31ca 100644 --- a/3party/osrm/osrm-backend/Util/ContainerUtils.h +++ b/3party/osrm/osrm-backend/Util/container.hpp @@ -25,26 +25,29 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef CONTAINERUTILS_H_ -#define CONTAINERUTILS_H_ +#ifndef CONTAINER_HPP_ +#define CONTAINER_HPP_ #include +#include #include -template inline void sort_unique_resize(std::vector &vector) +namespace osrm +{ +template void sort_unique_resize(std::vector &vector) { std::sort(vector.begin(), vector.end()); const auto number_of_unique_elements = std::unique(vector.begin(), vector.end()) - vector.begin(); vector.resize(number_of_unique_elements); } -// template inline void sort_unique_resize_shrink_vector(std::vector &vector) +// template void sort_unique_resize_shrink_vector(std::vector &vector) // { // sort_unique_resize(vector); // vector.shrink_to_fit(); // } -// template inline void remove_consecutive_duplicates_from_vector(std::vector &vector) +// template void remove_consecutive_duplicates_from_vector(std::vector &vector) // { // const auto number_of_unique_elements = std::unique(vector.begin(), vector.end()) - vector.begin(); // vector.resize(number_of_unique_elements); @@ -58,15 +61,15 @@ Function for_each_pair(ForwardIterator begin, ForwardIterator end, Function func return function; } - ForwardIterator next = begin; - ++next; + auto next = begin; + next = std::next(next); while (next != end) { function(*begin, *next); - ++begin; ++next; + begin = std::next(begin); next = std::next(next); } return function; } - -#endif /* CONTAINERUTILS_H_ */ +} +#endif /* CONTAINER_HPP_ */ diff --git a/3party/osrm/osrm-backend/Util/floating_point.hpp b/3party/osrm/osrm-backend/Util/floating_point.hpp new file mode 100644 index 0000000000..5c4810279a --- /dev/null +++ b/3party/osrm/osrm-backend/Util/floating_point.hpp @@ -0,0 +1,44 @@ +/* +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef FLOATING_POINT_HPP +#define FLOATING_POINT_HPP + +#include + +#include +#include + +namespace osrm +{ +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/3party/osrm/osrm-backend/Util/make_unique.hpp b/3party/osrm/osrm-backend/Util/make_unique.hpp new file mode 100644 index 0000000000..07786feaac --- /dev/null +++ b/3party/osrm/osrm-backend/Util/make_unique.hpp @@ -0,0 +1,57 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef MAKE_UNIQUE_H_ +#define MAKE_UNIQUE_H_ + +#include +#include +#include + +namespace osrm +{ +// Taken from http://msdn.microsoft.com/en-us/library/dn439780.asp +// Note, that the snippet was broken there and needed minor massaging + +// make_unique +template std::unique_ptr make_unique(Types &&... Args) +{ + return (std::unique_ptr(new T(std::forward(Args)...))); +} + +// make_unique +template std::unique_ptr make_unique(std::size_t Size) +{ + return (std::unique_ptr(new T[Size]())); +} + +// make_unique disallowed +template +typename std::enable_if::value != 0, void>::type make_unique(Types &&...) = delete; +} + +#endif //MAKE_UNIQUE_H_ diff --git a/3party/osrm/osrm-backend/Util/simple_logger.cpp b/3party/osrm/osrm-backend/Util/simple_logger.cpp new file mode 100644 index 0000000000..5442f54c15 --- /dev/null +++ b/3party/osrm/osrm-backend/Util/simple_logger.cpp @@ -0,0 +1,135 @@ +/* + +Copyright (c) 2013, Project OSRM, Dennis Luxen, others +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include "simple_logger.hpp" + +#include "OSRMException.h" + +#include + +#include + +#ifdef _MSC_VER +#include +#define isatty _isatty +#define fileno _fileno +#else +#include +#endif + +#include +#include +#include + +namespace +{ +static const char COL_RESET[] { "\x1b[0m"}; +static const char RED[] { "\x1b[31m"}; +#ifndef NDEBUG +static const char YELLOW[] { "\x1b[33m"}; +#endif +// static const char GREEN[] { "\x1b[32m"}; +// static const char BLUE[] { "\x1b[34m"}; +// static const char MAGENTA[] { "\x1b[35m"}; +// static const char CYAN[] { "\x1b[36m"}; +} + +void LogPolicy::Unmute() { m_is_mute = false; } + +void LogPolicy::Mute() { m_is_mute = true; } + +bool LogPolicy::IsMute() const { return m_is_mute; } + +LogPolicy &LogPolicy::GetInstance() +{ + static LogPolicy runningInstance; + return runningInstance; +} + +SimpleLogger::SimpleLogger() : level(logINFO) {} + +std::mutex &SimpleLogger::get_mutex() +{ + static std::mutex m; + return m; +} + +std::ostringstream &SimpleLogger::Write(LogLevel l) +{ + std::lock_guard lock(get_mutex()); + try + { + level = l; + os << "["; + switch (level) + { + case logWARNING: + os << "warn"; + break; + case logDEBUG: +#ifndef NDEBUG + os << "debug"; +#endif + break; + default: //logINFO: + os << "info"; + break; + } + os << "] "; + } + catch (const std::exception &e) + { + // encapsulate in OSRMException + throw OSRMException(std::string(e.what()) + ", getting ostringstream"); + } + return os; +} + +SimpleLogger::~SimpleLogger() +{ + std::lock_guard lock(get_mutex()); + if (!LogPolicy::GetInstance().IsMute()) + { + const bool is_terminal = static_cast(isatty(fileno(stdout))); + switch (level) + { + case logWARNING: + std::cerr << (is_terminal ? RED : "") << os.str() << (is_terminal ? COL_RESET : "") + << std::endl; + break; + case logDEBUG: +#ifndef NDEBUG + std::cout << (is_terminal ? YELLOW : "") << os.str() << (is_terminal ? COL_RESET : "") + << std::endl; +#endif + break; + default: //logINFO: + std::cout << os.str() << (is_terminal ? COL_RESET : "") << std::endl; + break; + } + } +} diff --git a/3party/osrm/osrm-backend/Server/ServerFactory.h b/3party/osrm/osrm-backend/Util/simple_logger.hpp similarity index 64% rename from 3party/osrm/osrm-backend/Server/ServerFactory.h rename to 3party/osrm/osrm-backend/Util/simple_logger.hpp index 5e037cf058..2f7d1ed79b 100644 --- a/3party/osrm/osrm-backend/Server/ServerFactory.h +++ b/3party/osrm/osrm-backend/Util/simple_logger.hpp @@ -25,25 +25,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef SERVER_FACTORY_H -#define SERVER_FACTORY_H +#ifndef SIMPLE_LOGGER_HPP +#define SIMPLE_LOGGER_HPP -#include "Server.h" -#include "../Util/SimpleLogger.h" +#include +#include +#include -#include - -struct ServerFactory +enum LogLevel { - ServerFactory() = delete; - ServerFactory(const ServerFactory &) = delete; - static Server *CreateServer(std::string &ip_address, int ip_port, unsigned requested_num_threads) - { - 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 new Server(ip_address, ip_port, real_num_threads); - } + logINFO, + logWARNING, + logDEBUG }; -#endif // SERVER_FACTORY_H +class LogPolicy +{ + public: + void Unmute(); + + void Mute(); + + bool IsMute() const; + + static LogPolicy &GetInstance(); + + LogPolicy(const LogPolicy &) = delete; + + private: + LogPolicy() : m_is_mute(true) {} + std::atomic m_is_mute; +}; + +class SimpleLogger +{ + public: + SimpleLogger(); + + virtual ~SimpleLogger(); + std::mutex &get_mutex(); + std::ostringstream &Write(LogLevel l = logINFO); + + private: + LogLevel level; + std::ostringstream os; +}; + +#endif /* SIMPLE_LOGGER_HPP */ diff --git a/3party/osrm/osrm-backend/appveyor.yml b/3party/osrm/osrm-backend/appveyor.yml index 6635c5117b..9c3dcdee24 100644 --- a/3party/osrm/osrm-backend/appveyor.yml +++ b/3party/osrm/osrm-backend/appveyor.yml @@ -23,6 +23,7 @@ platform: x64 install: # by default, all script lines are interpreted as batch + - nuget install protobuf - cd c:\projects\osrm - curl -O http://build.project-osrm.org/libs_osrm_%Configuration%.7z - 7z x libs_osrm_%Configuration%.7z | find ":" @@ -33,16 +34,16 @@ build_script: - cd build - echo Running cmake... - call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 + - SET PATH=C:\Program Files (x86)\MSBuild\12.0\bin\;%PATH% - SET P=c:/projects/osrm - set TBB_INSTALL_DIR=%P%/tbb - set TBB_ARCH_PLATFORM=intel64/vc12 - - cmake .. -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=%Configuration% -DBZIP2_INCLUDE_DIR=%P%/libs/include -DBZIP2_LIBRARIES=%P%/libs/lib/libbz2.lib -DCMAKE_INSTALL_PREFIX=%P%/libs -DBOOST_ROOT=%P%/boost_min -DBoost_USE_STATIC_LIBS=ON - - nmake - - nmake tests - - nmake benchmarks + - cmake .. -G "Visual Studio 12 Win64" -DCMAKE_BUILD_TYPE=%Configuration% -DBZIP2_INCLUDE_DIR=%P%/libs/include -DBZIP2_LIBRARIES=%P%/libs/lib/libbz2.lib -DCMAKE_INSTALL_PREFIX=%P%/libs -DBOOST_ROOT=%P%/boost_min -DBoost_USE_STATIC_LIBS=ON -T CTP_Nov2013 + - msbuild /clp:Verbosity=minimal /nologo OSRM.sln + - msbuild /clp:Verbosity=minimal /nologo tests.vcxproj - if "%APPVEYOR_REPO_BRANCH%"=="develop" (7z a %P%/osrm_%Configuration%.zip *.exe *.pdb %P%/libs/bin/*.dll -tzip) - set PATH=%PATH%;c:/projects/osrm/libs/bin - - cd c:/projects/osrm/build + - cd c:/projects/osrm/build/%Configuration% - datastructure-tests.exe test: off diff --git a/3party/osrm/osrm-backend/cmake/CPackDebianConfig.cmake b/3party/osrm/osrm-backend/cmake/CPackDebianConfig.cmake new file mode 100644 index 0000000000..065c429001 --- /dev/null +++ b/3party/osrm/osrm-backend/cmake/CPackDebianConfig.cmake @@ -0,0 +1,44 @@ +IF(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + MESSAGE(FATAL_ERROR "Cannot configure CPack to generate Debian packages on non-linux systems.") +ENDIF() + +INCLUDE(FindDebArch) + +SET(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.md") +SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENCE.TXT") +SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CPACK_RESOURCE_FILE_README}") +SET(CPACK_PACKAGE_VERSION_MAJOR "0") +SET(CPACK_PACKAGE_VERSION_MINOR "4") +SET(CPACK_PACKAGE_VERSION_PATCH "3") + +SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") + +string(TOLOWER "${CMAKE_PROJECT_NAME}" LOWER_PROJECT_NAME) +SET(CPACK_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") +SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_VERSION}_orig") +SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Open Source Routing Machine (OSRM).") +SET(CPACK_PACKAGE_DESCRIPTION "Open Source Routing Machine (OSRM) is a routing engine.") + +# To create a proper Debian/Ubuntu package, the following CMake +# options should be used: + +SET(CPACK_STRIP_FILES "TRUE") +SET(CPACK_INCLUDE_TOPLEVEL_DIRECTORY "FALSE") +SET(CPACK_GENERATOR "DEB") + +SET(CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}${VERSION_SUFFIX}") +SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}${CPACK_PACKAGE_REVISION}") +SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Dennis Luxen ") +SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") +SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") +SET(CPACK_DEBIAN_PACKAGE_DESCRIPTION "Open Source Routing Machine (OSRM) is a high-performance routing engine. + It combines sophisticated routing algorithms with the open and free data of the OpenStreetMap." +) +SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6-dev, libprotobuf-dev, libosmpbf-dev, libbz2-1.0, libstxxl1, libxml2, libzip2, liblua5.1-0, libtbb2, libboost-all-dev") + +file(GLOB_RECURSE ProfileGlob ${CMAKE_SOURCE_DIR}/profiles/*) +install(FILES ${ProfileGlob} DESTINATION "share/doc/${LOWER_PROJECT_NAME}/profiles") +CONFIGURE_FILE (${CMAKE_SOURCE_DIR}/cmake/postinst.in postinst) +set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_BINARY_DIR}/postinst;${CMAKE_CURRENT_BINARY_DIR}/copyright;") + +MESSAGE(STATUS "Debian Package: ${CPACK_DEBIAN_PACKAGE_NAME} (${CPACK_DEBIAN_PACKAGE_VERSION}) [${CPACK_PACKAGE_FILE_NAME}.deb]") diff --git a/3party/osrm/osrm-backend/cmake/FindDebArch.cmake b/3party/osrm/osrm-backend/cmake/FindDebArch.cmake new file mode 100644 index 0000000000..5b405bc39b --- /dev/null +++ b/3party/osrm/osrm-backend/cmake/FindDebArch.cmake @@ -0,0 +1,19 @@ +# +# Copyright (C) 2013 Emmanuel Roullit +# + +IF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) + FIND_PROGRAM(DPKG_CMD dpkg) + IF(NOT DPKG_CMD) + EXECUTE_PROCESS(COMMAND uname -p + OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + MESSAGE(STATUS "Can not find dpkg in your path, default to uname -p: ${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.") + ELSE(NOT DPKG_CMD) + EXECUTE_PROCESS(COMMAND "${DPKG_CMD}" --print-architecture + OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + ENDIF(NOT DPKG_CMD) +ENDIF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE) diff --git a/3party/osrm/osrm-backend/cmake/check_luabind.cmake b/3party/osrm/osrm-backend/cmake/check_luabind.cmake new file mode 100644 index 0000000000..18f065666b --- /dev/null +++ b/3party/osrm/osrm-backend/cmake/check_luabind.cmake @@ -0,0 +1,40 @@ +INCLUDE (CheckCXXSourceCompiles) +unset(LUABIND_WORKS CACHE) +unset(LUABIND51_WORKS CACHE) +set (LUABIND_CHECK_SRC "#include \"lua.h\"\n#include \n int main() { lua_State *myLuaState = luaL_newstate(); luabind::open(myLuaState); return 0;}") +set (CMAKE_TRY_COMPILE_CONFIGURATION ${CMAKE_BUILD_TYPE}) +set (CMAKE_REQUIRED_INCLUDES "${Boost_INCLUDE_DIR};${LUABIND_INCLUDE_DIR};${LUA_INCLUDE_DIR}") +set (CMAKE_REQUIRED_LIBRARIES "${LUABIND_LIBRARY};${LUA_LIBRARY}") + +find_package(Lua52) +if(NOT APPLE) + find_package(LuaJIT 5.2) +endif() +if(LUA52_FOUND) + set (CMAKE_REQUIRED_INCLUDES "${Boost_INCLUDE_DIR};${LUABIND_INCLUDE_DIR};${LUA_INCLUDE_DIR}") + set (CMAKE_REQUIRED_LIBRARIES "${LUABIND_LIBRARY};${LUA_LIBRARY}") + CHECK_CXX_SOURCE_COMPILES("${LUABIND_CHECK_SRC}" LUABIND_WORKS) +endif() + +if(LUABIND_WORKS) + message(STATUS "Luabind/Lua5.2 combination working with ${LUA_LIBRARY}") +else() + message(STATUS "Luabind/Lua5.2 not feasible, falling back to Lua 5.1.") + unset(LUA_FOUND CACHE) + unset(LUA_INCLUDE_DIR CACHE) + unset(LUA_LIBRARY CACHE) + find_package(Lua51 REQUIRED) + if(NOT APPLE) + find_package(LuaJIT 5.1) + endif() + set (CMAKE_REQUIRED_INCLUDES "${Boost_INCLUDE_DIR};${LUABIND_INCLUDE_DIR};${LUA_INCLUDE_DIR}") + set (CMAKE_REQUIRED_LIBRARIES "${LUABIND_LIBRARY};${LUA_LIBRARY}") + + CHECK_CXX_SOURCE_COMPILES("${LUABIND_CHECK_SRC}" LUABIND51_WORKS) + + if(LUABIND51_WORKS) + message(STATUS "Luabind works with Lua 5.1 at ${LUA_LIBRARY}") + else() + message(FATAL_ERROR "Luabind does not work with Lua 5.1 at ${LUA_LIBRARY}, no working Luabind found") + endif() +endif() diff --git a/3party/osrm/osrm-backend/cmake/postinst.in b/3party/osrm/osrm-backend/cmake/postinst.in new file mode 100644 index 0000000000..92f2fde4fb --- /dev/null +++ b/3party/osrm/osrm-backend/cmake/postinst.in @@ -0,0 +1,2 @@ +#/usr/bin/env bash +ln -s /usr/share/doc/@CMAKE_PROJECT_NAME@/profiles/car.lua @CMAKE_INSTALL_PREFIX@/profile.lua diff --git a/3party/osrm/osrm-backend/datastore.cpp b/3party/osrm/osrm-backend/datastore.cpp index 34c4e0477e..e26ab4b8ac 100644 --- a/3party/osrm/osrm-backend/datastore.cpp +++ b/3party/osrm/osrm-backend/datastore.cpp @@ -38,15 +38,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Server/DataStructures/SharedBarriers.h" #include "Util/BoostFileSystemFix.h" #include "Util/DataStoreOptions.h" -#include "Util/SimpleLogger.h" +#include "Util/simple_logger.hpp" #include "Util/FingerPrint.h" #include "typedefs.h" #include -typedef BaseDataFacade::RTreeLeaf RTreeLeaf; -typedef StaticRTree::vector, true>::TreeNode RTreeNode; -typedef StaticGraph QueryGraph; +using RTreeLeaf = BaseDataFacade::RTreeLeaf; +using RTreeNode = StaticRTree::vector, true>::TreeNode; +using QueryGraph = StaticGraph; #ifdef __linux__ #include @@ -90,33 +90,21 @@ void delete_region(const SharedDataType region) } } -// find all existing shmem regions and remove them. -void springclean() -{ - SimpleLogger().Write() << "spring-cleaning all shared memory regions"; - delete_region(DATA_1); - delete_region(LAYOUT_1); - delete_region(DATA_2); - delete_region(LAYOUT_2); - delete_region(CURRENT_REGIONS); -} - int main(const int argc, const char *argv[]) { LogPolicy::GetInstance().Unmute(); SharedBarriers barrier; -#ifdef __linux__ - // try to disable swapping on Linux - const bool lock_flags = MCL_CURRENT | MCL_FUTURE; - if (-1 == mlockall(lock_flags)) - { - SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; - } -#endif - try { +#ifdef __linux__ + // try to disable swapping on Linux + const bool lock_flags = MCL_CURRENT | MCL_FUTURE; + if (-1 == mlockall(lock_flags)) + { + SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; + } +#endif try { boost::interprocess::scoped_lock pending_lock( @@ -138,16 +126,10 @@ int main(const int argc, const char *argv[]) SimpleLogger().Write(logDEBUG) << "Checking input parameters"; ServerPaths server_paths; - bool should_springclean = false; - if (!GenerateDataStoreOptions(argc, argv, server_paths, should_springclean)) + if (!GenerateDataStoreOptions(argc, argv, server_paths)) { return 0; } - if (should_springclean) - { - springclean(); - return 0; - } if (server_paths.find("hsgrdata") == server_paths.end()) { @@ -267,6 +249,8 @@ int main(const int argc, const char *argv[]) number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_ID_LIST, number_of_original_edges); + shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, + number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, number_of_original_edges); // note: there are 32 geometry indicators in one unsigned block @@ -302,7 +286,7 @@ int main(const int argc, const char *argv[]) // load graph edge size unsigned number_of_graph_edges = 0; hsgr_input_stream.read((char *)&number_of_graph_edges, sizeof(unsigned)); - BOOST_ASSERT_MSG(0 != number_of_graph_edges, "number of graph edges is zero"); + // BOOST_ASSERT_MSG(0 != number_of_graph_edges, "number of graph edges is zero"); shared_layout_ptr->SetBlockSize( SharedDataLayout::GRAPH_EDGE_LIST, number_of_graph_edges); @@ -360,7 +344,6 @@ int main(const int argc, const char *argv[]) geometry_input_stream.read((char *)&number_of_compressed_geometries, sizeof(unsigned)); 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() << " bytes"; @@ -426,6 +409,10 @@ int main(const int argc, const char *argv[]) unsigned *name_id_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::NAME_ID_LIST); + TravelMode *travel_mode_ptr = + shared_layout_ptr->GetBlockPtr( + shared_memory_ptr, SharedDataLayout::TRAVEL_MODE); + TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::TURN_INSTRUCTION); @@ -439,6 +426,7 @@ int main(const int argc, const char *argv[]) edges_input_stream.read((char *)&(current_edge_data), sizeof(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; turn_instructions_ptr[i] = current_edge_data.turn_instruction; const unsigned bucket = i / 32; diff --git a/3party/osrm/osrm-backend/extractor.cpp b/3party/osrm/osrm-backend/extractor.cpp index 6536b0c6ab..43a0296b1b 100644 --- a/3party/osrm/osrm-backend/extractor.cpp +++ b/3party/osrm/osrm-backend/extractor.cpp @@ -26,8 +26,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Extractor/Extractor.h" +#include "Util/simple_logger.hpp" int main (int argc, char *argv[]) { - return Extractor().Run(argc, argv); + try + { + return Extractor().Run(argc, argv); + } + catch (const std::exception &e) + { + SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + } + } diff --git a/3party/osrm/osrm-backend/features/bicycle/mode.feature b/3party/osrm/osrm-backend/features/bicycle/mode.feature index eac04302c0..195a37f67b 100644 --- a/3party/osrm/osrm-backend/features/bicycle/mode.feature +++ b/3party/osrm/osrm-backend/features/bicycle/mode.feature @@ -1,89 +1,177 @@ @routing @bicycle @mode Feature: Bike - Mode flag - Background: - Given the profile "bicycle" +# bicycle modes: +# 1 bike +# 2 pushing +# 3 ferry +# 4 train + + Background: + Given the profile "bicycle" - @todo Scenario: Bike - Mode when using a ferry + Given the node map + | a | b | | + | | c | d | + + And the ways + | nodes | highway | route | duration | + | ab | primary | | | + | bc | | ferry | 0:01 | + | cd | primary | | | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,3,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,3,1 | + | c | a | bc,ab | head,left,destination | 3,1 | + | d | b | cd,bc | head,right,destination | 1,3 | + | a | c | ab,bc | head,right,destination | 1,3 | + | b | d | bc,cd | head,left,destination | 3,1 | + + Scenario: Bike - Mode when using a train + Given the node map + | a | b | | + | | c | d | + + And the ways + | nodes | highway | railway | bicycle | + | ab | primary | | | + | bc | | train | yes | + | cd | primary | | | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,4,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,4,1 | + | c | a | bc,ab | head,left,destination | 4,1 | + | d | b | cd,bc | head,right,destination | 1,4 | + | a | c | ab,bc | head,right,destination | 1,4 | + | b | d | bc,cd | head,left,destination | 4,1 | + + Scenario: Bike - Mode when pushing bike against oneways + Given the node map + | a | b | | + | | c | d | + + And the ways + | nodes | highway | oneway | + | ab | primary | | + | bc | primary | yes | + | cd | primary | | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,1,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,1 | + | b | d | bc,cd | head,left,destination | 1,1 | + + Scenario: Bike - Mode when pushing on pedestrain streets + Given the node map + | a | b | | + | | c | d | + + And the ways + | nodes | highway | + | ab | primary | + | bc | pedestrian | + | cd | primary | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,2 | + | b | d | bc,cd | head,left,destination | 2,1 | + + Scenario: Bike - Mode when pushing on pedestrain areas + Given the node map + | a | b | | | + | | c | d | f | + + And the ways + | nodes | highway | area | + | ab | primary | | + | bcd | pedestrian | yes | + | df | primary | | + + When I route I should get + | from | to | route | modes | + | a | f | ab,bcd,df | 1,2,1 | + | f | a | df,bcd,ab | 1,2,1 | + | d | a | bcd,ab | 2,1 | + | f | b | df,bcd | 1,2 | + | a | d | ab,bcd | 1,2 | + | b | f | bcd,df | 2,1 | + + Scenario: Bike - Mode when pushing on steps + Given the node map + | a | b | | | + | | c | d | f | + + And the ways + | nodes | highway | + | ab | primary | + | bc | steps | + | cd | primary | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,2 | + | b | d | bc,cd | head,left,destination | 2,1 | + + Scenario: Bike - Mode when bicycle=dismount + Given the node map + | a | b | | | + | | c | d | f | + + And the ways + | nodes | highway | bicycle | + | ab | primary | | + | bc | primary | dismount | + | cd | primary | | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,2 | + | b | d | bc,cd | head,left,destination | 2,1 | + + Scenario: Bicycle - Modes when starting on forward oneway Given the node map - | a | b | | - | | c | d | + | a | b | And the ways - | nodes | highway | route | duration | - | ab | primary | | | - | bc | | ferry | 0:01 | - | cd | primary | | | + | nodes | oneway | + | ab | yes | When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left, destination | bike,ferry,bike | - | d | a | cd,bc,ab | head,right,left, destination | bike,ferry,bike | - | c | a | bc,ab | head,left,destination | ferry,bike | - | d | b | cd,bc | head,right,destination | bike,ferry | - | a | c | ab,bc | head,right,destination | bike,ferry | - | b | d | bc,cd | head,left,destination | ferry,bike | + | from | to | route | modes | + | a | b | ab | 1 | + | b | a | ab | 2 | - @todo - Scenario: Bike - Mode when pushing bike against oneways + Scenario: Bicycle - Modes when starting on reverse oneway Given the node map - | a | b | | - | | c | d | + | a | b | And the ways - | nodes | highway | oneway | - | ab | primary | | - | bc | primary | yes | - | cd | primary | | + | nodes | oneway | + | ab | -1 | When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left,destination | bike,push,bike | - | d | a | cd,bc,ab | head,right,left,destination | bike,push,bike | - | c | a | bc,ab | head,left,destination | push,bike | - | d | b | cd,bc | head,right,destination | bike,push | - | a | c | ab,bc | head,right,destination | bike,push | - | b | d | bc,cd | head,left,destination | push,bike | - - @todo - Scenario: Bike - Mode when pushing on pedestrain streets - Given the node map - | a | b | | - | | c | d | - - And the ways - | nodes | highway | - | ab | primary | - | bc | pedestrian | - | cd | primary | - - When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left,destination | bike,push,bike | - | d | a | cd,bc,ab | head,right,left,destination | bike,push,bike | - | c | a | bc,ab | head,left,destination | push,bike | - | d | b | cd,bc | head,right,destination | bike,push | - | a | c | ab,bc | head,right,destination | bike,push | - | b | d | bc,cd | head,left,destination | push,bike | - - @todo - Scenario: Bike - Mode when pushing on pedestrain areas - Given the node map - | a | b | | | - | | c | d | f | - - And the ways - | nodes | highway | area | - | ab | primary | | - | bcd | pedestrian | yes | - | df | primary | | - - When I route I should get - | from | to | route | modes | - | a | f | ab,bcd,df | bike,push,bike | - | f | a | df,bcd,ab | bike,push,bike | - | d | a | bcd,ab | push,bike | - | f | b | df,bcd | bike,push | - | a | d | ab,bcd | bike,push | - | b | f | bcd,df | push,bike | + | from | to | route | modes | + | a | b | ab | 2 | + | b | a | ab | 1 | diff --git a/3party/osrm/osrm-backend/features/bicycle/pushing.feature b/3party/osrm/osrm-backend/features/bicycle/pushing.feature index 5b8d01500d..7cb5400bca 100644 --- a/3party/osrm/osrm-backend/features/bicycle/pushing.feature +++ b/3party/osrm/osrm-backend/features/bicycle/pushing.feature @@ -4,9 +4,9 @@ Feature: Bike - Accessability of different way types Background: Given the profile "bicycle" Given the shortcuts - | key | value | - | bike | 49s ~20% | - | foot | 121s ~20% | + | key | value | + | bike | 15 km/h ~20% | + | foot | 5 km/h ~20% | Scenario: Bike - Pushing bikes on pedestrian-only ways Then routability should be @@ -98,11 +98,11 @@ Feature: Bike - Accessability of different way types | cd | primary | | When I route I should get - | from | to | route | turns | - | a | d | ab,bc,cd | head,right,left,destination | - | d | a | cd,bc,ab | head,enter_contraflow,leave_contraflow,destination | - | c | a | bc,ab | head,leave_contraflow,destination | - | d | b | cd,bc | head,enter_contraflow,destination | + | from | to | route | turns | + | a | d | ab,bc,cd | head,right,left,destination | + | d | a | cd,bc,ab | head,right,left,destination | + | c | a | bc,ab | head,left,destination | + | d | b | cd,bc | head,right,destination | @todo Scenario: Bike - Instructions when pushing bike on footway/pedestrian, etc. @@ -117,8 +117,8 @@ Feature: Bike - Accessability of different way types | cd | primary | When I route I should get - | from | to | route | turns | - | a | d | ab,bc,cd | head,right,left,destination | - | d | a | cd,bc,ab | head,enter_contraflow,leave_contraflow,destination | - | c | a | bc,ab | head,leave_contraflow,destination | - | d | b | cd,bc | head,enter_contraflow,destination | + | from | to | route | turns | + | a | d | ab,bc,cd | head,right,left,destination | + | d | a | cd,bc,ab | head,right,left,destination | + | c | a | bc,ab | head,left,destination | + | d | b | cd,bc | head,right,destination | diff --git a/3party/osrm/osrm-backend/features/car/ferry.feature b/3party/osrm/osrm-backend/features/car/ferry.feature index 3e90cf0053..0e1fe98e52 100644 --- a/3party/osrm/osrm-backend/features/car/ferry.feature +++ b/3party/osrm/osrm-backend/features/car/ferry.feature @@ -17,12 +17,31 @@ Feature: Car - Handle ferry routes | efg | primary | | | When I route I should get - | from | to | route | - | a | g | abc,cde,efg | - | b | f | abc,cde,efg | - | e | c | cde | - | e | b | cde,abc | - | e | a | cde,abc | - | c | e | cde | - | c | f | cde,efg | - | c | g | cde,efg | + | from | to | route | modes | + | a | g | abc,cde,efg | 1,2,1 | + | b | f | abc,cde,efg | 1,2,1 | + | e | c | cde | 2 | + | e | b | cde,abc | 2,1 | + | e | a | cde,abc | 2,1 | + | c | e | cde | 2 | + | c | f | cde,efg | 2,1 | + | c | g | cde,efg | 2,1 | + + Scenario: Car - Properly handle durations + Given the node map + | a | b | c | | | + | | | d | | | + | | | e | f | g | + + And the ways + | nodes | highway | route | duration | + | abc | primary | | | + | cde | | ferry | 00:01:00 | + | efg | primary | | | + + When I route I should get + | from | to | route | modes | speed | + | a | g | abc,cde,efg | 1,2,1 | 24 km/h | + | b | f | abc,cde,efg | 1,2,1 | 19 km/h | + | c | e | cde | 2 | 12 km/h | + | e | c | cde | 2 | 12 km/h | diff --git a/3party/osrm/osrm-backend/features/car/link.feature b/3party/osrm/osrm-backend/features/car/link.feature new file mode 100644 index 0000000000..f4628e4cec --- /dev/null +++ b/3party/osrm/osrm-backend/features/car/link.feature @@ -0,0 +1,111 @@ +@routing @link @car +Feature: Car - Speed on links +# Check that there's a reasonable ratio between the +# speed of a way and it's corresponding link type. + + Background: Use specific speeds + Given the profile "car" + Given a grid size of 1000 meters + + Scenario: Car - Use motorway_link when reasonable + Given the node map + | | | e | | | | f | | | + | x | a | b | | | | c | d | y | + + And the ways + | nodes | highway | + | xa | unclassified | + | ab | motorway_link | + | bc | motorway_link | + | cd | motorway_link | + | ae | motorway | + | ef | motorway | + | fd | motorway | + | dy | unclassified | + + When I route I should get + | from | to | route | + | x | y | xa,ae,ef,fd,dy | + | b | c | bc | + + Scenario: Car - Use trunk_link when reasonable + Given the node map + | | | e | | | | f | | | + | x | a | b | | | | c | d | y | + + And the ways + | nodes | highway | + | xa | unclassified | + | ab | trunk_link | + | bc | trunk_link | + | cd | trunk_link | + | ae | trunk | + | ef | trunk | + | fd | trunk | + | dy | unclassified | + When I route I should get + | from | to | route | + | x | y | xa,ae,ef,fd,dy | + | b | c | bc | + + Scenario: Car - Use primary_link when reasonable + Given the node map + | | | e | | | | f | | | + | x | a | b | | | | c | d | y | + + And the ways + | nodes | highway | + | xa | unclassified | + | ab | primary_link | + | bc | primary_link | + | cd | primary_link | + | ae | primary | + | ef | primary | + | fd | primary | + | dy | unclassified | + When I route I should get + | from | to | route | + | x | y | xa,ae,ef,fd,dy | + | b | c | bc | + + Scenario: Car - Use secondary_link when reasonable + Given the node map + | | | e | | | | f | | | + | x | a | b | | | | c | d | y | + + And the ways + | nodes | highway | + | xa | unclassified | + | ab | secondary_link | + | bc | secondary_link | + | cd | secondary_link | + | ae | secondary | + | ef | secondary | + | fd | secondary | + | dy | unclassified | + + When I route I should get + | from | to | route | + | x | y | xa,ae,ef,fd,dy | + | b | c | bc | + + Scenario: Car - Use tertiary_link when reasonable + Given the node map + | | | e | | | | f | | | + | x | a | b | | | | c | d | y | + + And the ways + | nodes | highway | + | xa | unclassified | + | ab | tertiary_link | + | bc | tertiary_link | + | cd | tertiary_link | + | ae | tertiary | + | ef | tertiary | + | fd | tertiary | + | dy | unclassified | + + When I route I should get + | from | to | route | + | x | y | xa,ae,ef,fd,dy | + | b | c | bc | diff --git a/3party/osrm/osrm-backend/features/car/maxspeed.feature b/3party/osrm/osrm-backend/features/car/maxspeed.feature index 9e77cde74f..4a548020c4 100644 --- a/3party/osrm/osrm-backend/features/car/maxspeed.feature +++ b/3party/osrm/osrm-backend/features/car/maxspeed.feature @@ -8,44 +8,48 @@ OSRM will use 4/5 of the projected free-flow speed. Scenario: Car - Respect maxspeeds when lower that way type speed Given the node map - | a | b | c | + | a | b | c | d | And the ways | nodes | highway | maxspeed | | ab | trunk | | | bc | trunk | 60 | + | cd | trunk | FR:urban | When I route I should get | from | to | route | speed | | a | b | ab | 67 km/h | | b | c | bc | 48 km/h +- 1 | + | c | d | cd | 40 km/h | Scenario: Car - Do not ignore maxspeed when higher than way speed Given the node map - | a | b | c | + | a | b | c | d | And the ways - | nodes | highway | maxspeed | - | ab | residential | | - | bc | residential | 90 | + | nodes | highway | maxspeed | + | ab | residential | | + | bc | residential | 90 | + | cd | living_street | FR:urban | When I route I should get | from | to | route | speed | | a | b | ab | 20 km/h | | b | c | bc | 72 km/h +- 1 | + | c | d | cd | 40 km/h | Scenario: Car - Forward/backward maxspeed Given a grid size of 100 meters Then routability should be - | highway | maxspeed | maxspeed:forward | maxspeed:backward | forw | backw | - | primary | | | | 51 km/h | 51 km/h | - | primary | 60 | | | 48 km/h | 48 km/h | - | primary | | 60 | | 48 km/h | 65 km/h | - | primary | | | 60 | 51 km/h | 48 km/h | - | primary | 15 | 60 | | 48 km/h | 15 km/h +- 1 | - | primary | 15 | | 60 | 12 km/h +- 1| 48 km/h | - | primary | 15 | 30 | 60 | 24 km/h | 48 km/h | + | highway | maxspeed | maxspeed:forward | maxspeed:backward | forw | backw | + | primary | | | | 51 km/h | 51 km/h | + | primary | 60 | | | 48 km/h | 48 km/h | + | primary | | 60 | | 48 km/h | 51 km/h | + | primary | | | 60 | 51 km/h | 48 km/h | + | primary | 15 | 60 | | 48 km/h | 12 km/h | + | primary | 15 | | 60 | 12 km/h | 48 km/h | + | primary | 15 | 30 | 60 | 24 km/h | 48 km/h | Scenario: Car - Maxspeed should not allow routing on unroutable ways Then routability should be diff --git a/3party/osrm/osrm-backend/features/car/speed.feature b/3party/osrm/osrm-backend/features/car/speed.feature index 4f54a332c3..5682f31949 100644 --- a/3party/osrm/osrm-backend/features/car/speed.feature +++ b/3party/osrm/osrm-backend/features/car/speed.feature @@ -9,15 +9,15 @@ Feature: Car - speeds Then routability should be | highway | oneway | bothw | | motorway | no | 72 km/h | - | motorway_link | no | 60 km/h | + | motorway_link | no | 36 km/h | | trunk | no | 67 km/h +- 1 | - | trunk_link | no | 55 km/h +- 1 | + | trunk_link | no | 32 km/h +- 1 | | primary | no | 52 km/h +- 1 | - | primary_link | no | 48 km/h | + | primary_link | no | 24 km/h | | secondary | no | 43 km/h +- 1 | - | secondary_link | no | 40 km/h | + | secondary_link | no | 20 km/h | | tertiary | no | 32 km/h | - | tertiary_link | no | 24 km/h | + | tertiary_link | no | 16 km/h | | unclassified | no | 20 km/h | | residential | no | 20 km/h | | living_street | no | 8 km/h | diff --git a/3party/osrm/osrm-backend/features/car/surface.feature b/3party/osrm/osrm-backend/features/car/surface.feature new file mode 100644 index 0000000000..cd31acc983 --- /dev/null +++ b/3party/osrm/osrm-backend/features/car/surface.feature @@ -0,0 +1,140 @@ +@routing @car @surface +Feature: Car - Surfaces + + Background: + Given the profile "car" + + Scenario: Car - Routeability of tracktype tags + Then routability should be + | highway | tracktype | bothw | + | trunk | grade1 | x | + | trunk | grade2 | x | + | trunk | grade3 | x | + | trunk | grade4 | x | + | trunk | grade5 | x | + | trunk | nonsense | x | + + Scenario: Car - Routability of smoothness tags + Then routability should be + | highway | smoothness | bothw | + | trunk | excellent | x | + | trunk | good | x | + | trunk | intermediate | x | + | trunk | bad | x | + | trunk | very_bad | x | + | trunk | horrible | x | + | trunk | very_horrible | x | + | trunk | impassable | | + | trunk | nonsense | x | + + Scenario: Car - Routabiliy of surface tags + Then routability should be + | highway | surface | bothw | + | trunk | asphalt | x | + | trunk | sett | x | + | trunk | gravel | x | + | trunk | nonsense | x | + + Scenario: Car - Good surfaces should not grant access + Then routability should be + | highway | access | tracktype | smoothness | surface | forw | backw | + | motorway | | | | | x | | + | motorway | no | grade1 | excellent | asphalt | | | + | motorway | private | grade1 | excellent | asphalt | | | + | motorway | agricultural | grade1 | excellent | asphalt | | | + | motorway | forestry | grade1 | excellent | asphalt | | | + | motorway | emergency | grade1 | excellent | asphalt | | | + | primary | | | | | x | x | + | primary | no | grade1 | excellent | asphalt | | | + | primary | private | grade1 | excellent | asphalt | | | + | primary | agricultural | grade1 | excellent | asphalt | | | + | primary | forestry | grade1 | excellent | asphalt | | | + | primary | emergency | grade1 | excellent | asphalt | | | + + Scenario: Car - Impassable surfaces should deny access + Then routability should be + | highway | access | smoothness | forw | backw | + | motorway | | impassable | | | + | motorway | yes | | x | | + | motorway | yes | impassable | | | + | primary | | impassable | | | + | primary | yes | | x | x | + | primary | yes | impassable | | | + + Scenario: Car - Surface should reduce speed + Then routability should be + | highway | oneway | surface | forw | backw | + | motorway | no | | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | asphalt | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | concrete | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | concrete:plates | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | concrete:lanes | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | paved | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | cement | 65 km/h +-1 | 65 km/h +-1 | + | motorway | no | compacted | 65 km/h +-1 | 65 km/h +-1 | + | motorway | no | fine_gravel | 65 km/h +-1 | 65 km/h +-1 | + | motorway | no | paving_stones | 48 km/h +-1 | 48 km/h +-1 | + | motorway | no | metal | 48 km/h +-1 | 48 km/h +-1 | + | motorway | no | bricks | 48 km/h +-1 | 48 km/h +-1 | + | motorway | no | grass | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | wood | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | sett | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | grass_paver | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | gravel | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | unpaved | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | ground | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | dirt | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | pebblestone | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | tartan | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | cobblestone | 24 km/h +-1 | 24 km/h +-1 | + | motorway | no | clay | 24 km/h +-1 | 24 km/h +-1 | + | motorway | no | earth | 16 km/h +-1 | 16 km/h +-1 | + | motorway | no | stone | 16 km/h +-1 | 16 km/h +-1 | + | motorway | no | rocky | 16 km/h +-1 | 16 km/h +-1 | + | motorway | no | sand | 16 km/h +-1 | 16 km/h +-1 | + + Scenario: Car - Tracktypes should reduce speed + Then routability should be + | highway | oneway | tracktype | forw | backw | + | motorway | no | | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | grade1 | 48 km/h +-1 | 48 km/h +-1 | + | motorway | no | grade2 | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | grade3 | 24 km/h +-1 | 24 km/h +-1 | + | motorway | no | grade4 | 20 km/h +-1 | 20 km/h +-1 | + | motorway | no | grade5 | 16 km/h +-1 | 16 km/h +-1 | + + Scenario: Car - Smoothness should reduce speed + Then routability should be + | highway | oneway | smoothness | forw | backw | + | motorway | no | | 72 km/h +-1 | 72 km/h +-1 | + | motorway | no | intermediate | 65 km/h +-1 | 65 km/h +-1 | + | motorway | no | bad | 32 km/h +-1 | 32 km/h +-1 | + | motorway | no | very_bad | 16 km/h +-1 | 16 km/h +-1 | + | motorway | no | horrible | 8 km/h +-1 | 8 km/h +-1 | + | motorway | no | very_horrible | 4 km/h +-1 | 4 km/h +-1 | + + Scenario: Car - Combination of surface tags should use lowest speed + Then routability should be + | highway | oneway | tracktype | surface | smoothness | backw | forw | + | motorway | no | | | | 72 km/h | 72 km/h | + | service | no | grade1 | asphalt | excellent | 12 km/h | 12 km/h | + | motorway | no | grade5 | asphalt | excellent | 16 km/h | 16 km/h | + | motorway | no | grade1 | mud | excellent | 8 km/h | 8 km/h | + | motorway | no | grade1 | asphalt | very_horrible | 4 km/h | 4 km/h | + | service | no | grade5 | mud | very_horrible | 4 km/h | 4 km/h | + + Scenario: Car - Surfaces should not affect oneway direction + Then routability should be + | highway | oneway | tracktype | smoothness | surface | forw | backw | + | primary | | grade1 | excellent | asphalt | x | x | + | primary | | grade5 | very_bad | mud | x | x | + | primary | | nonsense | nonsense | nonsense | x | x | + | primary | no | grade1 | excellent | asphalt | x | x | + | primary | no | grade5 | very_bad | mud | x | x | + | primary | no | nonsense | nonsense | nonsense | x | x | + | primary | yes | grade1 | excellent | asphalt | x | | + | primary | yes | grade5 | very_bad | mud | x | | + | primary | yes | nonsense | nonsense | nonsense | x | | + | primary | -1 | grade1 | excellent | asphalt | | x | + | primary | -1 | grade5 | very_bad | mud | | x | + | primary | -1 | nonsense | nonsense | nonsense | | x | diff --git a/3party/osrm/osrm-backend/features/foot/ferry.feature b/3party/osrm/osrm-backend/features/foot/ferry.feature index 4308756559..866644d26a 100644 --- a/3party/osrm/osrm-backend/features/foot/ferry.feature +++ b/3party/osrm/osrm-backend/features/foot/ferry.feature @@ -17,15 +17,15 @@ Feature: Foot - Handle ferry routes | efg | primary | | | When I route I should get - | from | to | route | - | a | g | abc,cde,efg | - | b | f | abc,cde,efg | - | e | c | cde | - | e | b | cde,abc | - | e | a | cde,abc | - | c | e | cde | - | c | f | cde,efg | - | c | g | cde,efg | + | from | to | route | modes | + | a | g | abc,cde,efg | 1,2,1 | + | b | f | abc,cde,efg | 1,2,1 | + | e | c | cde | 2 | + | e | b | cde,abc | 2,1 | + | e | a | cde,abc | 2,1 | + | c | e | cde | 2 | + | c | f | cde,efg | 2,1 | + | c | g | cde,efg | 2,1 | Scenario: Foot - Ferry duration, single node Given the node map diff --git a/3party/osrm/osrm-backend/features/options/extract/files.feature b/3party/osrm/osrm-backend/features/options/extract/files.feature index 3061263e92..aceab19f74 100644 --- a/3party/osrm/osrm-backend/features/options/extract/files.feature +++ b/3party/osrm/osrm-backend/features/options/extract/files.feature @@ -1,7 +1,7 @@ @extract @options @files Feature: osrm-extract command line options: files # expansions: -# {base} => path to current input file +# {osm_base} => path to current input file # {profile} => path to current profile script Background: @@ -14,12 +14,12 @@ Feature: osrm-extract command line options: files And the data has been saved to disk Scenario: osrm-extract - Passing base file - When I run "osrm-extract {base}.osm --profile {profile}" + When I run "osrm-extract {osm_base}.osm --profile {profile}" Then stderr should be empty And it should exit with code 0 Scenario: osrm-extract - Order of options should not matter - When I run "osrm-extract --profile {profile} {base}.osm" + When I run "osrm-extract --profile {profile} {osm_base}.osm" Then stderr should be empty And it should exit with code 0 diff --git a/3party/osrm/osrm-backend/features/options/prepare/files.feature b/3party/osrm/osrm-backend/features/options/prepare/files.feature index de356a82be..6e82a6b1b8 100644 --- a/3party/osrm/osrm-backend/features/options/prepare/files.feature +++ b/3party/osrm/osrm-backend/features/options/prepare/files.feature @@ -1,7 +1,7 @@ @prepare @options @files Feature: osrm-prepare command line options: files # expansions: -# {base} => path to current input file +# {extracted_base} => path to current extracted input file # {profile} => path to current profile script Background: @@ -14,12 +14,12 @@ Feature: osrm-prepare command line options: files And the data has been extracted Scenario: osrm-prepare - Passing base file - When I run "osrm-prepare {base}.osrm --profile {profile}" + When I run "osrm-prepare {extracted_base}.osrm --profile {profile}" Then stderr should be empty And it should exit with code 0 Scenario: osrm-prepare - Order of options should not matter - When I run "osrm-prepare --profile {profile} {base}.osrm" + When I run "osrm-prepare --profile {profile} {extracted_base}.osrm" Then stderr should be empty And it should exit with code 0 diff --git a/3party/osrm/osrm-backend/features/options/routed/files.feature b/3party/osrm/osrm-backend/features/options/routed/files.feature index 68c13902e1..9be77f775e 100644 --- a/3party/osrm/osrm-backend/features/options/routed/files.feature +++ b/3party/osrm/osrm-backend/features/options/routed/files.feature @@ -1,11 +1,16 @@ -@routed @options @files +@routed @options @files @todo Feature: osrm-routed command line options: files # Normally when launching osrm-routed, it will keep running as a server until it's shut down. # For testing program options, the --trial option is used, which causes osrm-routed to quit # immediately after initialization. This makes testing easier and faster. # -# The {base} part of the options to osrm-routed will be expanded to the actual base path of -# the preprocessed file. +# The {prepared_base} part of the options to osrm-routed will be expanded to the actual base path of +# the prepared input file. + +# TODO +# Since we're not using osmr-datastore for all testing, osrm-routed is kept running. +# This means this test fails because osrm-routed is already running. +# It probably needs to be rewritten to first quit osrm-routed. Background: Given the profile "testbot" @@ -17,7 +22,7 @@ Feature: osrm-routed command line options: files And the data has been prepared Scenario: osrm-routed - Passing base file - When I run "osrm-routed {base}.osrm --trial" + When I run "osrm-routed {prepared_base}.osrm --trial" Then stdout should contain /^\[info\] starting up engines/ And stdout should contain /\d{1,2}\.\d{1,2}\.\d{1,2}/ And stdout should contain /compiled at/ diff --git a/3party/osrm/osrm-backend/features/step_definitions/data.rb b/3party/osrm/osrm-backend/features/step_definitions/data.rb index e0985a4b16..f1e58bae22 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/data.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/data.rb @@ -158,3 +158,19 @@ Given /^the data has been prepared$/ do @process_error = e end end + +Given /^osrm\-routed is stopped$/ do + begin + OSRMLoader.shutdown + rescue OSRMError => e + @process_error = e + end +end + +Given /^data is loaded directly/ do + @load_method = 'directly' +end + +Given /^data is loaded with datastore$/ do + @load_method = 'datastore' +end diff --git a/3party/osrm/osrm-backend/features/step_definitions/locate.rb b/3party/osrm/osrm-backend/features/step_definitions/locate.rb index 9d3d74f655..3e67be3c96 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/locate.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/locate.rb @@ -1,7 +1,7 @@ When /^I request locate I should get$/ do |table| reprocess actual = [] - OSRMBackgroundLauncher.new("#{@osm_file}.osrm") do + OSRMLoader.load(self,"#{prepared_file}.osrm") do table.hashes.each_with_index do |row,ri| in_node = find_node_by_name row['in'] raise "*** unknown in-node '#{row['in']}" unless in_node diff --git a/3party/osrm/osrm-backend/features/step_definitions/nearest.rb b/3party/osrm/osrm-backend/features/step_definitions/nearest.rb index ae5a79cf57..532c1f0d74 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/nearest.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/nearest.rb @@ -1,7 +1,7 @@ When /^I request nearest I should get$/ do |table| reprocess actual = [] - OSRMBackgroundLauncher.new("#{@osm_file}.osrm") do + OSRMLoader.load(self,"#{prepared_file}.osrm") do table.hashes.each_with_index do |row,ri| in_node = find_node_by_name row['in'] raise "*** unknown in-node '#{row['in']}" unless in_node diff --git a/3party/osrm/osrm-backend/features/step_definitions/options.rb b/3party/osrm/osrm-backend/features/step_definitions/options.rb index 38c9ea2566..e2e50661e2 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/options.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/options.rb @@ -1,6 +1,6 @@ When(/^I run "osrm\-routed\s?(.*?)"$/) do |options| begin - Timeout.timeout(1) { run_bin 'osrm-routed', options } + Timeout.timeout(SHUTDOWN_TIMEOUT) { run_bin 'osrm-routed', options } rescue Timeout::Error raise "*** osrm-routed didn't quit. Maybe the --trial option wasn't used?" end @@ -14,6 +14,10 @@ When(/^I run "osrm\-prepare\s?(.*?)"$/) do |options| run_bin 'osrm-prepare', options end +When(/^I run "osrm\-datastore\s?(.*?)"$/) do |options| + run_bin 'osrm-datastore', options +end + Then /^it should exit with code (\d+)$/ do |code| expect(@exit_code).to eq( code.to_i ) end diff --git a/3party/osrm/osrm-backend/features/step_definitions/requests.rb b/3party/osrm/osrm-backend/features/step_definitions/requests.rb index 7002cd9e31..41257e5b9d 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/requests.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/requests.rb @@ -1,6 +1,6 @@ When /^I request \/(.*)$/ do |path| reprocess - OSRMBackgroundLauncher.new("#{@osm_file}.osrm") do + OSRMLoader.load(self,"#{prepared_file}.osrm") do @response = request_path path end end @@ -43,4 +43,4 @@ Then /^"([^"]*)" should return code (\d+)$/ do |binary, code| expect(@process_error.is_a?(OSRMError)).to eq(true) expect(@process_error.process).to eq(binary) expect(@process_error.code.to_i).to eq(code.to_i) -end \ No newline at end of file +end diff --git a/3party/osrm/osrm-backend/features/step_definitions/routability.rb b/3party/osrm/osrm-backend/features/step_definitions/routability.rb index 03336e583d..dcbde5afad 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/routability.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/routability.rb @@ -44,7 +44,7 @@ Then /^routability should be$/ do |table| if table.headers&["forw","backw","bothw"] == [] raise "*** routability tabel must contain either 'forw', 'backw' or 'bothw' column" end - OSRMBackgroundLauncher.new("#{@osm_file}.osrm") do + OSRMLoader.load(self,"#{prepared_file}.osrm") do table.hashes.each_with_index do |row,i| output_row = row.dup attempts = [] @@ -54,11 +54,11 @@ Then /^routability should be$/ do |table| want = shortcuts_hash[row[direction]] || row[direction] #expand shortcuts case want when '', 'x' - output_row[direction] = result[direction][:status].to_s + output_row[direction] = result[direction][:status] ? result[direction][:status].to_s : '' when /^\d+s/ - output_row[direction] = "#{result[direction][:time]}s" + output_row[direction] = result[direction][:time] ? "#{result[direction][:time]}s" : '' when /^\d+ km\/h/ - output_row[direction] = "#{result[direction][:speed]} km/h" + output_row[direction] = result[direction][:speed] ? "#{result[direction][:speed]} km/h" : '' else raise "*** Unknown expectation format: #{want}" end diff --git a/3party/osrm/osrm-backend/features/step_definitions/routing.rb b/3party/osrm/osrm-backend/features/step_definitions/routing.rb index 73bd5381d1..c25f5b7c8c 100644 --- a/3party/osrm/osrm-backend/features/step_definitions/routing.rb +++ b/3party/osrm/osrm-backend/features/step_definitions/routing.rb @@ -1,7 +1,7 @@ When /^I route I should get$/ do |table| reprocess actual = [] - OSRMBackgroundLauncher.new("#{@osm_file}.osrm") do + OSRMLoader.load(self,"#{prepared_file}.osrm") do table.hashes.each_with_index do |row,ri| if row['request'] got = {'request' => row['request'] } @@ -104,22 +104,22 @@ When /^I route I should get$/ do |table| end end if table.headers.include? 'bearing' - got['bearing'] = bearings + got['bearing'] = instructions ? bearings : '' end if table.headers.include? 'compass' - got['compass'] = compasses + got['compass'] = instructions ? compasses : '' end if table.headers.include? 'turns' - got['turns'] = turns + got['turns'] = instructions ? turns : '' end if table.headers.include? 'modes' - got['modes'] = modes + got['modes'] = instructions ? modes : '' end if table.headers.include? 'times' - got['times'] = times + got['times'] = instructions ? times : '' end if table.headers.include? 'distances' - got['distances'] = distances + got['distances'] = instructions ? distances : '' end end end diff --git a/3party/osrm/osrm-backend/features/support/data.rb b/3party/osrm/osrm-backend/features/support/data.rb index 7c1ba887ae..1ff186181f 100644 --- a/3party/osrm/osrm-backend/features/support/data.rb +++ b/3party/osrm/osrm-backend/features/support/data.rb @@ -1,6 +1,7 @@ require 'OSM/objects' #osmlib gem require 'OSM/Database' require 'builder' +require 'fileutils' class Location attr_accessor :lon,:lat @@ -11,6 +12,7 @@ class Location end end + def set_input_format format raise '*** Input format must be eiter "osm" or "pbf"' unless ['pbf','osm'].include? format.to_s @input_format = format.to_s @@ -21,7 +23,7 @@ def input_format end def sanitized_scenario_title - @sanitized_scenario_title ||= @scenario_title.gsub /[^0-9A-Za-z.\-]/, '_' + @sanitized_scenario_title ||= @scenario_title.to_s.gsub /[^0-9A-Za-z.\-]/, '_' end def set_grid_size meters @@ -154,7 +156,10 @@ def reset_data end reset_profile reset_osm - @fingerprint = nil + @fingerprint_osm = nil + @fingerprint_extract = nil + @fingerprint_prepare = nil + @fingerprint_route = nil end def make_osm_id @@ -204,20 +209,30 @@ def osm_str @osm_str end +def osm_file + @osm_file ||= "#{DATA_FOLDER}/#{fingerprint_osm}" +end + +def extracted_file + @extracted_file ||= "#{osm_file}_#{fingerprint_extract}" +end + +def prepared_file + @prepared_file ||= "#{osm_file}_#{fingerprint_extract}_#{fingerprint_prepare}" +end + def write_osm - #write .oms file if needed Dir.mkdir DATA_FOLDER unless File.exist? DATA_FOLDER - @osm_file = "#{DATA_FOLDER}/#{sanitized_scenario_title}_#{fingerprint}" - unless File.exist?("#{@osm_file}.osm") - File.open( "#{@osm_file}.osm", 'w') {|f| f.write(osm_str) } + unless File.exist?("#{osm_file}.osm") + File.open( "#{osm_file}.osm", 'w') {|f| f.write(osm_str) } end end def convert_osm_to_pbf - unless File.exist?("#{@osm_file}.osm.pbf") + unless File.exist?("#{osm_file}.osm.pbf") log_preprocess_info - log "== Converting #{@osm_file}.osm to protobuffer format...", :preprocess - unless system "osmosis --read-xml #{@osm_file}.osm --write-pbf #{@osm_file}.osm.pbf omitmetadata=true >>#{PREPROCESS_LOG_FILE} 2>&1" + log "== Converting #{osm_file}.osm to protobuffer format...", :preprocess + unless system "osmosis --read-xml #{osm_file}.osm --write-pbf #{osm_file}.osm.pbf omitmetadata=true >>#{PREPROCESS_LOG_FILE} 2>&1" raise OsmosisError.new $?, "osmosis exited with code #{$?.exitstatus}" end log '', :preprocess @@ -225,22 +240,27 @@ def convert_osm_to_pbf end def extracted? - File.exist?("#{@osm_file}.osrm") && - File.exist?("#{@osm_file}.osrm.names") && - File.exist?("#{@osm_file}.osrm.restrictions") + Dir.chdir TEST_FOLDER do + File.exist?("#{extracted_file}.osrm") && + File.exist?("#{extracted_file}.osrm.names") && + File.exist?("#{extracted_file}.osrm.restrictions") + end end def prepared? - File.exist?("#{@osm_file}.osrm.hsgr") + Dir.chdir TEST_FOLDER do + File.exist?("#{prepared_file}.osrm.hsgr") + end end def write_timestamp - File.open( "#{@osm_file}.osrm.timestamp", 'w') {|f| f.write(OSM_TIMESTAMP) } + File.open( "#{prepared_file}.osrm.timestamp", 'w') {|f| f.write(OSM_TIMESTAMP) } end def pbf? input_format=='pbf' end + def write_input_data Dir.chdir TEST_FOLDER do write_osm @@ -252,23 +272,43 @@ end def extract_data Dir.chdir TEST_FOLDER do log_preprocess_info - log "== Extracting #{@osm_file}.osm...", :preprocess - unless system "#{BIN_PATH}/osrm-extract #{@osm_file}.osm#{'.pbf' if pbf?} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + log "== Extracting #{osm_file}.osm...", :preprocess + unless system "#{BIN_PATH}/osrm-extract #{osm_file}.osm#{'.pbf' if pbf?} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess raise ExtractError.new $?.exitstatus, "osrm-extract exited with code #{$?.exitstatus}." end - log '', :preprocess + begin + ["osrm","osrm.names","osrm.restrictions"].each do |file| + File.rename "#{osm_file}.#{file}", "#{extracted_file}.#{file}" + end + rescue Exception => e + raise FileError.new nil, "failed to rename data file after extracting." + end end end def prepare_data Dir.chdir TEST_FOLDER do log_preprocess_info - log "== Preparing #{@osm_file}.osm...", :preprocess - unless system "#{BIN_PATH}/osrm-prepare #{@osm_file}.osrm --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + log "== Preparing #{extracted_file}.osm...", :preprocess + unless system "#{BIN_PATH}/osrm-prepare #{extracted_file}.osrm --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess raise PrepareError.new $?.exitstatus, "osrm-prepare exited with code #{$?.exitstatus}." end + begin + ["osrm.hsgr","osrm.fileIndex","osrm.geometry","osrm.nodes","osrm.ramIndex"].each do |file| + File.rename "#{extracted_file}.#{file}", "#{prepared_file}.#{file}" + end + rescue Exception => e + raise FileError.new nil, "failed to rename data file after preparing." + end + begin + ["osrm.names","osrm.edges","osrm.restrictions"].each do |file| + FileUtils.cp "#{extracted_file}.#{file}", "#{prepared_file}.#{file}" + end + rescue Exception => e + raise FileError.new nil, "failed to copy data file after preparing." + end log '', :preprocess end end diff --git a/3party/osrm/osrm-backend/features/support/env.rb b/3party/osrm/osrm-backend/features/support/env.rb index 369705ab03..a01341dd6a 100644 --- a/3party/osrm/osrm-backend/features/support/env.rb +++ b/3party/osrm/osrm-backend/features/support/env.rb @@ -1,8 +1,8 @@ require 'rspec/expectations' + DEFAULT_PORT = 5000 DEFAULT_TIMEOUT = 2 - ROOT_FOLDER = Dir.pwd OSM_USER = 'osrm' OSM_GENERATOR = 'osrm-test' @@ -17,6 +17,26 @@ PROFILES_PATH = File.join ROOT_FOLDER, 'profiles' BIN_PATH = File.join ROOT_FOLDER, 'build' DEFAULT_INPUT_FORMAT = 'osm' DEFAULT_ORIGIN = [1,1] +LAUNCH_TIMEOUT = 1 +SHUTDOWN_TIMEOUT = 10 +DEFAULT_LOAD_METHOD = 'datastore' +OSRM_ROUTED_LOG_FILE = 'osrm-routed.log' + +if ENV['OS']==/Windows.*/ then + TERMSIGNAL='TERM' +else + TERMSIGNAL=9 +end + + +def log_time_and_run cmd + log_time cmd + `#{cmd}` +end + +def log_time cmd + puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S:%L')}] #{cmd}" +end puts "Ruby version #{RUBY_VERSION}" @@ -44,6 +64,7 @@ unless File.exists? TEST_FOLDER raise "*** Test folder #{TEST_FOLDER} doesn't exist." end + if ENV['OS']=~/Windows.*/ then EXE='.exe' QQ='"' @@ -53,5 +74,12 @@ else end AfterConfiguration do |config| + if OSRMLoader::OSRMBaseLoader.new.osrm_up? + raise "*** osrm-routed is already running." + end clear_log_files end + +at_exit do + OSRMLoader::OSRMBaseLoader.new.shutdown +end diff --git a/3party/osrm/osrm-backend/features/support/exceptions.rb b/3party/osrm/osrm-backend/features/support/exceptions.rb index 2901bfe6af..02f59d388a 100644 --- a/3party/osrm/osrm-backend/features/support/exceptions.rb +++ b/3party/osrm/osrm-backend/features/support/exceptions.rb @@ -31,6 +31,12 @@ class OSRMError < StandardError end end +class FileError < OSRMError + def initialize code, msg + super 'fileutil', code, msg, PREPROCESS_LOG_FILE, 5 + end +end + class OsmosisError < OSRMError def initialize code, msg super 'osmosis', code, msg, PREPROCESS_LOG_FILE, 40 diff --git a/3party/osrm/osrm-backend/features/support/hash.rb b/3party/osrm/osrm-backend/features/support/hash.rb index 197cd426ee..6980b66456 100644 --- a/3party/osrm/osrm-backend/features/support/hash.rb +++ b/3party/osrm/osrm-backend/features/support/hash.rb @@ -32,18 +32,32 @@ def lua_lib_hash end def bin_extract_hash - bin_extract_hash ||= hash_of_files "#{BIN_PATH}/osrm-extract#{EXE}" + @bin_extract_hash ||= hash_of_files "#{BIN_PATH}/osrm-extract#{EXE}" + @bin_extract_hash end def bin_prepare_hash - bin_prepare_hash ||= hash_of_files "#{BIN_PATH}/osrm-prepare#{EXE}" + @bin_prepare_hash ||= hash_of_files "#{BIN_PATH}/osrm-prepare#{EXE}" end def bin_routed_hash - bin_routed_hash ||= hash_of_files "#{BIN_PATH}/osrm-routed#{EXE}" + @bin_routed_hash ||= hash_of_files "#{BIN_PATH}/osrm-routed#{EXE}" end -#combine state of data, profile and binaries into a hash that identifies the exact test scenario -def fingerprint - @fingerprint ||= Digest::SHA1.hexdigest "#{bin_extract_hash}-#{bin_prepare_hash}-#{bin_routed_hash}-#{profile_hash}-#{lua_lib_hash}-#{osm_hash}" +# combine state of data, profile and binaries into a hashes that identifies +# the exact test situation at different stages, so we can later skip steps when possible. +def fingerprint_osm + @fingerprint_osm ||= Digest::SHA1.hexdigest "#{osm_hash}" end + +def fingerprint_extract + @fingerprint_extract ||= Digest::SHA1.hexdigest "#{profile_hash}-#{lua_lib_hash}-#{bin_extract_hash}" +end + +def fingerprint_prepare + @fingerprint_prepare ||= Digest::SHA1.hexdigest "#{bin_prepare_hash}" +end + +def fingerprint_route + @fingerprint_route ||= Digest::SHA1.hexdigest "#{bin_routed_hash}" +end \ No newline at end of file diff --git a/3party/osrm/osrm-backend/features/support/hooks.rb b/3party/osrm/osrm-backend/features/support/hooks.rb index ff8f10ff1d..3370142468 100644 --- a/3party/osrm/osrm-backend/features/support/hooks.rb +++ b/3party/osrm/osrm-backend/features/support/hooks.rb @@ -1,7 +1,9 @@ STRESS_TIMEOUT = 300 + Before do |scenario| + # feature name case scenario when Cucumber::Ast::Scenario @@ -18,6 +20,7 @@ Before do |scenario| @scenario_title = scenario.scenario_outline.name end + @load_method = DEFAULT_LOAD_METHOD @query_params = {} @scenario_time = Time.now.strftime("%Y-%m-%dT%H:%m:%SZ") reset_data @@ -25,6 +28,7 @@ Before do |scenario| @has_logged_scenario_info = false set_grid_size DEFAULT_GRID_SIZE set_origin DEFAULT_ORIGIN + end Around('@stress') do |scenario, block| diff --git a/3party/osrm/osrm-backend/features/support/launch.rb b/3party/osrm/osrm-backend/features/support/launch.rb index e55867a671..f6667fad6d 100644 --- a/3party/osrm/osrm-backend/features/support/launch.rb +++ b/3party/osrm/osrm-backend/features/support/launch.rb @@ -1,95 +1,136 @@ require 'socket' require 'open3' -if ENV['OS']==/Windows.*/ then - TERMSIGNAL='TERM' -else - TERMSIGNAL=9 -end +# Only one isntance of osrm-routed is ever launched, to avoid collisions. +# The default is to keep osrm-routed running and load data with datastore. +# however, osrm-routed it shut down and relaunched for each scenario thats +# loads data directly. +class OSRMLoader -OSRM_ROUTED_LOG_FILE = 'osrm-routed.log' + class OSRMBaseLoader + @@pid = nil -class OSRMBackgroundLauncher - def initialize input_file, &block - @input_file = input_file - Dir.chdir TEST_FOLDER do - begin + def launch + Timeout.timeout(LAUNCH_TIMEOUT) do + osrm_up + wait_for_connection + end + rescue Timeout::Error + raise RoutedError.new "Launching osrm-routed timed out." + end + + def shutdown + Timeout.timeout(SHUTDOWN_TIMEOUT) do + osrm_down + end + rescue Timeout::Error + kill + raise RoutedError.new "Shutting down osrm-routed timed out." + end + + def osrm_up? + if @@pid + begin + if Process.waitpid(@@pid, Process::WNOHANG) then + false + else + true + end + rescue Errno::ESRCH, Errno::ECHILD + false + end + end + end + + def osrm_down + if @@pid + Process.kill TERMSIGNAL, @@pid + wait_for_shutdown + @@pid = nil + end + end + + def kill + if @@pid + Process.kill 'KILL', @@pid + end + end + + def wait_for_connection + while true + begin + socket = TCPSocket.new('127.0.0.1', OSRM_PORT) + return + rescue Errno::ECONNREFUSED + sleep 0.1 + end + end + end + + def wait_for_shutdown + while osrm_up? + sleep 0.01 + end + end + end + + # looading data directly when lauching osrm-routed: + # under this scheme, osmr-routed is launched and shutdown for each scenario, + # and osrm-datastore is not used + class OSRMDirectLoader < OSRMBaseLoader + def load world, input_file, &block + @world = world + @input_file = input_file + Dir.chdir TEST_FOLDER do + shutdown launch yield - ensure shutdown end end - end - private - - def launch - Timeout.timeout(OSRM_TIMEOUT) do - osrm_up - wait_for_connection + def osrm_up + return if @@pid + @@pid = Process.spawn("#{BIN_PATH}/osrm-routed #{@input_file} --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) + Process.detach(@@pid) # avoid zombie processes end - rescue Timeout::Error - raise RoutedError.new "Launching osrm-routed timed out." + end - def shutdown - Timeout.timeout(OSRM_TIMEOUT) do - osrm_down - end - rescue Timeout::Error - kill - raise RoutedError.new "Shutting down osrm-routed timed out." - end - - - def osrm_up? - if @pid - begin - if Process.waitpid(@pid, Process::WNOHANG) then - false - else - true - end - rescue Errno::ESRCH, Errno::ECHILD - false + # looading data with osrm-datastore: + # under this scheme, osmr-routed is launched once and kept running for all scenarios, + # and osrm-datastore is used to load data for each scenario + class OSRMDatastoreLoader < OSRMBaseLoader + def load world, input_file, &block + @world = world + @input_file = input_file + Dir.chdir TEST_FOLDER do + load_data + launch unless @@pid + yield end end - end - def osrm_up - return if osrm_up? - @pid = Process.spawn("#{BIN_PATH}/osrm-routed #{@input_file} --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) - Process.detach(@pid) # avoid zombie processes - end + def load_data + run_bin "osrm-datastore", @input_file + end - def osrm_down - if @pid - Process.kill TERMSIGNAL, @pid - wait_for_shutdown + def osrm_up + return if osrm_up? + @@pid = Process.spawn("#{BIN_PATH}/osrm-routed --sharedmemory=1 --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) + Process.detach(@@pid) # avoid zombie processes end end - def kill - if @pid - Process.kill 'KILL', @pid + def self.load world, input_file, &block + method = world.instance_variable_get "@load_method" + if method == 'datastore' + OSRMDatastoreLoader.new.load world, input_file, &block + elsif method == 'directly' + OSRMDirectLoader.new.load world, input_file, &block + else + raise "*** Unknown load method '#{method}'" end end - def wait_for_connection - while true - begin - socket = TCPSocket.new('127.0.0.1', OSRM_PORT) - return - rescue Errno::ECONNREFUSED - sleep 0.1 - end - end - end - - def wait_for_shutdown - while osrm_up? - sleep 0.1 - end - end end diff --git a/3party/osrm/osrm-backend/features/support/log.rb b/3party/osrm/osrm-backend/features/support/log.rb index 7dc34f29c8..e480bdb0c4 100644 --- a/3party/osrm/osrm-backend/features/support/log.rb +++ b/3party/osrm/osrm-backend/features/support/log.rb @@ -29,7 +29,10 @@ def log_scenario_fail_info log "=========================================" log "Failed scenario: #{@scenario_title}" log "Time: #{@scenario_time}" - log "Fingerprint: #{@fingerprint}" + log "Fingerprint osm stage: #{@fingerprint_osm}" + log "Fingerprint extract stage: #{@fingerprint_extract}" + log "Fingerprint prepare stage: #{@fingerprint_prepare}" + log "Fingerprint route stage: #{@fingerprint_route}" log "Profile: #{@profile}" log log '```xml' #so output can be posted directly to github comment fields @@ -41,6 +44,7 @@ def log_scenario_fail_info end def log_fail expected,got,attempts + return log_scenario_fail_info log "== " log "Expected: #{expected}" diff --git a/3party/osrm/osrm-backend/features/support/run.rb b/3party/osrm/osrm-backend/features/support/run.rb index 3eadf90d57..0e64b93de5 100644 --- a/3party/osrm/osrm-backend/features/support/run.rb +++ b/3party/osrm/osrm-backend/features/support/run.rb @@ -2,16 +2,26 @@ def run_bin bin, options Dir.chdir TEST_FOLDER do opt = options.dup - if opt.include? '{base}' - raise "*** {base} is missing" unless @osm_file - opt.gsub! "{base}", "#{@osm_file}" + if opt.include? '{osm_base}' + raise "*** {osm_base} is missing" unless osm_file + opt.gsub! "{osm_base}", "#{osm_file}" end + if opt.include? '{extracted_base}' + raise "*** {extracted_base} is missing" unless extracted_file + opt.gsub! "{extracted_base}", "#{extracted_file}" + end + + if opt.include? '{prepared_base}' + raise "*** {prepared_base} is missing" unless prepared_file + opt.gsub! "{prepared_base}", "#{prepared_file}" + end if opt.include? '{profile}' opt.gsub! "{profile}", "#{PROFILES_PATH}/#{@profile}.lua" end - @stdout = `#{QQ}#{BIN_PATH}/#{bin}#{EXE}#{QQ} #{opt} 2>error.log` + cmd = "#{QQ}#{BIN_PATH}/#{bin}#{EXE}#{QQ} #{opt} 2>error.log" + @stdout = `#{cmd}` @stderr = File.read 'error.log' @exit_code = $?.exitstatus end diff --git a/3party/osrm/osrm-backend/features/testbot/bad.feature b/3party/osrm/osrm-backend/features/testbot/bad.feature index f0f3cfacc6..d7e3c95af1 100644 --- a/3party/osrm/osrm-backend/features/testbot/bad.feature +++ b/3party/osrm/osrm-backend/features/testbot/bad.feature @@ -1,4 +1,4 @@ -@routing @bad +@routing @bad @testbot Feature: Handle bad data in a graceful manner Background: diff --git a/3party/osrm/osrm-backend/features/testbot/basic.feature b/3party/osrm/osrm-backend/features/testbot/basic.feature index 3fda3d3633..2b35d29a01 100644 --- a/3party/osrm/osrm-backend/features/testbot/basic.feature +++ b/3party/osrm/osrm-backend/features/testbot/basic.feature @@ -1,4 +1,4 @@ -@routing @basic +@routing @basic @testbot Feature: Basic Routing Background: diff --git a/3party/osrm/osrm-backend/features/testbot/bearing.feature b/3party/osrm/osrm-backend/features/testbot/bearing.feature index c306af92db..9b3dc4eb7a 100644 --- a/3party/osrm/osrm-backend/features/testbot/bearing.feature +++ b/3party/osrm/osrm-backend/features/testbot/bearing.feature @@ -1,4 +1,4 @@ -@routing @bearing +@routing @bearing @testbot Feature: Compass bearing Background: diff --git a/3party/osrm/osrm-backend/features/testbot/bearing_param.feature b/3party/osrm/osrm-backend/features/testbot/bearing_param.feature index e9db873317..810f690384 100644 --- a/3party/osrm/osrm-backend/features/testbot/bearing_param.feature +++ b/3party/osrm/osrm-backend/features/testbot/bearing_param.feature @@ -1,4 +1,4 @@ -@routing @bearing_param @todo +@routing @bearing_param @todo @testbot Feature: Bearing parameter Background: diff --git a/3party/osrm/osrm-backend/features/testbot/compression.feature b/3party/osrm/osrm-backend/features/testbot/compression.feature new file mode 100644 index 0000000000..146ad63df7 --- /dev/null +++ b/3party/osrm/osrm-backend/features/testbot/compression.feature @@ -0,0 +1,22 @@ +@routing @graph @testbot +Feature: Geometry Compression + + Background: + Given the profile "testbot" + + Scenario: Compressed segments have correct order + Given the node map + | a | | d | | | | h | + | b | | | | e | | f | + | | c | | | | | g | + + And the ways + | nodes | + | abcdef | + | fh | + | fg | + + When I route I should get + | from | to | route | distance | speed | + | b | e | abcdef | 589m | 35 km/h | + | e | b | abcdef | 589m | 35 km/h | diff --git a/3party/osrm/osrm-backend/features/testbot/datastore.feature b/3party/osrm/osrm-backend/features/testbot/datastore.feature new file mode 100644 index 0000000000..568ae7aa4b --- /dev/null +++ b/3party/osrm/osrm-backend/features/testbot/datastore.feature @@ -0,0 +1,31 @@ +@routing @datastore @testbot +Feature: Temporary tests related to osrm-datastore + + Background: + Given the profile "testbot" + + Scenario: Scenario ab + Given the node map + | a | b | + + And the ways + | nodes | + | ab | + + When I route I should get + | from | to | route | + | a | b | ab | + | b | a | ab | + + Scenario: Scenaria xy + Given the node map + | x | y | + + And the ways + | nodes | + | xy | + + When I route I should get + | from | to | route | + | x | y | xy | + | y | x | xy | diff --git a/3party/osrm/osrm-backend/features/testbot/distance.feature b/3party/osrm/osrm-backend/features/testbot/distance.feature index f9f166bd72..1f777d24f4 100644 --- a/3party/osrm/osrm-backend/features/testbot/distance.feature +++ b/3party/osrm/osrm-backend/features/testbot/distance.feature @@ -1,4 +1,4 @@ -@routing @distance +@routing @distance @testbot Feature: Distance calculation Background: diff --git a/3party/osrm/osrm-backend/features/testbot/fastest.feature b/3party/osrm/osrm-backend/features/testbot/fastest.feature index 9a5cf24a34..8c24a5334d 100644 --- a/3party/osrm/osrm-backend/features/testbot/fastest.feature +++ b/3party/osrm/osrm-backend/features/testbot/fastest.feature @@ -1,4 +1,4 @@ -@routing @fastest +@routing @fastest @testbot Feature: Choosing fastest route Background: diff --git a/3party/osrm/osrm-backend/features/testbot/geometry.feature b/3party/osrm/osrm-backend/features/testbot/geometry.feature index 553af9393f..8b38c06f81 100644 --- a/3party/osrm/osrm-backend/features/testbot/geometry.feature +++ b/3party/osrm/osrm-backend/features/testbot/geometry.feature @@ -1,4 +1,4 @@ -@routing +@routing @testbot Feature: Retrieve geometry Background: Use some profile diff --git a/3party/osrm/osrm-backend/features/testbot/graph.feature b/3party/osrm/osrm-backend/features/testbot/graph.feature index a870106dc1..adff998681 100644 --- a/3party/osrm/osrm-backend/features/testbot/graph.feature +++ b/3party/osrm/osrm-backend/features/testbot/graph.feature @@ -1,4 +1,4 @@ -@routing @graph +@routing @graph @testbot Feature: Basic Routing #Test the input data descibed on https://github.com/DennisOSRM/Project-OSRM/wiki/Graph-representation @@ -19,3 +19,22 @@ Feature: Basic Routing When I route I should get | from | to | route | | a | e | abc,dce | + + Scenario: Turn instructions on compressed road network geometry + Given the node map + | x | a | | | + | | b | | | + | f | | | e | + | | | | | + | | | | | + | y | c | | d | + + And the ways + | nodes | name | + | xa | first | + | abcdef | compr | + | fy | last | + + When I route I should get + | from | to | route | turns | + | x | y | first,compr,last | head,right,left,destination | diff --git a/3party/osrm/osrm-backend/features/testbot/load.feature b/3party/osrm/osrm-backend/features/testbot/load.feature new file mode 100644 index 0000000000..cf5e470bdc --- /dev/null +++ b/3party/osrm/osrm-backend/features/testbot/load.feature @@ -0,0 +1,63 @@ +@routing @load @testbot +Feature: Ways of loading data +# Several scenarios that change between direct/datastore makes +# it easier to check that the test framework behaves as expected. + + Background: + Given the profile "testbot" + + Scenario: Load data with datastore - ab + Given data is loaded with datastore + Given the node map + | a | b | + + And the ways + | nodes | + | ab | + + When I route I should get + | from | to | route | + | a | b | ab | + | b | a | ab | + + Scenario: Load data directly - st + Given data is loaded directly + Given the node map + | s | t | + + And the ways + | nodes | + | st | + + When I route I should get + | from | to | route | + | s | t | st | + | t | s | st | + + Scenario: Load data datstore - xy + Given data is loaded with datastore + Given the node map + | x | y | + + And the ways + | nodes | + | xy | + + When I route I should get + | from | to | route | + | x | y | xy | + | y | x | xy | + + Scenario: Load data directly - cd + Given data is loaded directly + Given the node map + | c | d | + + And the ways + | nodes | + | cd | + + When I route I should get + | from | to | route | + | c | d | cd | + | d | c | cd | diff --git a/3party/osrm/osrm-backend/features/testbot/loop.feature b/3party/osrm/osrm-backend/features/testbot/loop.feature index eb5b45e669..fe898ecf08 100644 --- a/3party/osrm/osrm-backend/features/testbot/loop.feature +++ b/3party/osrm/osrm-backend/features/testbot/loop.feature @@ -1,4 +1,4 @@ -@routing @726 +@routing @726 @testbot Feature: Avoid weird loops caused by rounding errors Background: @@ -73,6 +73,6 @@ Feature: Avoid weird loops caused by rounding errors | cf | secondary | When I route I should get - | waypoints | route | turns | - | a,2,d | ab,be,ef,cf,cd | head,left,right,right,left,destination | - | a,1,d | ab,be,ef,cf,cd | head,left,right,right,left,destination | + | waypoints | route | turns | + | a,2,d | ab,be,ef,ef,cf,cd | head,left,right,via,right,left,destination | + | a,1,d | ab,be,ef,ef,cf,cd | head,left,right,via,right,left,destination | diff --git a/3party/osrm/osrm-backend/features/testbot/mode.feature b/3party/osrm/osrm-backend/features/testbot/mode.feature index bcc087ec44..54b99d3a11 100644 --- a/3party/osrm/osrm-backend/features/testbot/mode.feature +++ b/3party/osrm/osrm-backend/features/testbot/mode.feature @@ -1,26 +1,227 @@ @routing @testbot @mode -Feature: Testbot - Mode flag +Feature: Testbot - Travel mode + +# testbot modes: +# 1 normal +# 2 route +# 3 river downstream +# 4 river upstream +# 5 steps down +# 6 steps up Background: - Given the profile "testbot" + Given the profile "testbot" - @todo - Scenario: Bike - Mode + Scenario: Testbot - Modes in each direction, different forward/backward speeds Given the node map - | a | b | | - | | c | d | + | | 0 | 1 | | + | a | | | b | And the ways + | nodes | highway | oneway | + | ab | river | | + + When I route I should get + | from | to | route | modes | + | a | 0 | ab | 3 | + | a | b | ab | 3 | + | 0 | 1 | ab | 3 | + | 0 | b | ab | 3 | + | b | 1 | ab | 4 | + | b | a | ab | 4 | + | 1 | 0 | ab | 4 | + | 1 | a | ab | 4 | + + Scenario: Testbot - Modes in each direction, same forward/backward speeds + Given the node map + | | 0 | 1 | | + | a | | | b | + + And the ways + | nodes | highway | + | ab | steps | + + When I route I should get + | from | to | route | modes | time | + | 0 | 1 | ab | 5 | 60s +-1 | + | 1 | 0 | ab | 6 | 60s +-1 | + + @oneway + Scenario: Testbot - Modes for oneway, different forward/backward speeds + Given the node map + | a | b | + + And the ways + | nodes | highway | oneway | + | ab | river | yes | + + When I route I should get + | from | to | route | modes | + | a | b | ab | 3 | + | b | a | | | + + @oneway + Scenario: Testbot - Modes for oneway, same forward/backward speeds + Given the node map + | a | b | + + And the ways + | nodes | highway | oneway | + | ab | steps | yes | + + When I route I should get + | from | to | route | modes | + | a | b | ab | 5 | + | b | a | | | + + @oneway + Scenario: Testbot - Modes for reverse oneway, different forward/backward speeds + Given the node map + | a | b | + + And the ways + | nodes | highway | oneway | + | ab | river | -1 | + + When I route I should get + | from | to | route | modes | + | a | b | | | + | b | a | ab | 4 | + + @oneway + Scenario: Testbot - Modes for reverse oneway, same forward/backward speeds + Given the node map + | a | b | + + And the ways + | nodes | highway | oneway | + | ab | steps | -1 | + + When I route I should get + | from | to | route | modes | + | a | b | | | + | b | a | ab | 6 | + + @via + Scenario: Testbot - Mode should be set at via points + Given the node map + | a | 1 | b | + + And the ways + | nodes | highway | + | ab | river | + + When I route I should get + | waypoints | route | modes | turns | + | a,1,b | ab,ab | 3,3 | head,via,destination | + | b,1,a | ab,ab | 4,4 | head,via,destination | + + Scenario: Testbot - Starting at a tricky node + Given the node map + | | a | | | | + | | | | b | c | + + And the ways + | nodes | highway | + | ab | river | + | bc | primary | + + When I route I should get + | from | to | route | modes | + | b | a | ab | 4 | + + Scenario: Testbot - Mode changes on straight way without name change + Given the node map + | a | 1 | b | 2 | c | + + And the ways + | nodes | highway | name | + | ab | primary | Avenue | + | bc | river | Avenue | + + When I route I should get + | from | to | route | modes | turns | + | a | c | Avenue,Avenue | 1,3 | head,straight,destination | + | c | a | Avenue,Avenue | 4,1 | head,straight,destination | + | 1 | 2 | Avenue,Avenue | 1,3 | head,straight,destination | + | 2 | 1 | Avenue,Avenue | 4,1 | head,straight,destination | + + Scenario: Testbot - Mode for routes + Given the node map + | a | b | | | | + | | c | d | e | f | + + And the ways | nodes | highway | route | duration | | ab | primary | | | | bc | | ferry | 0:01 | | cd | primary | | | + | de | primary | | | + | ef | primary | | | + + When I route I should get + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,2 | + | b | d | bc,cd | head,left,destination | 2,1 | + | a | f | ab,bc,cd,de,ef | head,right,left,straight,straight,destination | 1,2,1,1,1 | + + Scenario: Testbot - Modes, triangle map + Given the node map + | | | | | | | d | + | | | | | | 2 | | + | | | | | 6 | | 5 | + | a | 0 | b | c | | | | + | | | | | 4 | | 1 | + | | | | | | 3 | | + | | | | | | | e | + + And the ways + | nodes | highway | oneway | + | abc | primary | | + | cd | primary | yes | + | ce | river | | + | de | primary | | + + When I route I should get + | from | to | route | modes | + | 0 | 1 | abc,ce,de | 1,3,1 | + | 1 | 0 | de,ce,abc | 1,4,1 | + | 0 | 2 | abc,cd | 1,1 | + | 2 | 0 | cd,de,ce,abc | 1,1,4,1 | + | 0 | 3 | abc,ce | 1,3 | + | 3 | 0 | ce,abc | 4,1 | + | 4 | 3 | ce | 3 | + | 3 | 4 | ce | 4 | + | 3 | 1 | ce,de | 3,1 | + | 1 | 3 | de,ce | 1,4 | + | a | e | abc,ce | 1,3 | + | e | a | ce,abc | 4,1 | + | a | d | abc,cd | 1,1 | + | d | a | de,ce,abc | 1,4,1 | + + Scenario: Testbot - River in the middle + Given the node map + | a | b | c | | | + | | | d | | | + | | | e | f | g | + + And the ways + | nodes | highway | + | abc | primary | + | cde | river | + | efg | primary | When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left,destination | bot,ferry,bot | - | d | a | cd,bc,ab | head,right left,destination | bot,ferry,bot | - | c | a | bc,ab | head,left,destination | ferry,bot | - | d | b | cd,bc | head,right,destination | bot,ferry | - | a | c | ab,bc | head,right,destination | bot,ferry | - | b | d | bc,cd | head,left,destination | ferry,bot | + | from | to | route | modes | + | a | g | abc,cde,efg | 1,3,1 | + | b | f | abc,cde,efg | 1,3,1 | + | e | c | cde | 4 | + | e | b | cde,abc | 4,1 | + | e | a | cde,abc | 4,1 | + | c | e | cde | 3 | + | c | f | cde,efg | 3,1 | + | c | g | cde,efg | 3,1 | diff --git a/3party/osrm/osrm-backend/features/testbot/oneway.feature b/3party/osrm/osrm-backend/features/testbot/oneway.feature index c21d8b1cb6..766bf8b3b9 100644 --- a/3party/osrm/osrm-backend/features/testbot/oneway.feature +++ b/3party/osrm/osrm-backend/features/testbot/oneway.feature @@ -6,11 +6,12 @@ Feature: Testbot - oneways Scenario: Routing on a oneway roundabout Given the node map - | x | | | v | | | - | | | d | c | | | + | | | | | v | | + | x | | d | c | | | | | e | | | b | | | | f | | | a | | - | | | g | h | | | + | | | g | h | | y | + | | z | | | | | And the ways | nodes | oneway | @@ -23,6 +24,9 @@ Feature: Testbot - oneways | gh | yes | | ha | yes | | vx | yes | + | vy | yes | + | yz | yes | + | xe | yes | When I route I should get | from | to | route | @@ -42,3 +46,57 @@ Feature: Testbot - oneways | g | f | gh,ha,ab,bc,cd,de,ef | | h | g | ha,ab,bc,cd,de,ef,fg | | a | h | ab,bc,cd,de,ef,fg,gh | + + Scenario: Testbot - Simple oneway + Then routability should be + | highway | foot | oneway | forw | backw | + | primary | no | yes | x | | + + Scenario: Simple reverse oneway + Then routability should be + | highway | foot | oneway | forw | backw | + | primary | no | -1 | | x | + + Scenario: Testbot - Around the Block + Given the node map + | a | b | + | d | c | + + And the ways + | nodes | oneway | foot | + | ab | yes | no | + | bc | | no | + | cd | | no | + | da | | no | + + When I route I should get + | from | to | route | + | a | b | ab | + | b | a | bc,cd,da | + + Scenario: Testbot - Handle various oneway tag values + Then routability should be + | foot | oneway | forw | backw | + | no | | x | x | + | no | nonsense | x | x | + | no | no | x | x | + | no | false | x | x | + | no | 0 | x | x | + | no | yes | x | | + | no | true | x | | + | no | 1 | x | | + | no | -1 | | x | + + Scenario: Testbot - Two consecutive oneways + Given the node map + | a | b | c | + + And the ways + | nodes | oneway | + | ab | yes | + | bc | yes | + + + When I route I should get + | from | to | route | + | a | c | ab,bc | diff --git a/3party/osrm/osrm-backend/features/testbot/origin.feature b/3party/osrm/osrm-backend/features/testbot/origin.feature index c43e04e612..b5b1945020 100644 --- a/3party/osrm/osrm-backend/features/testbot/origin.feature +++ b/3party/osrm/osrm-backend/features/testbot/origin.feature @@ -1,4 +1,4 @@ -@routing @origin +@routing @origin @testbot Feature: Routing close to the [0,0] origin Background: diff --git a/3party/osrm/osrm-backend/features/testbot/penalty.feature b/3party/osrm/osrm-backend/features/testbot/penalty.feature index 85f43c7ed8..e4f3cb632f 100644 --- a/3party/osrm/osrm-backend/features/testbot/penalty.feature +++ b/3party/osrm/osrm-backend/features/testbot/penalty.feature @@ -1,4 +1,4 @@ -@routing @penalty @signal +@routing @penalty @signal @testbot Feature: Penalties # Testbot uses a signal penalty of 7s. diff --git a/3party/osrm/osrm-backend/features/testbot/planetary.feature b/3party/osrm/osrm-backend/features/testbot/planetary.feature index f2ba21e887..19925fe27f 100644 --- a/3party/osrm/osrm-backend/features/testbot/planetary.feature +++ b/3party/osrm/osrm-backend/features/testbot/planetary.feature @@ -1,4 +1,4 @@ -@routing @planetary +@routing @planetary @testbot Feature: Distance calculation Scenario: Approximated Longitudinal distances at equator diff --git a/3party/osrm/osrm-backend/features/testbot/projection.feature b/3party/osrm/osrm-backend/features/testbot/projection.feature index ed2f2fcc4a..d7a0b89930 100644 --- a/3party/osrm/osrm-backend/features/testbot/projection.feature +++ b/3party/osrm/osrm-backend/features/testbot/projection.feature @@ -1,4 +1,4 @@ -@routing @projection +@routing @projection @testbot Feature: Projection to nearest point on road # Waypoints are projected perpendiculary onto the closest road diff --git a/3party/osrm/osrm-backend/features/testbot/protobuffer.feature b/3party/osrm/osrm-backend/features/testbot/protobuffer.feature index a77ff34a64..e32de26c25 100644 --- a/3party/osrm/osrm-backend/features/testbot/protobuffer.feature +++ b/3party/osrm/osrm-backend/features/testbot/protobuffer.feature @@ -1,4 +1,4 @@ -@routing @pbf +@routing @pbf @testbot Feature: Importing protobuffer (.pbf) format # Test normally read .osm, which is faster than .pbf files, # since we don't need to use osmosis to first convert to .pbf diff --git a/3party/osrm/osrm-backend/features/testbot/snap.feature b/3party/osrm/osrm-backend/features/testbot/snap.feature index c8a04bfd74..bee75bc445 100644 --- a/3party/osrm/osrm-backend/features/testbot/snap.feature +++ b/3party/osrm/osrm-backend/features/testbot/snap.feature @@ -1,4 +1,4 @@ -@routing @snap +@routing @snap @testbot Feature: Snap start/end point to the nearest way Background: diff --git a/3party/osrm/osrm-backend/features/testbot/status.feature b/3party/osrm/osrm-backend/features/testbot/status.feature index 4fa15ebb3c..1b12b33ea8 100644 --- a/3party/osrm/osrm-backend/features/testbot/status.feature +++ b/3party/osrm/osrm-backend/features/testbot/status.feature @@ -1,4 +1,4 @@ -@routing @status +@routing @status @testbot Feature: Status messages Background: diff --git a/3party/osrm/osrm-backend/features/testbot/time.feature b/3party/osrm/osrm-backend/features/testbot/time.feature index e0ccc3760a..c838796f23 100644 --- a/3party/osrm/osrm-backend/features/testbot/time.feature +++ b/3party/osrm/osrm-backend/features/testbot/time.feature @@ -1,4 +1,4 @@ -@routing @time +@routing @time @testbot Feature: Estimation of travel time # Testbot speeds: # Primary road: 36km/h = 36000m/3600s = 100m/10s diff --git a/3party/osrm/osrm-backend/features/testbot/turns.feature b/3party/osrm/osrm-backend/features/testbot/turns.feature index 87bf21f551..6eba4f9e9f 100644 --- a/3party/osrm/osrm-backend/features/testbot/turns.feature +++ b/3party/osrm/osrm-backend/features/testbot/turns.feature @@ -1,4 +1,4 @@ -@routing @turns +@routing @turns @testbot Feature: Turn directions/codes Background: diff --git a/3party/osrm/osrm-backend/features/testbot/utf.feature b/3party/osrm/osrm-backend/features/testbot/utf.feature index e9d324c1bc..d979e9f925 100644 --- a/3party/osrm/osrm-backend/features/testbot/utf.feature +++ b/3party/osrm/osrm-backend/features/testbot/utf.feature @@ -1,4 +1,4 @@ -@routing @utf +@routing @utf @testbot Feature: Handling of UTF characters Background: diff --git a/3party/osrm/osrm-backend/features/testbot/uturn.feature b/3party/osrm/osrm-backend/features/testbot/uturn.feature index 0056f023b3..943796e698 100644 --- a/3party/osrm/osrm-backend/features/testbot/uturn.feature +++ b/3party/osrm/osrm-backend/features/testbot/uturn.feature @@ -1,4 +1,4 @@ -@routing @uturn @via +@routing @uturn @via @testbot Feature: U-turns at via points Background: @@ -21,7 +21,7 @@ Feature: U-turns at via points When I route I should get | waypoints | route | turns | - | a,e,c | ab,be,ef,fg,dg,cd | head,right,left,straight,left,left,destination | + | a,e,c | ab,be,be,ef,fg,dg,cd | head,right,via,left,straight,left,left,destination | Scenario: Query param to allow U-turns at all via points Given the node map @@ -42,8 +42,8 @@ Feature: U-turns at via points | fg | When I route I should get - | waypoints | route | - | a,e,c | ab,be,bc | + | waypoints | route | + | a,e,c | ab,be,be,bc | @todo Scenario: Instructions at via points at u-turns diff --git a/3party/osrm/osrm-backend/features/testbot/via.feature b/3party/osrm/osrm-backend/features/testbot/via.feature index 79fe540904..9eb8f556ec 100644 --- a/3party/osrm/osrm-backend/features/testbot/via.feature +++ b/3party/osrm/osrm-backend/features/testbot/via.feature @@ -13,9 +13,9 @@ Feature: Via points | abc | When I route I should get - | waypoints | route | - | a,b,c | abc | - | c,b,a | abc | + | waypoints | route | + | a,b,c | abc,abc | + | c,b,a | abc,abc | Scenario: Via point at a dead end Given the node map @@ -28,9 +28,9 @@ Feature: Via points | bd | When I route I should get - | waypoints | route | - | a,d,c | abc,bd,bd,abc | - | c,d,a | abc,bd,bd,abc | + | waypoints | route | + | a,d,c | abc,bd,bd,bd,abc | + | c,d,a | abc,bd,bd,bd,abc | Scenario: Multiple via points Given the node map @@ -48,9 +48,9 @@ Feature: Via points | dh | When I route I should get - | waypoints | route | - | a,c,f | ab,bcd,de,efg | - | a,c,f,h | ab,bcd,de,efg,gh | + | waypoints | route | + | a,c,f | ab,bcd,bcd,de,efg | + | a,c,f,h | ab,bcd,bcd,de,efg,efg,gh | Scenario: Via points on ring of oneways # xa it to avoid only having a single ring, which cna trigger edge cases @@ -73,9 +73,9 @@ Feature: Via points | waypoints | route | distance | turns | | 1,3 | ab,bc,cd | 400m +-1 | head,straight,straight,destination | | 3,1 | cd,de,ef,fa,ab | 1000m +-1 | head,right,right,right,right,destination | - | 1,2,3 | ab,bc,cd | 400m +-1 | head,straight,straight,destination | - | 1,3,2 | ab,bc,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,right,right,right,right,straight,destination | - | 3,2,1 | cd,de,ef,fa,ab,bc,cd,de,ef,fa,ab | 2400m +-1 | head,right,right,right,right,straight,straight,right,right,right,right,destination | + | 1,2,3 | ab,bc,bc,cd | 400m +-1 | head,straight,via,straight,destination | + | 1,3,2 | ab,bc,cd,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,via,right,right,right,right,straight,destination | + | 3,2,1 | cd,de,ef,fa,ab,bc,bc,cd,de,ef,fa,ab | 2400m +-1 | head,right,right,right,right,straight,via,straight,right,right,right,right,destination | @bug Scenario: Via points on ring on the same oneway diff --git a/3party/osrm/osrm-backend/mapsme/CMakeLists.txt b/3party/osrm/osrm-backend/mapsme/CMakeLists.txt deleted file mode 100644 index 09fe32e968..0000000000 --- a/3party/osrm/osrm-backend/mapsme/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -file(GLOB_RECURSE SOURCES "*.cpp") -file(GLOB_RECURSE HEADERS "*.hpp") - - -set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DNDEBUG") - -add_executable(osrm-mapsme ${SOURCES} ${HEADERS} "${CMAKE_SOURCE_DIR}/../../succinct/rs_bit_vector.cpp") -target_link_libraries(osrm-mapsme ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB - debug "${CMAKE_SOURCE_DIR}/../../../../omim-build-debug/out/debug/libcoding.a" - "${CMAKE_SOURCE_DIR}/../../../../omim-build-debug/out/debug/libbase.a" - general "${CMAKE_SOURCE_DIR}/../../../../omim-build-release/out/release/libcoding.a" - "${CMAKE_SOURCE_DIR}/../../../../omim-build-release/out/release/libbase.a") diff --git a/3party/osrm/osrm-backend/mapsme/converter.cpp b/3party/osrm/osrm-backend/mapsme/converter.cpp deleted file mode 100644 index 38b7c39169..0000000000 --- a/3party/osrm/osrm-backend/mapsme/converter.cpp +++ /dev/null @@ -1,389 +0,0 @@ -#include "converter.hpp" - -#include - - -#include "../../../../base/bits.hpp" -#include "../../../../base/logging.hpp" -#include "../../../../base/scope_guard.hpp" - -#include "../../../../coding/matrix_traversal.hpp" -#include "../../../../coding/internal/file_data.hpp" - -#include "../../../../routing/osrm_data_facade.hpp" - -#include "../../../succinct/elias_fano.hpp" -#include "../../../succinct/elias_fano_compressed_list.hpp" -#include "../../../succinct/gamma_vector.hpp" -#include "../../../succinct/rs_bit_vector.hpp" -#include "../../../succinct/mapper.hpp" - -#include "../Server/DataStructures/InternalDataFacade.h" - -namespace mapsme -{ - -typedef pair EdgeOsrmT; - -struct EdgeLess -{ - bool operator () (EdgeOsrmT const & e1, EdgeOsrmT const & e2) const - { - if (e1.first != e2.first) - return e1.first < e2.first; - - QueryEdge::EdgeData const & d1 = e1.second; - QueryEdge::EdgeData const & d2 = e2.second; - - if (d1.distance != d2.distance) - return d1.distance < d2.distance; - - if (d1.shortcut != d2.shortcut) - return d1.shortcut < d2.shortcut; - - if (d1.forward != d2.forward) - return d1.forward < d2.forward; - - if (d1.backward != d2.backward) - return e1.second.backward < d2.backward; - - if (d1.id != d2.id) - return d1.id < d2.id; - - return false; - } -}; - -void PrintStatus(bool b) -{ - std::cout << (b ? "[Ok]" : "[Fail]") << std::endl; -} - -string EdgeDataToString(EdgeOsrmT const & d) -{ - stringstream ss; - ss << "[" << d.first << ", " << d.second.distance << ", " << d.second.shortcut << ", " << d.second.forward << ", " - << d.second.backward << ", " << d.second.id << "]"; - return ss.str(); -} - - - -void GenerateRoutingIndex(const std::string & fPath) -{ - ServerPaths server_paths; - - server_paths["hsgrdata"] = boost::filesystem::path(fPath + ".hsgr"); - server_paths["ramindex"] = boost::filesystem::path(fPath + ".ramIndex"); - server_paths["fileindex"] = boost::filesystem::path(fPath + ".fileIndex"); - server_paths["geometries"] = boost::filesystem::path(fPath + ".geometry"); - server_paths["nodesdata"] = boost::filesystem::path(fPath + ".nodes"); - server_paths["edgesdata"] = boost::filesystem::path(fPath + ".edges"); - server_paths["namesdata"] = boost::filesystem::path(fPath + ".names"); - server_paths["timestamp"] = boost::filesystem::path(fPath + ".timestamp"); - - std::cout << "Create internal data facade for file: " << fPath << "..."; - InternalDataFacade facade(server_paths); - PrintStatus(true); - - uint32_t const nodeCount = facade.GetNumberOfNodes(); - - std::vector edges; - std::vector edgesData; - std::vector shortcuts; - std::vector edgeId; - - std::cout << "Repack graph..." << std::endl; - - typedef pair EdgeInfoT; - typedef vector EdgeInfoVecT; - - uint64_t copiedEdges = 0, ignoredEdges = 0; - for (uint32_t node = 0; node < nodeCount; ++node) - { - EdgeInfoVecT edgesInfo; - for (auto edge : facade.GetAdjacentEdgeRange(node)) - { - uint64_t target = facade.GetTarget(edge); - auto const & data = facade.GetEdgeData(edge); - - edgesInfo.push_back(EdgeInfoT(target, data)); - } - - sort(edgesInfo.begin(), edgesInfo.end(), [](EdgeInfoT const & a, EdgeInfoT const & b) - { - if (a.first != b.first) - return a.first < b.first; - - if (a.second.forward != b.second.forward) - return a.second.forward > b.second.forward; - - return a.second.id < b.second.id; - }); - - uint64_t lastTarget = 0; - for (auto edge : edgesInfo) - { - uint64_t const target = edge.first; - auto const & data = edge.second; - - if (target < lastTarget) - LOG(LCRITICAL, ("Invalid order of target nodes", target, lastTarget)); - - lastTarget = target; - assert(data.forward || data.backward); - - auto addDataFn = [&](bool b) - { - uint64_t const e = TraverseMatrixInRowOrder(nodeCount, node, target, b); - - auto compressId = [&](uint64_t id) - { - return bits::ZigZagEncode(int64_t(node) - int64_t(id)); - }; - - if (!edges.empty()) - CHECK_GREATER_OR_EQUAL(e, edges.back(), ()); - - if (!edges.empty() && (edges.back() == e)) - { - LOG(LWARNING, ("Invalid order of edges", e, edges.back(), nodeCount, node, target, b)); - CHECK(data.shortcut == shortcuts.back(), ()); - - auto const last = edgesData.back(); - if (data.distance <= last) - { - if (!edgeId.empty() && data.shortcut) - { - CHECK(shortcuts.back(), ()); - unsigned oldId = node - bits::ZigZagDecode(edgeId.back()); - - if (data.distance == last) - edgeId.back() = compressId(min(oldId, data.id)); - else - edgeId.back() = compressId(data.id); - } - - edgesData.back() = data.distance; - } - - ++ignoredEdges; - return; - } - - edges.push_back(e); - edgesData.push_back(data.distance); - shortcuts.push_back(data.shortcut); - - if (data.shortcut) - edgeId.push_back(compressId(data.id)); - }; - - if (data.forward && data.backward) - { - addDataFn(false); - addDataFn(true); - copiedEdges++; - } - else - addDataFn(data.backward); - } - } - - std::cout << "Edges count: " << edgeId.size() << std::endl; - PrintStatus(true); - - std::cout << "Sort edges..."; - std::sort(edges.begin(), edges.end()); - PrintStatus(true); - - std::cout << "Edges count: " << edges.size() << std::endl; - std::cout << "Nodes count: " << nodeCount << std::endl; - - std::cout << "--- Save matrix" << std::endl; - succinct::elias_fano::elias_fano_builder builder(edges.back(), edges.size()); - for (auto e : edges) - builder.push_back(e); - succinct::elias_fano matrix(&builder); - - std::string fileName = fPath + "." + ROUTING_MATRIX_FILE_TAG; - std::ofstream fout(fileName, std::ios::binary); - fout.write((const char*)&nodeCount, sizeof(nodeCount)); - succinct::mapper::freeze(matrix, fout); - fout.close(); - - std::cout << "--- Save edge data" << std::endl; - succinct::elias_fano_compressed_list edgeVector(edgesData); - fileName = fPath + "." + ROUTING_EDGEDATA_FILE_TAG; - succinct::mapper::freeze(edgeVector, fileName.c_str()); - - succinct::elias_fano_compressed_list edgeIdVector(edgeId); - fileName = fPath + "." + ROUTING_EDGEID_FILE_TAG; - succinct::mapper::freeze(edgeIdVector, fileName.c_str()); - - std::cout << "--- Save edge shortcuts" << std::endl; - succinct::rs_bit_vector shortcutsVector(shortcuts); - fileName = fPath + "." + ROUTING_SHORTCUTS_FILE_TAG; - succinct::mapper::freeze(shortcutsVector, fileName.c_str()); - - if (edgeId.size() != shortcutsVector.num_ones()) - LOG(LCRITICAL, ("Invalid data")); - - std::cout << "--- Test packed data" << std::endl; - std::string path = fPath + ".test"; - - { - FilesContainerW routingCont(path); - - auto appendFile = [&] (string const & tag) - { - string const fileName = fPath + "." + tag; - routingCont.Write(fileName, tag); - }; - - appendFile(ROUTING_SHORTCUTS_FILE_TAG); - appendFile(ROUTING_EDGEDATA_FILE_TAG); - appendFile(ROUTING_MATRIX_FILE_TAG); - appendFile(ROUTING_EDGEID_FILE_TAG); - - routingCont.Finish(); - } - - MY_SCOPE_GUARD(testFileGuard, bind(&my::DeleteFileX, cref(path))); - - FilesMappingContainer container; - container.Open(path); - typedef routing::OsrmDataFacade DataFacadeT; - DataFacadeT facadeNew; - facadeNew.Load(container); - - uint64_t edgesCount = facadeNew.GetNumberOfEdges() - copiedEdges + ignoredEdges; - std::cout << "Check node count " << facade.GetNumberOfNodes() << " == " << facadeNew.GetNumberOfNodes() << "..." << std::endl; - CHECK_EQUAL(facade.GetNumberOfNodes(), facadeNew.GetNumberOfNodes(), ()); - std::cout << "Check edges count " << facade.GetNumberOfEdges() << " == " << edgesCount << "..." << std::endl; - CHECK_EQUAL(facade.GetNumberOfEdges(), edgesCount, ()); - - std::cout << "Check edges data ..."; - bool error = false; - - typedef vector EdgeDataT; - assert(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges()); - for (uint32_t i = 0; i < facade.GetNumberOfNodes(); ++i) - { - // get all edges from osrm datafacade and store just minimal weights for duplicates - vector edgesOsrm; - for (auto e : facade.GetAdjacentEdgeRange(i)) - edgesOsrm.push_back(EdgeOsrmT(facade.GetTarget(e), facade.GetEdgeData(e))); - - sort(edgesOsrm.begin(), edgesOsrm.end(), [](EdgeOsrmT const & a, EdgeOsrmT const & b) - { - if (a.first != b.first) - return a.first < b.first; - - QueryEdge::EdgeData const & d1 = a.second; - QueryEdge::EdgeData const & d2 = b.second; - - if (d1.forward != d2.forward) - return d1.forward < d2.forward; - - if (d1.backward != d2.backward) - return d1.backward < d2.backward; - - if (d1.distance != d2.distance) - return d1.distance < d2.distance; - - return d1.id < d2.id; - }); - - for (size_t k = 1; k < edgesOsrm.size();) - { - auto const & e1 = edgesOsrm[k - 1]; - auto const & e2 = edgesOsrm[k]; - - if (e1.first != e2.first || - e1.second.forward != e2.second.forward || - e1.second.backward != e2.second.backward) - { - ++k; - continue; - } - - if (e1.second.distance > e2.second.distance) - edgesOsrm.erase(edgesOsrm.begin() + k - 1); - else - edgesOsrm.erase(edgesOsrm.begin() + k); - } - - vector v1, v2; - for (auto e : edgesOsrm) - { - QueryEdge::EdgeData d = e.second; - if (d.forward && d.backward) - { - d.backward = false; - v1.push_back(EdgeOsrmT(e.first, d)); - d.forward = false; - d.backward = true; - } - - v1.push_back(EdgeOsrmT(e.first, d)); - } - - for (auto e : facadeNew.GetAdjacentEdgeRange(i)) - v2.push_back(EdgeOsrmT(facadeNew.GetTarget(e), facadeNew.GetEdgeData(e, i))); - - if (v1.size() != v2.size()) - { - auto printV = [](vector const & v, stringstream & ss) - { - for (auto i : v) - ss << EdgeDataToString(i) << std::endl; - }; - - sort(v1.begin(), v1.end(), EdgeLess()); - sort(v2.begin(), v2.end(), EdgeLess()); - - stringstream ss; - ss << "File name: " << fPath << std::endl; - ss << "Not equal edges count for node: " << i << std::endl; - ss << "v1: " << v1.size() << " v2: " << v2.size() << std::endl; - ss << "--- v1 ---" << std::endl; - printV(v1, ss); - ss << "--- v2 ---" << std::endl; - printV(v2, ss); - - LOG(LCRITICAL, (ss.str())); - } - - sort(v1.begin(), v1.end(), EdgeLess()); - sort(v2.begin(), v2.end(), EdgeLess()); - - // compare vectors - for (size_t k = 0; k < v1.size(); ++k) - { - EdgeOsrmT const & e1 = v1[k]; - EdgeOsrmT const & e2 = v2[k]; - - QueryEdge::EdgeData const & d1 = e1.second; - QueryEdge::EdgeData const & d2 = e2.second; - - if (e1.first != e2.first || - d1.backward != d2.backward || - d1.forward != d2.forward || - d1.distance != d2.distance || - (d1.id != d2.id && (d1.shortcut || d2.shortcut)) || - d1.shortcut != d2.shortcut) - { - std::cout << "--- " << std::endl; - for (size_t j = 0; j < v1.size(); ++j) - std::cout << EdgeDataToString(v1[j]) << " - " << EdgeDataToString(v2[j]) << std::endl; - - LOG(LCRITICAL, ("File:", fPath, "Node:", i, EdgeDataToString(e1), EdgeDataToString(e2))); - } - } - - } - PrintStatus(!error); -} - -} diff --git a/3party/osrm/osrm-backend/mapsme/converter.hpp b/3party/osrm/osrm-backend/mapsme/converter.hpp deleted file mode 100644 index 77961dd3ca..0000000000 --- a/3party/osrm/osrm-backend/mapsme/converter.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -#include "../DataStructures/QueryEdge.h" - -namespace mapsme -{ - - -void GenerateRoutingIndex(const std::string & fPath); - -} diff --git a/3party/osrm/osrm-backend/mapsme/main.cpp b/3party/osrm/osrm-backend/mapsme/main.cpp deleted file mode 100644 index 5d626a9e61..0000000000 --- a/3party/osrm/osrm-backend/mapsme/main.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include - -#include -#include -#include "converter.hpp" - -int main(int argc, char **argv) -{ - - boost::program_options::options_description descr; - - descr.add_options() - ("help", "h") - ("input,i", boost::program_options::value(), "Path to input osrm file (belarus.osrm)"); - - boost::program_options::variables_map vm; - boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(descr).run(), vm); - boost::program_options::notify(vm); - if (vm.count("help") || !vm.count("input")) - { - std::cout << descr; - return 0; - } - - - mapsme::GenerateRoutingIndex(vm["input"].as()); - - return 0; -} diff --git a/3party/osrm/osrm-backend/profile.lua b/3party/osrm/osrm-backend/profile.lua deleted file mode 120000 index bad7e6bb5b..0000000000 --- a/3party/osrm/osrm-backend/profile.lua +++ /dev/null @@ -1 +0,0 @@ -profiles/car.lua \ No newline at end of file diff --git a/3party/osrm/osrm-backend/profile.lua b/3party/osrm/osrm-backend/profile.lua new file mode 100644 index 0000000000..ad58cd86ef --- /dev/null +++ b/3party/osrm/osrm-backend/profile.lua @@ -0,0 +1,412 @@ +-- Begin of globals +--require("lib/access") --function temporarily inlined + +barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["checkpoint"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true } +access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true } +access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true, ["emergency"] = true } +access_tag_restricted = { ["destination"] = true, ["delivery"] = true } +access_tags = { "motorcar", "motor_vehicle", "vehicle" } +access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" } +service_tag_restricted = { ["parking_aisle"] = true } +ignore_in_grid = { ["ferry"] = true } +restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" } + +speed_profile = { + ["motorway"] = 90, + ["motorway_link"] = 45, + ["trunk"] = 85, + ["trunk_link"] = 40, + ["primary"] = 65, + ["primary_link"] = 30, + ["secondary"] = 55, + ["secondary_link"] = 25, + ["tertiary"] = 40, + ["tertiary_link"] = 20, + ["unclassified"] = 25, + ["residential"] = 25, + ["living_street"] = 10, + ["service"] = 15, +-- ["track"] = 5, + ["ferry"] = 5, + ["shuttle_train"] = 10, + ["default"] = 10 +} + + +-- surface/trackype/smoothness +-- values were estimated from looking at the photos at the relevant wiki pages + +-- max speed for surfaces +surface_speeds = { + ["asphalt"] = nil, -- nil mean no limit. removing the line has the same effect + ["concrete"] = nil, + ["concrete:plates"] = nil, + ["concrete:lanes"] = nil, + ["paved"] = nil, + + ["cement"] = 80, + ["compacted"] = 80, + ["fine_gravel"] = 80, + + ["paving_stones"] = 60, + ["metal"] = 60, + ["bricks"] = 60, + + ["grass"] = 40, + ["wood"] = 40, + ["sett"] = 40, + ["grass_paver"] = 40, + ["gravel"] = 40, + ["unpaved"] = 40, + ["ground"] = 40, + ["dirt"] = 40, + ["pebblestone"] = 40, + ["tartan"] = 40, + + ["cobblestone"] = 30, + ["clay"] = 30, + + ["earth"] = 20, + ["stone"] = 20, + ["rocky"] = 20, + ["sand"] = 20, + + ["mud"] = 10 +} + +-- max speed for tracktypes +tracktype_speeds = { + ["grade1"] = 60, + ["grade2"] = 40, + ["grade3"] = 30, + ["grade4"] = 25, + ["grade5"] = 20 +} + +-- max speed for smoothnesses +smoothness_speeds = { + ["intermediate"] = 80, + ["bad"] = 40, + ["very_bad"] = 20, + ["horrible"] = 10, + ["very_horrible"] = 5, + ["impassable"] = 0 +} + +-- http://wiki.openstreetmap.org/wiki/Speed_limits +maxspeed_table_default = { + ["urban"] = 50, + ["rural"] = 90, + ["trunk"] = 110, + ["motorway"] = 130 +} + +-- List only exceptions +maxspeed_table = { + ["de:living_street"] = 7, + ["ru:living_street"] = 20, + ["ru:urban"] = 60, + ["ua:urban"] = 60, + ["at:rural"] = 100, + ["de:rural"] = 100, + ["at:trunk"] = 100, + ["cz:trunk"] = 0, + ["ro:trunk"] = 100, + ["cz:motorway"] = 0, + ["de:motorway"] = 0, + ["ru:motorway"] = 110, + ["gb:nsl_single"] = (60*1609)/1000, + ["gb:nsl_dual"] = (70*1609)/1000, + ["gb:motorway"] = (70*1609)/1000, + ["uk:nsl_single"] = (60*1609)/1000, + ["uk:nsl_dual"] = (70*1609)/1000, + ["uk:motorway"] = (70*1609)/1000 +} + +traffic_signal_penalty = 2 + +local take_minimum_of_speeds = false +local obey_oneway = true +local obey_bollards = true +local use_turn_restrictions = true +local ignore_areas = true -- future feature +local u_turn_penalty = 20 + +local abs = math.abs +local min = math.min +local max = math.max + +local speed_reduction = 0.8 + +--modes +local mode_normal = 1 +local mode_ferry = 2 + + +local function find_access_tag(source,access_tags_hierachy) + for i,v in ipairs(access_tags_hierachy) do + local has_tag = source.tags:Holds(v) + if has_tag then + return source.tags:Find(v) + end + end + return nil +end + +function get_exceptions(vector) + for i,v in ipairs(restriction_exception_tags) do + vector:Add(v) + end +end + +local function parse_maxspeed(source) + if not source then + return 0 + end + local n = tonumber(source:match("%d*")) + if n then + if string.match(source, "mph") or string.match(source, "mp/h") then + n = (n*1609)/1000; + end + else + -- parse maxspeed like FR:urban + source = string.lower(source) + n = maxspeed_table[source] + if not n then + local highway_type = string.match(source, "%a%a:(%a+)") + n = maxspeed_table_default[highway_type] + if not n then + n = 0 + end + end + end + return n +end + +-- function turn_function (angle) +-- -- print ("called at angle " .. angle ) +-- local index = math.abs(math.floor(angle/10+0.5))+1 -- +1 'coz LUA starts as idx 1 +-- local penalty = turn_cost_table[index] +-- -- print ("index: " .. index .. ", bias: " .. penalty ) +-- return penalty +-- end + +function node_function (node) + local access = find_access_tag(node, access_tags_hierachy) + + --flag node if it carries a traffic light + if node.tags:Holds("highway") then + if node.tags:Find("highway") == "traffic_signals" then + node.traffic_light = true; + end + end + + -- parse access and barrier tags + if access and access ~= "" then + if access_tag_blacklist[access] then + node.bollard = true + end + elseif node.tags:Holds("barrier") then + local barrier = node.tags:Find("barrier") + if barrier_whitelist[barrier] then + return + else + node.bollard = true + end + end +end + +function way_function (way) + + local is_highway = way.tags:Holds("highway") + local is_route = way.tags:Holds("route") + + if not (is_highway or is_route) then + return + end + + -- we dont route over areas + local is_area = way.tags:Holds("area") + if ignore_areas and is_area then + local area = way.tags:Find("area") + if "yes" == area then + return + end + end + + -- check if oneway tag is unsupported + local oneway = way.tags:Find("oneway") + if "reversible" == oneway then + return + end + + local is_impassable = way.tags:Holds("impassable") + if is_impassable then + local impassable = way.tags:Find("impassable") + if "yes" == impassable then + return + end + end + + local is_status = way.tags:Holds("status") + if is_status then + local status = way.tags:Find("status") + if "impassable" == status then + return + end + end + + -- Check if we are allowed to access the way + local access = find_access_tag(way, access_tags_hierachy) + if access_tag_blacklist[access] then + return + end + + -- Second, parse the way according to these properties + local highway = way.tags:Find("highway") + local route = way.tags:Find("route") + + -- Handling ferries and piers + local route_speed = speed_profile[route] + if(route_speed and route_speed > 0) then + highway = route; + local duration = way.tags:Find("duration") + if durationIsValid(duration) then + way.duration = max( parseDuration(duration), 1 ); + end + way.forward_mode = mode_ferry + way.backward_mode = mode_ferry + way.forward_speed = route_speed + way.backward_speed = route_speed + end + + -- leave early of this way is not accessible + if "" == highway then + return + end + + if way.forward_speed == -1 then + local highway_speed = speed_profile[highway] + local max_speed = parse_maxspeed( way.tags:Find("maxspeed") ) + -- Set the avg speed on the way if it is accessible by road class + if highway_speed then + if max_speed > highway_speed then + way.forward_speed = max_speed + way.backward_speed = max_speed + -- max_speed = math.huge + else + way.forward_speed = highway_speed + way.backward_speed = highway_speed + end + else + -- Set the avg speed on ways that are marked accessible + if access_tag_whitelist[access] then + way.forward_speed = speed_profile["default"] + way.backward_speed = speed_profile["default"] + end + end + if 0 == max_speed then + max_speed = math.huge + end + way.forward_speed = min(way.forward_speed, max_speed) + way.backward_speed = min(way.backward_speed, max_speed) + end + + if -1 == way.forward_speed and -1 == way.backward_speed then + return + end + + -- reduce speed on bad surfaces + local surface = way.tags:Find("surface") + local tracktype = way.tags:Find("tracktype") + local smoothness = way.tags:Find("smoothness") + + if surface and surface_speeds[surface] then + way.forward_speed = math.min(surface_speeds[surface], way.forward_speed) + way.backward_speed = math.min(surface_speeds[surface], way.backward_speed) + end + if tracktype and tracktype_speeds[tracktype] then + way.forward_speed = math.min(tracktype_speeds[tracktype], way.forward_speed) + way.backward_speed = math.min(tracktype_speeds[tracktype], way.backward_speed) + end + if smoothness and smoothness_speeds[smoothness] then + way.forward_speed = math.min(smoothness_speeds[smoothness], way.forward_speed) + way.backward_speed = math.min(smoothness_speeds[smoothness], way.backward_speed) + end + + -- parse the remaining tags + local name = way.tags:Find("name") + local ref = way.tags:Find("ref") + local junction = way.tags:Find("junction") + -- local barrier = way.tags:Find("barrier") + -- local cycleway = way.tags:Find("cycleway") + local service = way.tags:Find("service") + + -- Set the name that will be used for instructions + if "" ~= ref then + way.name = ref + elseif "" ~= name then + way.name = name +-- else + -- way.name = highway -- if no name exists, use way type + end + + if "roundabout" == junction then + way.roundabout = true; + end + + -- Set access restriction flag if access is allowed under certain restrictions only + if access ~= "" and access_tag_restricted[access] then + way.is_access_restricted = true + end + + -- Set access restriction flag if service is allowed under certain restrictions only + if service ~= "" and service_tag_restricted[service] then + way.is_access_restricted = true + end + + -- Set direction according to tags on way + if obey_oneway then + if oneway == "-1" then + way.forward_mode = 0 + elseif oneway == "yes" or + oneway == "1" or + oneway == "true" or + junction == "roundabout" or + (highway == "motorway_link" and oneway ~="no") or + (highway == "motorway" and oneway ~= "no") then + way.backward_mode = 0 + end + end + + -- Override speed settings if explicit forward/backward maxspeeds are given + local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward")) + local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward")) + if maxspeed_forward > 0 then + if 0 ~= way.forward_mode and 0 ~= way.backward_mode then + way.backward_speed = way.forward_speed + end + way.forward_speed = maxspeed_forward + end + if maxspeed_backward > 0 then + way.backward_speed = maxspeed_backward + end + + -- Override general direction settings of there is a specific one for our mode of travel + if ignore_in_grid[highway] then + way.ignore_in_grid = true + end + + -- scale speeds to get better avg driving times + way.forward_speed = way.forward_speed * speed_reduction + if way.backward_speed > 0 then + way.backward_speed = way.backward_speed*speed_reduction + end +end + +-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT +function node_vector_function(vector) + for v in vector.nodes do + node_function(v) + end +end diff --git a/3party/osrm/osrm-backend/profiles/bicycle.lua b/3party/osrm/osrm-backend/profiles/bicycle.lua index 3efa3d025d..13bfd280db 100644 --- a/3party/osrm/osrm-backend/profiles/bicycle.lua +++ b/3party/osrm/osrm-backend/profiles/bicycle.lua @@ -1,4 +1,5 @@ require("lib/access") +require("lib/maxspeed") -- Begin of globals barrier_whitelist = { [""] = true, ["cycle_barrier"] = true, ["bollard"] = true, ["entrance"] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true } @@ -94,7 +95,13 @@ u_turn_penalty = 20 use_turn_restrictions = false turn_penalty = 60 turn_bias = 1.4 --- End of globals + + +--modes +mode_normal = 1 +mode_pushing = 2 +mode_ferry = 3 +mode_train = 4 local function parse_maxspeed(source) @@ -161,18 +168,18 @@ function way_function (way) (not man_made or man_made=='') and (not public_transport or public_transport=='') then - return 0 + return end -- don't route on ways or railways that are still under construction if highway=='construction' or railway=='construction' then - return 0 + return end -- access local access = Access.find_access_tag(way, access_tags_hierachy) if access_tag_blacklist[access] then - return 0 + return end -- other tags @@ -193,6 +200,7 @@ function way_function (way) local area = way.tags:Find("area") local foot = way.tags:Find("foot") local surface = way.tags:Find("surface") + local bicycle = way.tags:Find("bicycle") -- name if "" ~= ref and "" ~= name then @@ -215,126 +223,152 @@ function way_function (way) -- speed if route_speeds[route] then -- ferries (doesn't cover routes tagged using relations) - way.direction = Way.bidirectional + way.forward_mode = mode_ferry + way.backward_mode = mode_ferry way.ignore_in_grid = true if durationIsValid(duration) then way.duration = math.max( 1, parseDuration(duration) ) else - way.speed = route_speeds[route] + way.forward_speed = route_speeds[route] + way.backward_speed = route_speeds[route] end elseif railway and platform_speeds[railway] then -- railway platforms (old tagging scheme) - way.speed = platform_speeds[railway] + way.forward_speed = platform_speeds[railway] + way.backward_speed = platform_speeds[railway] elseif platform_speeds[public_transport] then -- public_transport platforms (new tagging platform) - way.speed = platform_speeds[public_transport] + way.forward_speed = platform_speeds[public_transport] + way.backward_speed = platform_speeds[public_transport] elseif railway and railway_speeds[railway] then + way.forward_mode = mode_train + way.backward_mode = mode_train -- railways if access and access_tag_whitelist[access] then - way.speed = railway_speeds[railway] - way.direction = Way.bidirectional + way.forward_speed = railway_speeds[railway] + way.backward_speed = railway_speeds[railway] end elseif amenity and amenity_speeds[amenity] then -- parking areas - way.speed = amenity_speeds[amenity] + way.forward_speed = amenity_speeds[amenity] + way.backward_speed = amenity_speeds[amenity] elseif bicycle_speeds[highway] then -- regular ways - way.speed = bicycle_speeds[highway] + way.forward_speed = bicycle_speeds[highway] + way.backward_speed = bicycle_speeds[highway] elseif access and access_tag_whitelist[access] then -- unknown way, but valid access tag - way.speed = default_speed + way.forward_speed = default_speed + way.backward_speed = default_speed else -- biking not allowed, maybe we can push our bike? -- essentially requires pedestrian profiling, for example foot=no mean we can't push a bike - -- TODO: if we can push, the way should be marked as pedestrion mode, but there's no way to do it yet from lua.. - if foot ~= 'no' then + if foot ~= 'no' and junction ~= "roundabout" then if pedestrian_speeds[highway] then -- pedestrian-only ways and areas - way.speed = pedestrian_speeds[highway] + way.forward_speed = pedestrian_speeds[highway] + way.backward_speed = pedestrian_speeds[highway] + way.forward_mode = mode_pushing + way.backward_mode = mode_pushing elseif man_made and man_made_speeds[man_made] then -- man made structures - way.speed = man_made_speeds[man_made] + way.forward_speed = man_made_speeds[man_made] + way.backward_speed = man_made_speeds[man_made] + way.forward_mode = mode_pushing + way.backward_mode = mode_pushing elseif foot == 'yes' then - way.speed = walking_speed + way.forward_speed = walking_speed + way.backward_speed = walking_speed + way.forward_mode = mode_pushing + way.backward_mode = mode_pushing + elseif foot_forward == 'yes' then + way.forward_speed = walking_speed + way.forward_mode = mode_pushing + way.backward_mode = 0 + elseif foot_backward == 'yes' then + way.forward_speed = walking_speed + way.forward_mode = 0 + way.backward_mode = mode_pushing end end end -- direction - way.direction = Way.bidirectional local impliedOneway = false if junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then - way.direction = Way.oneway impliedOneway = true end if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then - way.direction = Way.oneway + way.backward_mode = 0 elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then - way.direction = Way.bidirectional + -- prevent implied oneway elseif onewayClass == "-1" then - way.direction = Way.opposite + way.forward_mode = 0 elseif oneway == "no" or oneway == "0" or oneway == "false" then - way.direction = Way.bidirectional + -- prevent implied oneway elseif cycleway and string.find(cycleway, "opposite") == 1 then if impliedOneway then - way.direction = Way.opposite - else - way.direction = Way.bidirectional + way.forward_mode = 0 + way.backward_mode = mode_normal + way.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_left and cycleway_tags[cycleway_left] and cycleway_right and cycleway_tags[cycleway_right] then - way.direction = Way.bidirectional + -- prevent implied elseif cycleway_left and cycleway_tags[cycleway_left] then if impliedOneway then - way.direction = Way.opposite - else - way.direction = Way.bidirectional + way.forward_mode = 0 + way.backward_mode = mode_normal + way.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_right and cycleway_tags[cycleway_right] then if impliedOneway then - way.direction = Way.oneway - else - way.direction = Way.bidirectional + way.forward_mode = mode_normal + way.backward_speed = bicycle_speeds["cycleway"] + way.backward_mode = 0 end elseif oneway == "-1" then - way.direction = Way.opposite - elseif oneway == "yes" or oneway == "1" or oneway == "true" then - way.direction = Way.oneway + way.forward_mode = 0 + elseif oneway == "yes" or oneway == "1" or oneway == "true" or impliedOneway then + way.backward_mode = 0 end -- pushing bikes if bicycle_speeds[highway] or pedestrian_speeds[highway] then - if foot ~= 'no' then - if junction ~= "roundabout" then - if way.direction == Way.oneway then - way.backward_speed = walking_speed - elseif way.direction == Way.opposite then - way.backward_speed = walking_speed - way.speed = way.speed - end + if foot ~= "no" and junction ~= "roundabout" then + if way.backward_mode == 0 then + way.backward_speed = walking_speed + way.backward_mode = mode_pushing + elseif way.forward_mode == 0 then + way.forward_speed = walking_speed + way.forward_mode = mode_pushing end end - if way.backward_speed == way.speed then - -- TODO: no way yet to mark a way as pedestrian mode if forward/backward speeds are equal - way.direction = Way.bidirectional - end end -- cycleways if cycleway and cycleway_tags[cycleway] then - way.speed = bicycle_speeds["cycleway"] + way.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_left and cycleway_tags[cycleway_left] then - way.speed = bicycle_speeds["cycleway"] + way.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_right and cycleway_tags[cycleway_right] then - way.speed = bicycle_speeds["cycleway"] + way.forward_speed = bicycle_speeds["cycleway"] + end + + -- dismount + if bicycle == "dismount" then + way.forward_mode = mode_pushing + way.backward_mode = mode_pushing + way.forward_speed = walking_speed + way.backward_speed = walking_speed end -- surfaces if surface then surface_speed = surface_speeds[surface] if surface_speed then - if way.speed > 0 then - way.speed = surface_speed + if way.forward_speed > 0 then + way.forward_speed = surface_speed end if way.backward_speed > 0 then way.backward_speed = surface_speed @@ -343,26 +377,7 @@ function way_function (way) end -- maxspeed - -- TODO: maxspeed of backward direction - if take_minimum_of_speeds then - if maxspeed and maxspeed>0 then - way.speed = math.min(way.speed, maxspeed) - end - end - - -- Override speed settings if explicit forward/backward maxspeeds are given - if way.speed > 0 and maxspeed_forward ~= nil and maxspeed_forward > 0 then - if Way.bidirectional == way.direction then - way.backward_speed = way.speed - end - way.speed = maxspeed_forward - end - if maxspeed_backward ~= nil and maxspeed_backward > 0 then - way.backward_speed = maxspeed_backward - end - - way.type = 1 - return 1 + MaxSpeed.limit( way, maxspeed, maxspeed_forward, maxspeed_backward ) end function turn_function (angle) diff --git a/3party/osrm/osrm-backend/profiles/car.lua b/3party/osrm/osrm-backend/profiles/car.lua index 8f8d1bcdde..ad58cd86ef 100644 --- a/3party/osrm/osrm-backend/profiles/car.lua +++ b/3party/osrm/osrm-backend/profiles/car.lua @@ -1,7 +1,7 @@ -- Begin of globals --require("lib/access") --function temporarily inlined -barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true } +barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["checkpoint"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true } access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true, ["emergency"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } @@ -13,15 +13,15 @@ restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" } speed_profile = { ["motorway"] = 90, - ["motorway_link"] = 75, + ["motorway_link"] = 45, ["trunk"] = 85, - ["trunk_link"] = 70, + ["trunk_link"] = 40, ["primary"] = 65, - ["primary_link"] = 60, + ["primary_link"] = 30, ["secondary"] = 55, - ["secondary_link"] = 50, + ["secondary_link"] = 25, ["tertiary"] = 40, - ["tertiary_link"] = 30, + ["tertiary_link"] = 20, ["unclassified"] = 25, ["residential"] = 25, ["living_street"] = 10, @@ -32,9 +32,99 @@ speed_profile = { ["default"] = 10 } + +-- surface/trackype/smoothness +-- values were estimated from looking at the photos at the relevant wiki pages + +-- max speed for surfaces +surface_speeds = { + ["asphalt"] = nil, -- nil mean no limit. removing the line has the same effect + ["concrete"] = nil, + ["concrete:plates"] = nil, + ["concrete:lanes"] = nil, + ["paved"] = nil, + + ["cement"] = 80, + ["compacted"] = 80, + ["fine_gravel"] = 80, + + ["paving_stones"] = 60, + ["metal"] = 60, + ["bricks"] = 60, + + ["grass"] = 40, + ["wood"] = 40, + ["sett"] = 40, + ["grass_paver"] = 40, + ["gravel"] = 40, + ["unpaved"] = 40, + ["ground"] = 40, + ["dirt"] = 40, + ["pebblestone"] = 40, + ["tartan"] = 40, + + ["cobblestone"] = 30, + ["clay"] = 30, + + ["earth"] = 20, + ["stone"] = 20, + ["rocky"] = 20, + ["sand"] = 20, + + ["mud"] = 10 +} + +-- max speed for tracktypes +tracktype_speeds = { + ["grade1"] = 60, + ["grade2"] = 40, + ["grade3"] = 30, + ["grade4"] = 25, + ["grade5"] = 20 +} + +-- max speed for smoothnesses +smoothness_speeds = { + ["intermediate"] = 80, + ["bad"] = 40, + ["very_bad"] = 20, + ["horrible"] = 10, + ["very_horrible"] = 5, + ["impassable"] = 0 +} + +-- http://wiki.openstreetmap.org/wiki/Speed_limits +maxspeed_table_default = { + ["urban"] = 50, + ["rural"] = 90, + ["trunk"] = 110, + ["motorway"] = 130 +} + +-- List only exceptions +maxspeed_table = { + ["de:living_street"] = 7, + ["ru:living_street"] = 20, + ["ru:urban"] = 60, + ["ua:urban"] = 60, + ["at:rural"] = 100, + ["de:rural"] = 100, + ["at:trunk"] = 100, + ["cz:trunk"] = 0, + ["ro:trunk"] = 100, + ["cz:motorway"] = 0, + ["de:motorway"] = 0, + ["ru:motorway"] = 110, + ["gb:nsl_single"] = (60*1609)/1000, + ["gb:nsl_dual"] = (70*1609)/1000, + ["gb:motorway"] = (70*1609)/1000, + ["uk:nsl_single"] = (60*1609)/1000, + ["uk:nsl_dual"] = (70*1609)/1000, + ["uk:motorway"] = (70*1609)/1000 +} + traffic_signal_penalty = 2 --- End of globals local take_minimum_of_speeds = false local obey_oneway = true local obey_bollards = true @@ -48,6 +138,11 @@ local max = math.max local speed_reduction = 0.8 +--modes +local mode_normal = 1 +local mode_ferry = 2 + + local function find_access_tag(source,access_tags_hierachy) for i,v in ipairs(access_tags_hierachy) do local has_tag = source.tags:Holds(v) @@ -69,11 +164,21 @@ local function parse_maxspeed(source) return 0 end local n = tonumber(source:match("%d*")) - if not n then - n = 0 - end - if string.match(source, "mph") or string.match(source, "mp/h") then - n = (n*1609)/1000; + if n then + if string.match(source, "mph") or string.match(source, "mp/h") then + n = (n*1609)/1000; + end + else + -- parse maxspeed like FR:urban + source = string.lower(source) + n = maxspeed_table[source] + if not n then + local highway_type = string.match(source, "%a%a:(%a+)") + n = maxspeed_table_default[highway_type] + if not n then + n = 0 + end + end end return n end @@ -169,8 +274,10 @@ function way_function (way) if durationIsValid(duration) then way.duration = max( parseDuration(duration), 1 ); end - way.direction = Way.bidirectional - way.speed = route_speed + way.forward_mode = mode_ferry + way.backward_mode = mode_ferry + way.forward_speed = route_speed + way.backward_speed = route_speed end -- leave early of this way is not accessible @@ -178,33 +285,55 @@ function way_function (way) return end - if way.speed == -1 then + if way.forward_speed == -1 then local highway_speed = speed_profile[highway] local max_speed = parse_maxspeed( way.tags:Find("maxspeed") ) -- Set the avg speed on the way if it is accessible by road class if highway_speed then if max_speed > highway_speed then - way.speed = max_speed + way.forward_speed = max_speed + way.backward_speed = max_speed -- max_speed = math.huge else - way.speed = highway_speed + way.forward_speed = highway_speed + way.backward_speed = highway_speed end else -- Set the avg speed on ways that are marked accessible if access_tag_whitelist[access] then - way.speed = speed_profile["default"] + way.forward_speed = speed_profile["default"] + way.backward_speed = speed_profile["default"] end end if 0 == max_speed then max_speed = math.huge end - way.speed = min(way.speed, max_speed) + way.forward_speed = min(way.forward_speed, max_speed) + way.backward_speed = min(way.backward_speed, max_speed) end - if -1 == way.speed then + if -1 == way.forward_speed and -1 == way.backward_speed then return end + -- reduce speed on bad surfaces + local surface = way.tags:Find("surface") + local tracktype = way.tags:Find("tracktype") + local smoothness = way.tags:Find("smoothness") + + if surface and surface_speeds[surface] then + way.forward_speed = math.min(surface_speeds[surface], way.forward_speed) + way.backward_speed = math.min(surface_speeds[surface], way.backward_speed) + end + if tracktype and tracktype_speeds[tracktype] then + way.forward_speed = math.min(tracktype_speeds[tracktype], way.forward_speed) + way.backward_speed = math.min(tracktype_speeds[tracktype], way.backward_speed) + end + if smoothness and smoothness_speeds[smoothness] then + way.forward_speed = math.min(smoothness_speeds[smoothness], way.forward_speed) + way.backward_speed = math.min(smoothness_speeds[smoothness], way.backward_speed) + end + -- parse the remaining tags local name = way.tags:Find("name") local ref = way.tags:Find("ref") @@ -237,17 +366,16 @@ function way_function (way) end -- Set direction according to tags on way - way.direction = Way.bidirectional if obey_oneway then if oneway == "-1" then - way.direction = Way.opposite + way.forward_mode = 0 elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or (highway == "motorway_link" and oneway ~="no") or (highway == "motorway" and oneway ~= "no") then - way.direction = Way.oneway + way.backward_mode = 0 end end @@ -255,10 +383,10 @@ function way_function (way) local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward")) local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward")) if maxspeed_forward > 0 then - if Way.bidirectional == way.direction then - way.backward_speed = way.speed + if 0 ~= way.forward_mode and 0 ~= way.backward_mode then + way.backward_speed = way.forward_speed end - way.speed = maxspeed_forward + way.forward_speed = maxspeed_forward end if maxspeed_backward > 0 then way.backward_speed = maxspeed_backward @@ -268,14 +396,12 @@ function way_function (way) if ignore_in_grid[highway] then way.ignore_in_grid = true end - way.type = 1 -- scale speeds to get better avg driving times - way.speed = way.speed * speed_reduction - if maxspeed_backward > 0 then + way.forward_speed = way.forward_speed * speed_reduction + if way.backward_speed > 0 then way.backward_speed = way.backward_speed*speed_reduction end - return end -- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT diff --git a/3party/osrm/osrm-backend/profiles/examples/postgis.lua b/3party/osrm/osrm-backend/profiles/examples/postgis.lua index 89ecbc7958..b02a43d8a5 100644 --- a/3party/osrm/osrm-backend/profiles/examples/postgis.lua +++ b/3party/osrm/osrm-backend/profiles/examples/postgis.lua @@ -65,11 +65,11 @@ function way_function (way) local cursor = assert( sql_con:execute(sql_query) ) -- execute querty local row = cursor:fetch( {}, "a" ) -- fetch first (and only) row - way.speed = 20.0 -- default speed + way.forward_speed = 20.0 -- default speed if row then local val = tonumber(row.val) -- read 'val' from row if val > 10 then - way.speed = way.speed / math.log10( val ) -- reduce speed by amount of industry close by + way.forward_speed = way.forward_speed / math.log10( val ) -- reduce speed by amount of industry close by end end cursor:close() -- done with this query diff --git a/3party/osrm/osrm-backend/profiles/foot.lua b/3party/osrm/osrm-backend/profiles/foot.lua index 144a5f96c4..7c366bf119 100644 --- a/3party/osrm/osrm-backend/profiles/foot.lua +++ b/3party/osrm/osrm-backend/profiles/foot.lua @@ -63,6 +63,10 @@ traffic_signal_penalty = 2 u_turn_penalty = 2 use_turn_restrictions = false +--modes +local mode_normal = 1 +local mode_ferry = 2 + function get_exceptions(vector) for i,v in ipairs(restriction_exception_tags) do vector:Add(v) @@ -105,25 +109,25 @@ function way_function (way) local railway = way.tags:Find("railway") local amenity = way.tags:Find("amenity") local public_transport = way.tags:Find("public_transport") - if (not highway or highway == '') and + if (not highway or highway == '') and (not route or route == '') and (not railway or railway=='') and (not amenity or amenity=='') and (not man_made or man_made=='') and - (not public_transport or public_transport=='') - then - return 0 + (not public_transport or public_transport=='') + then + return end -- don't route on ways that are still under construction if highway=='construction' then - return 0 + return end -- access local access = Access.find_access_tag(way, access_tags_hierachy) if access_tag_blacklist[access] then - return 0 + return end local name = way.tags:Find("name") @@ -156,50 +160,52 @@ function way_function (way) -- speed if route_speeds[route] then -- ferries (doesn't cover routes tagged using relations) - way.direction = Way.bidirectional way.ignore_in_grid = true if durationIsValid(duration) then way.duration = math.max( 1, parseDuration(duration) ) else - way.speed = route_speeds[route] + way.forward_speed = route_speeds[route] + way.backward_speed = route_speeds[route] end + way.forward_mode = mode_ferry + way.backward_mode = mode_ferry elseif railway and platform_speeds[railway] then -- railway platforms (old tagging scheme) - way.speed = platform_speeds[railway] + way.forward_speed = platform_speeds[railway] + way.backward_speed = platform_speeds[railway] elseif platform_speeds[public_transport] then -- public_transport platforms (new tagging platform) - way.speed = platform_speeds[public_transport] + way.forward_speed = platform_speeds[public_transport] + way.backward_speed = platform_speeds[public_transport] elseif amenity and amenity_speeds[amenity] then -- parking areas - way.speed = amenity_speeds[amenity] + way.forward_speed = amenity_speeds[amenity] + way.backward_speed = amenity_speeds[amenity] elseif speeds[highway] then -- regular ways - way.speed = speeds[highway] + way.forward_speed = speeds[highway] + way.backward_speed = speeds[highway] elseif access and access_tag_whitelist[access] then -- unknown way, but valid access tag - way.speed = walking_speed + way.forward_speed = walking_speed + way.backward_speed = walking_speed end -- oneway if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then - way.direction = Way.oneway + way.backward_mode = 0 elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then - way.direction = Way.bidirectional + -- nothing to do elseif onewayClass == "-1" then - way.direction = Way.opposite - else - way.direction = Way.bidirectional + way.forward_mode = 0 end -- surfaces if surface then surface_speed = surface_speeds[surface] if surface_speed then - way.speed = math.min(way.speed, surface_speed) + way.forward_speed = math.min(way.forward_speed, surface_speed) way.backward_speed = math.min(way.backward_speed, surface_speed) end end - - way.type = 1 - return 1 end diff --git a/3party/osrm/osrm-backend/profiles/lib/maxspeed.lua b/3party/osrm/osrm-backend/profiles/lib/maxspeed.lua new file mode 100644 index 0000000000..aca344a796 --- /dev/null +++ b/3party/osrm/osrm-backend/profiles/lib/maxspeed.lua @@ -0,0 +1,17 @@ +local math = math + +module "MaxSpeed" + +function limit(way,max,maxf,maxb) + if maxf and maxf>0 then + way.forward_speed = math.min(way.forward_speed, maxf) + elseif max and max>0 then + way.forward_speed = math.min(way.forward_speed, max) + end + + if maxb and maxb>0 then + way.backward_speed = math.min(way.backward_speed, maxb) + elseif max and max>0 then + way.backward_speed = math.min(way.backward_speed, max) + end +end diff --git a/3party/osrm/osrm-backend/profiles/testbot.lua b/3party/osrm/osrm-backend/profiles/testbot.lua index 66d6599740..a0b06f56d2 100644 --- a/3party/osrm/osrm-backend/profiles/testbot.lua +++ b/3party/osrm/osrm-backend/profiles/testbot.lua @@ -6,10 +6,19 @@ -- Secondary road: 18km/h = 18000m/3600s = 100m/20s -- Tertiary road: 12km/h = 12000m/3600s = 100m/30s +-- modes: +-- 1: normal +-- 2: route +-- 3: river downstream +-- 4: river upstream +-- 5: steps down +-- 6: steps up + speed_profile = { ["primary"] = 36, ["secondary"] = 18, ["tertiary"] = 12, + ["steps"] = 6, ["default"] = 24 } @@ -61,14 +70,21 @@ function way_function (way) if route ~= nil and durationIsValid(duration) then way.duration = math.max( 1, parseDuration(duration) ) + way.forward_mode = 2 + way.backward_mode = 2 else local speed_forw = speed_profile[highway] or speed_profile['default'] local speed_back = speed_forw if highway == "river" then local temp_speed = speed_forw; + way.forward_mode = 3 + way.backward_mode = 4 speed_forw = temp_speed*1.5 speed_back = temp_speed/1.5 + elseif highway == "steps" then + way.forward_mode = 5 + way.backward_mode = 6 end if maxspeed_forward ~= nil and maxspeed_forward > 0 then @@ -87,26 +103,19 @@ function way_function (way) end end - way.speed = speed_forw - if speed_back ~= way_forw then - way.backward_speed = speed_back - end + way.forward_speed = speed_forw + way.backward_speed = speed_back end if oneway == "no" or oneway == "0" or oneway == "false" then - way.direction = Way.bidirectional + -- nothing to do elseif oneway == "-1" then - way.direction = Way.opposite + way.forward_mode = 0 elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" then - way.direction = Way.oneway - else - way.direction = Way.bidirectional + way.backward_mode = 0 end if junction == 'roundabout' then way.roundabout = true end - - way.type = 1 - return 1 end diff --git a/3party/osrm/osrm-backend/routed.cpp b/3party/osrm/osrm-backend/routed.cpp index adf2e2dbc9..a7ba54ab5f 100644 --- a/3party/osrm/osrm-backend/routed.cpp +++ b/3party/osrm/osrm-backend/routed.cpp @@ -26,10 +26,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Library/OSRM.h" -#include "Server/ServerFactory.h" +#include "Server/Server.h" #include "Util/GitDescription.h" #include "Util/ProgramOptions.h" -#include "Util/SimpleLogger.h" +#include "Util/simple_logger.hpp" #include "Util/FingerPrint.h" #ifdef __linux__ @@ -101,27 +101,16 @@ int main(int argc, const char *argv[]) SimpleLogger().Write(logWARNING) << argv[0] << " could not be locked to RAM"; } #endif - SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", " - << "compiled at " << __DATE__ << ", " __TIME__; + SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; if (use_shared_memory) { SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; } - else - { - SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; - SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"]; - SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"]; - SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"]; - SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"]; - SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"]; - SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"]; - SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"]; - SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; - SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; - SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; - } + + SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; + SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; + SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; #ifndef _WIN32 int sig = 0; sigset_t new_mask; @@ -131,8 +120,8 @@ int main(int argc, const char *argv[]) #endif OSRM osrm_lib(server_paths, use_shared_memory); - Server *routing_server = - ServerFactory::CreateServer(ip_address, ip_port, requested_thread_num); + auto routing_server = + Server::CreateServer(ip_address, ip_port, requested_thread_num); routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib); @@ -169,19 +158,19 @@ int main(int argc, const char *argv[]) auto status = future.wait_for(std::chrono::seconds(2)); - if (status != std::future_status::ready) + if (status == std::future_status::ready) + { + server_thread.join(); + } + else { SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!"; server_task.reset(); // just kill it } - else - { - server_thread.join(); - } } SimpleLogger().Write() << "freeing objects"; - delete routing_server; + routing_server.reset(); SimpleLogger().Write() << "shutdown completed"; } catch (const std::exception &e) diff --git a/3party/osrm/osrm-backend/taginfo.json b/3party/osrm/osrm-backend/taginfo.json new file mode 100644 index 0000000000..17a4f8f24e --- /dev/null +++ b/3party/osrm/osrm-backend/taginfo.json @@ -0,0 +1,84 @@ +{ + "data_format": 1, + "data_url": "https://raw.githubusercontent.com/Project-OSRM/osrm-backend/develop/taginfo.json", + "project": { + "name": "Open Source Routing Machine (car profile)", + "description": "High-performance routing engine for shortest paths in road networks.", + "project_url": "http://project-osrm.org", + "icon_url": "http://project-osrm.org/images/osrm_icon.png", + "contact_name": "Dennis Luxen", + "contact_email": "info@project-osrm.org" + }, + "tags": [ + { + "key": "highway", + "description": "Type of road.", + "object_types": [ "way" ] + }, + { + "key": "service", + "value": "parking_aisle", + "object_types": [ "way" ] + }, + { + "key": "oneway", + "object_types": [ "way" ] + }, + { + "key": "area", + "value": "yes", + "object_types": [ "way" ], + "description": "Roads with area=yes are ignored by default." + }, + { + "key": "impassable", + "description": "This is used by HOT." + }, + { + "key": "status", + "description": "This is used by HOT." + }, + { + "key": "access", + "object_types": [ "way" ] + }, + { + "key": "barrier" + }, + { + "key": "maxspeed", + "object_types": [ "way" ] + }, + { + "key": "maxspeed:forward", + "object_types": [ "way" ] + }, + { + "key": "maxspeed:backward", + "object_types": [ "way" ] + }, + { + "key": "duration" + }, + { + "key": "name", + "object_types": [ "way" ], + "description": "Name of road for navigation instructions." + }, + { + "key": "ref", + "object_types": [ "way" ], + "description": "Ref of road for navigation instructions, overrides name." + }, + { + "key": "junction", + "object_types": [ "way" ], + "value": "roundabout" + }, + { + "key": "type", + "value": "restriction", + "object_types": [ "relation" ] + } + ] +} diff --git a/3party/osrm/osrm-backend/test/.stxxl b/3party/osrm/osrm-backend/test/.stxxl new file mode 100644 index 0000000000..b1765e2c08 --- /dev/null +++ b/3party/osrm/osrm-backend/test/.stxxl @@ -0,0 +1 @@ +disk=/tmp/stxxl,10,syscall diff --git a/3party/osrm/osrm-backend/typedefs.h b/3party/osrm/osrm-backend/typedefs.h index ff1d2a1579..e45a6e8c90 100644 --- a/3party/osrm/osrm-backend/typedefs.h +++ b/3party/osrm/osrm-backend/typedefs.h @@ -35,16 +35,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef M_PI #define M_PI 3.14159265358979323846 #endif -#define constexpr const static #endif -typedef unsigned int NodeID; -typedef unsigned int EdgeID; -typedef int EdgeWeight; +using NodeID = unsigned int; +using EdgeID = unsigned int; +using EdgeWeight = int; -constexpr NodeID SPECIAL_NODEID = std::numeric_limits::max(); -constexpr EdgeID SPECIAL_EDGEID = std::numeric_limits::max(); -constexpr unsigned INVALID_NAMEID = std::numeric_limits::max(); -constexpr EdgeWeight INVALID_EDGE_WEIGHT = std::numeric_limits::max(); +static const NodeID SPECIAL_NODEID = std::numeric_limits::max(); +static const EdgeID SPECIAL_EDGEID = std::numeric_limits::max(); +static const unsigned INVALID_NAMEID = std::numeric_limits::max(); +static const EdgeWeight INVALID_EDGE_WEIGHT = std::numeric_limits::max(); #endif /* TYPEDEFS_H */