Compare commits

...

532 Commits

Author SHA1 Message Date
Dennis Luxen 725b93a961 Merge branch 'develop' 2015-01-06 11:03:29 +01:00
Dennis Luxen a21e4c5a0b link library against exception lib 2015-01-06 11:00:44 +01:00
Dennis Luxen 433db17083 fix initialization of simple client 2015-01-05 18:14:49 +01:00
Dennis Luxen f8753fb9f1 fix overly long line 2015-01-05 16:32:11 +01:00
Dennis Luxen 25d5653f66 rename a number of overly long variable names 2015-01-05 16:29:33 +01:00
Dennis Luxen 703a88a639 remove empty d'tor from osrm::exception 2015-01-05 15:53:28 +01:00
Dennis Luxen 25326b571b renamed: Util/OSRMException.h -> Util/osrm_exception.hpp 2015-01-05 15:40:05 +01:00
Dennis Luxen 5e2f4c9d2d fix header include 2015-01-05 14:47:05 +01:00
Dennis Luxen f43d380fe2 remove unneeded method 2015-01-05 14:46:38 +01:00
Dennis Luxen 2240d3d0d1 add new header file 2015-01-05 14:39:17 +01:00
Dennis Luxen b6eea9a880 fix unintended implicit cast from unsigned to signed 2015-01-05 14:38:24 +01:00
Dennis Luxen 6bbd7c0c0b update ignore list in git 2015-01-05 14:37:35 +01:00
Dennis Luxen 2caeb4008c renamed: Util/GitDescription.cpp.in -> Util/git_sha.cpp.in
renamed:    Util/GitDescription.h -> Util/git_sha.h
2015-01-05 14:32:04 +01:00
Dennis Luxen a4919ffb45 re-enable hintin mechanism 2015-01-05 12:59:29 +01:00
Dennis Luxen b384340cbb Revert "remove remnants of hinting mechanism"
This reverts commit 7de428233e.
2015-01-05 12:57:34 +01:00
Dennis Luxen 061f46306f remove unneeded lvalue parameter 2015-01-05 12:00:11 +01:00
Dennis Luxen fe1f11b071 renamed: Util/StringUtil.h -> Util/string_util.hpp 2015-01-05 10:22:11 +01:00
Patrick Niklaus d3f5db576a Enable gcc color output when available 2015-01-04 23:13:15 +01:00
Emil Tin 0ca586e1c8 cuke: remove unneeded @x tag 2015-01-03 16:53:01 +01:00
Emil Tin a0b55f9df3 table tests: use empty string to mean no route 2015-01-03 11:12:47 +01:00
Dennis Luxen 24943ccee6 fix use of old-style cast 2015-01-02 17:43:46 +01:00
Dennis Luxen bcaaf34fa7 implicit conversion loses integer precision 2015-01-02 17:41:11 +01:00
Dennis Luxen ea17d1f6c7 dynamic exception specifications are deprecated, use 'noexcept' instead 2015-01-02 17:39:11 +01:00
Dennis Luxen 3be734010c fix warning: 'const' type qualifier on return type has no effect 2015-01-02 17:34:21 +01:00
Dennis Luxen e79787cc77 reorder members to avoid padding class 'SimpleLogger' with 4 bytes to align 'os' 2015-01-02 17:32:52 +01:00
Dennis Luxen 7de428233e remove remnants of hinting mechanism 2015-01-02 17:10:47 +01:00
Dennis Luxen 9722f56be8 remove more debug code 2015-01-02 16:41:36 +01:00
Dennis Luxen e766d206f1 remove debug code 2015-01-02 16:06:09 +01:00
Dennis Luxen 1fa9091239 retire json hinting mechanism 2015-01-02 15:46:43 +01:00
Dennis Luxen 04e1e5e3a2 reformat code 2015-01-02 15:17:15 +01:00
Dennis Luxen fa5c0560fa use tiny cc id if all phantoms have such an id, and if and only if all ids are equal 2015-01-02 09:36:27 +01:00
Dennis Luxen 55d47b3e31 reimplement incremental nearest neighbor query 2015-01-02 09:36:27 +01:00
Dennis Luxen 5bb96fd477 reformat code of phantom node c'tor for legibility 2015-01-02 09:36:27 +01:00
Dennis Luxen 22b404a1b4 add is_in_tiny_cc() util function 2015-01-02 09:36:27 +01:00
Dennis Luxen 03dcf82602 use first phantom node of second pair 2015-01-02 09:36:26 +01:00
Dennis Luxen 95d1e8a4f1 adapt viaroute plugin to query NN search for vector of phantom nodes 2015-01-02 09:36:26 +01:00
Emil Tin 67f68b47db add fuzzy match to table tests, add more tests 2015-01-01 20:19:41 +01:00
Emil Tin 593808f24d initial support for testing distance matrices 2015-01-01 15:12:45 +01:00
Dennis Luxen 0a884cc64a don't stop traversing at bollard node 2014-12-31 16:04:53 +01:00
Dennis Luxen a54d4b98b1 add const keyword in range based for loop 2014-12-31 16:04:53 +01:00
Patrick Niklaus 23132e5292 Use >= 0 to include routes where start/end is the same 2014-12-31 15:59:42 +01:00
Dennis Luxen d741b624be pass component class by ref (not value) in edge-based graph factory 2014-12-30 11:44:11 +01:00
Patrick Niklaus 00bc394bdb Fix off-by-one in distance table plugin.
Should fix #1320.
2014-12-28 17:45:55 +01:00
Dennis Luxen d7215ad185 fix tests, temporarily disable one test case 2014-12-24 13:03:05 +01:00
Dennis Luxen 2b63eb8243 remove zoom level from nearest neighbor calls 2014-12-24 10:40:03 +01:00
Dennis Luxen 1bb3da0332 expose component_id in phantom node 2014-12-24 10:25:27 +01:00
Dennis Luxen c7d3d635f6 fix test compile 2014-12-23 17:18:32 +01:00
Dennis Luxen f4c8db6105 - serialize component_id
- remove calls to deprecated NN function in facades
2014-12-23 16:14:28 +01:00
Dennis Luxen b2637b9a43 compute component id for each SCC 2014-12-23 15:26:06 +01:00
Dennis Luxen 09d0ac3838 add aux. function to get component id for a given node 2014-12-23 15:17:38 +01:00
Dennis Luxen f42cc848d5 - correct number of components in compressed graph by number of removed nodes
- replace integer for loops by integer range-based loop
2014-12-23 14:51:25 +01:00
Dennis Luxen 4b1224f874 fix copyright year 2014-12-23 14:38:04 +01:00
Dennis Luxen 10bb2cce8e count number of removed nodes as a private member variable in EdgeBasedGraphFactory 2014-12-23 14:37:01 +01:00
Dennis Luxen 8174b3b85a output total number of compoments and those of size one 2014-12-23 14:33:38 +01:00
Dennis Luxen 71e2f2ed61 move SCC stats output out of algo implementation 2014-12-23 14:31:55 +01:00
Dennis Luxen 8d8724b3e1 use SCC code for exploration of components 2014-12-23 12:27:04 +01:00
Dennis Luxen 47f65ccba6 use restriction map in tiny components 2014-12-23 11:47:19 +01:00
Dennis Luxen df0c1106ce compile and link restriction map object to components and routes 2014-12-23 11:46:25 +01:00
Dennis Luxen 47a2271e27 copy edits: 2014-12-23 11:30:45 +01:00
Dennis Luxen ea367a7f37 add better checks for forbidden routes 2014-12-22 18:12:47 +01:00
Dennis Luxen f4b192e33c simplify code 2014-12-22 18:12:18 +01:00
Dennis Luxen a5c824f694 adapt tiny_components.hpp to have the same interface as bfs_components.hpp 2014-12-22 16:43:57 +01:00
Dennis Luxen ccc4607d6d renamed: Util/GraphLoader.h -> Util/graph_loader.hpp 2014-12-22 16:09:01 +01:00
Dennis Luxen 4ec41392f7 code cleanup in graph loading function 2014-12-22 16:03:22 +01:00
Dennis Luxen 5f2b2cd0f7 remove dead code 2014-12-22 15:53:11 +01:00
Dennis Luxen 361e3ca356 fix a copy&paste oversight, fixes #1319
remove UINT_MAX
2014-12-22 15:11:37 +01:00
Dennis Luxen 13bf4fab32 make implementation of restriction map independent of graph type 2014-12-19 16:46:12 +01:00
Dennis Luxen 4b583e8ce9 replace insecure std::rand by C++11's random number generation
fixes coverity issue 1248916 Don't call
2014-12-19 10:59:12 +01:00
Dennis Luxen d31c6fe286 fix coverity issue 1258907 Division or modulo by float zero 2014-12-19 10:49:33 +01:00
Dennis Luxen 79de97d814 move application logic, i.e. shape file generation, from SCC traversal class to calling tool code 2014-12-18 18:14:14 +01:00
Dennis Luxen 1c5d093b59 Revert "catch uncaught exception"
This reverts commit ecff2beafa.
2014-12-18 16:42:14 +01:00
Dennis Luxen ecff2beafa catch uncaught exception 2014-12-18 16:11:49 +01:00
Dennis Luxen 7e0b19c43d renamed Util/StdHashExtensions.h -> Util/std_hash.hpp 2014-12-18 10:09:31 +01:00
Dennis Luxen 2ebe2faa74 renamed Util/TimingUtil.h -> Util/timing_util.hpp 2014-12-17 17:33:31 +01:00
Dennis Luxen aec1451168 add workaround for Windows build issues. 2014-12-17 16:24:43 +01:00
Dennis Luxen 38251aa513 construct RequestParser object on demand
pass CompressionType refs instead of ptrs to parser
2014-12-17 15:48:33 +01:00
Dennis Luxen d92e8ca8d2 remove unneeded function 2014-12-17 15:09:07 +01:00
Dennis Luxen 2e5876d488 add lock_guard to protect against data races in initialization of scripting environment
rename function names to reduce camel case noise
2014-12-17 14:34:23 +01:00
Dennis Luxen 3dddd16ec7 bump osmium version 2014-12-17 11:19:08 +01:00
Dennis Luxen 40ff7ad999 update speed profile from external calibration data 2014-12-17 11:02:04 +01:00
Dennis Luxen cb79f769c9 Merge pull request #1312 from joto/const
Some cleanups in the extractor code.
2014-12-12 17:10:47 -08:00
Jochen Topf e95feff016 Use 'const' where possible in extractor and simplify iterator loop. 2014-12-13 00:23:41 +01:00
Jochen Topf f65b32c1af Use atomics for counters. 2014-12-13 00:16:32 +01:00
Dennis Luxen 46dd9b9887 remove duplicated paths 2014-12-13 00:09:25 +01:00
Dennis Luxen 4445f21e8a renamed: Tools/* -> tools/* 2014-11-28 15:36:40 +01:00
Dennis Luxen 00d3676a20 renamed: RoutingAlgorithms/* routing_algorithms/ 2014-11-28 15:33:41 +01:00
Dennis Luxen 0f7cb12e97 renamed: ThirdParty/* -> third_party/* 2014-11-28 15:22:26 +01:00
Dennis Luxen 8485e02c00 renamed: Plugins/* -> plugins/* 2014-11-28 15:14:13 +01:00
Dennis Luxen ae7300f9b4 renamed: extractor.cpp -> extract.cpp
renamed:    Extractor/* -> extractor/
2014-11-28 15:00:48 +01:00
Dennis Luxen fc796539e8 deleted: Docs/webclient.txt 2014-11-28 14:39:28 +01:00
Dennis Luxen 1d8c43b445 renamed: Descriptors/* -> descriptors/* 2014-11-28 14:36:38 +01:00
Dennis Luxen 58de37e822 renamed: DataStructures/* -> data_structures/* 2014-11-28 12:15:31 +01:00
Dennis Luxen 7b3a0c5105 renamed: Contractor/* -> contractor/* 2014-11-28 10:30:21 +01:00
Dennis Luxen 592034653c renamed: Benchmarks/* -> benchmarks/*s 2014-11-28 10:15:27 +01:00
Dennis Luxen 8d9f830c53 change includes to lower case algorithms/ 2014-11-28 10:12:08 +01:00
Dennis Luxen d8eea0ce0e renamed: Algorithms/* -> algorithms/* 2014-11-28 10:07:06 +01:00
Dennis Luxen c28c441e77 renamed: Contractor.h -> contractor.hpp 2014-11-27 19:07:59 +01:00
Dennis Luxen 1391420699 renamed: ../Benchmarks/StaticRTreeBench.cpp -> ../Benchmarks/static_rtree.cpp 2014-11-27 19:04:30 +01:00
Dennis Luxen c0be751ef4 renamed: DataStructures/SegmentInformation.h -> DataStructures/segment_information.hpp 2014-11-27 18:54:20 +01:00
Dennis Luxen 5e2462e061 renamed: DataStructures/RestrictionMap.cpp -> DataStructures/restriction_map.cpp
renamed:    DataStructures/RestrictionMap.h -> DataStructures/restriction_map.hpp
2014-11-27 18:38:21 +01:00
Dennis Luxen 5c0eb4772d renamed: Util/LuaUtil.h -> Util/lua_util.hpp 2014-11-27 18:31:01 +01:00
Dennis Luxen ef8706b4e1 fix inconsistencies with integer and iterator range header files, closes #1296 2014-11-27 09:54:57 +01:00
Dennis Luxen acd1919e8d renamed: Util/Azimuth.h -> Util/bearing.hpp 2014-11-26 16:55:18 +01:00
Dennis Luxen 459e2a322b cast computed way in a proper way, add a static assertion to check for file types via traits 2014-11-26 12:05:55 +01:00
Dennis Luxen e62caf33aa Merge pull request #1294 from alex85k/appveyor
update appveyor.yml (newer libraries, algorithm-tests)
2014-11-26 09:46:05 +01:00
alex85k 72fd0f3d41 update appveyor.yml (newer libraries, algorithm-tests) 2014-11-26 12:38:04 +03:00
Dennis Luxen 032c21c545 fix mixed up include header <numeric> <-> <cmath> 2014-11-25 14:52:21 +01:00
Dennis Luxen b391daac6d use C++11's std::round from <numeric> instead of C-style round from cstdlib 2014-11-25 14:49:33 +01:00
Dennis Luxen 8cb6959e3f untangle includes 2014-11-24 15:51:52 +01:00
Dennis Luxen 49c817a60e remove redundant clear() calls in Extractor.cpp 2014-11-24 15:42:55 +01:00
Dennis Luxen 6859b53155 use JSON container to hold all intermediate results:
- no hand-rolled GPX generation anymore
- render gpx thru a JSONContainer visitor pattern
- precursor to expose JSON containter as result from OSRM lib interface, cf. #1261
2014-11-24 15:15:57 +01:00
Dennis Luxen c581563230 fix setting of restriction end nodes, fixes #1286, and potentially #1287 2014-11-24 11:29:25 +01:00
Patrick Niklaus fc1db35f27 Add missing json dependency to cucumber 2014-11-23 13:29:22 +01:00
Patrick Niklaus 2734a4aee4 Merge pull request #1284 from Project-OSRM/algo-test-fix
Fix DP unit test
2014-11-22 16:22:07 +01:00
Patrick Niklaus 172f65969c Fix DP unit test 2014-11-22 13:47:20 +01:00
Dennis Luxen f0dbe0deb9 fix compilation 2014-11-21 09:35:20 +01:00
Dennis Luxen 8f8d81f90c renamed: Algorithms/StronglyConnectedComponents.h -> Algorithms/tiny_components.hpp 2014-11-20 17:21:35 +01:00
Dennis Luxen 665523bc7e add springclean tool to ignore list 2014-11-20 17:05:55 +01:00
Dennis Luxen 99e8fa70ba renamed: Algorithms/DouglasPeucker.cpp -> Algorithms/douglas_peucker.cpp
renamed:    Algorithms/DouglasPeucker.h -> Algorithms/douglas_peucker.hpp
2014-11-20 17:04:52 +01:00
Dennis Luxen 4c1d7c9d73 renamed: Algorithms/ExtractRouteNames.h -> Algorithms/route_name_extraction.hpp 2014-11-20 17:01:36 +01:00
Dennis Luxen d1cc8e7ad7 renamed: Algorithms/BFSComponentExplorer.h -> Algorithms/bfs_components.hpp 2014-11-20 16:58:35 +01:00
Dennis Luxen 7629e44e4c renamed: Algorithms/IteratorBasedCRC32.h -> Algorithms/crc32_processor.hpp 2014-11-20 16:17:49 +01:00
Dennis Luxen b62f6a6141 renamed: Algorithms/ObjectToBase64.h -> Algorithms/object_encoder.hpp 2014-11-20 16:10:11 +01:00
Dennis Luxen 10d7a2396c move JSON rendering code out of container header file. prerequesite to #1261 2014-11-20 15:26:30 +01:00
Dennis Luxen 007eced326 fix variant include 2014-11-20 15:14:19 +01:00
Dennis Luxen 1128270d4b fix short variable names 2014-11-20 15:06:48 +01:00
Dennis Luxen c7d889bf9e add missing break 2014-11-20 15:02:02 +01:00
Dennis Luxen 7cb585c1a1 remove constant conditional operator 2014-11-20 15:00:49 +01:00
Dennis Luxen 75157221b2 commit another if statement 2014-11-20 14:59:27 +01:00
Dennis Luxen 9807520ef0 collapse if statement 2014-11-20 14:58:32 +01:00
Dennis Luxen c658ee5c78 fix OCLint warning: short variable name, unused parameter 2014-11-20 14:55:43 +01:00
Dennis Luxen cbfbcdcff5 reformat RestrictionParser 2014-11-20 10:46:14 +01:00
Dennis Luxen 9a0581ea7f Merge pull request #1159 from Project-OSRM/feature/libosmium
parallelizing profile calls and porting lib osmium to Windows
2014-11-20 10:20:09 +01:00
Dennis Luxen 60c268ddd6 reorder some of the code 2014-11-19 11:02:38 +01:00
Dennis Luxen 0361e0204a rename Clear() method to clear() 2014-11-19 10:53:28 +01:00
Dennis Luxen 2da427134b use push_back to insert into tbb::concurrent_vector as emplace_back is not generally available 2014-11-19 10:12:08 +01:00
Dennis Luxen 4fce0dadcf remove further debug output from profiles 2014-11-19 09:58:41 +01:00
Dennis Luxen 288c241fb4 move initialization of Lua error callback into scripting environment 2014-11-19 09:49:39 +01:00
Dennis Luxen f3e3eda69e remove debug output from bike profile 2014-11-19 09:47:23 +01:00
Dennis Luxen 0f4dd8103d add cast.hpp from osmium 2014-11-19 09:44:02 +01:00
Dennis Luxen 86ee05ee5e add missing include 2014-11-19 09:22:31 +01:00
Dennis Luxen 3b9c6a6465 reformat Extractor 2014-11-18 19:03:44 +01:00
Dennis Luxen 8e73a4a19d enable relation parsing with libosmium 2014-11-18 18:53:19 +01:00
Dennis Luxen 428bb36ec6 parallelize with a vector of iterators 2014-11-18 16:54:48 +01:00
Dennis Luxen 0a24df6bd0 Merge pull request #1279 from Project-OSRM/config-parsing-fix
Fix ignored config file. Fixes issue #1276.
2014-11-18 14:09:03 +01:00
Patrick Niklaus d3ca080729 Fix windows build. 2014-11-18 11:52:39 +01:00
Patrick Niklaus 7658031784 Fix ignored config file. Fixes issue #1276. 2014-11-18 00:43:38 +01:00
Dennis Luxen 710e74219a libosmium version bump 2014-11-17 14:58:39 +01:00
Dennis Luxen 0249bed53a bump variant dependency 2014-11-17 14:58:39 +01:00
Dennis Luxen 9d14f81b79 set default timestamp for tests 2014-11-17 14:58:39 +01:00
Dennis Luxen a7c683a83c forward way ID information properly in turn restrictions parsing 2014-11-17 14:58:38 +01:00
Dennis Luxen 16631bf454 port track smoothness to new parsing 2014-11-17 14:58:38 +01:00
Dennis Luxen 3c563f7073 rebase branch onto most recent changes from develop branch 2014-11-17 14:58:38 +01:00
Dennis Luxen 344bdbb707 basic parallelization infrastructure 2014-11-17 14:58:38 +01:00
Dennis Luxen a0256dfc60 add error callback when calling get_exceptions 2014-11-17 14:58:38 +01:00
Dennis Luxen b131f27eb9 use_turn_restrictions as global in car profile 2014-11-17 14:58:38 +01:00
Dennis Luxen 0d9b70552e refactor FirstAndLastSegmentOfWay 2014-11-17 14:58:38 +01:00
Dennis Luxen ea1a89290a uncouple configuration of Extractor into compile unit 2014-11-17 14:58:38 +01:00
Dennis Luxen 59f1679d37 move LUA error callback function into anonymous namespace 2014-11-17 14:58:37 +01:00
Dennis Luxen 5121983218 Rename NodeInfo -> QueryNode 2014-11-17 14:58:37 +01:00
Dennis Luxen 0d7141ce5b Rename NodeInfo -> QueryNode 2014-11-17 14:58:37 +01:00
Dennis Luxen b4b753ce2e rename variables in ExternalMemoryNode to be more telling and consistent 2014-11-17 14:58:37 +01:00
Dennis Luxen 4f666e4d53 remove dead code 2014-11-17 14:58:37 +01:00
Dennis Luxen 874a988527 add dummy NodeID.h (to move into include) 2014-11-17 14:58:37 +01:00
Dennis Luxen 51c79f9784 rename ExtractorStructs into a more telling name 2014-11-17 14:58:37 +01:00
Dennis Luxen 4d19811026 apply reformatting 2014-11-17 14:58:37 +01:00
Dennis Luxen d1454075ab untangle function object code for stxxl comperators 2014-11-17 14:58:37 +01:00
Dennis Luxen becb6cf5bf compile renamed object file 2014-11-17 14:58:36 +01:00
Dennis Luxen a6f34d2044 rename ImportNode.h/cpp -> ExternalMemoryNode.h/cpp 2014-11-17 14:58:36 +01:00
Dennis Luxen 7300024e13 remove unneeded code: HashTable 2014-11-17 14:58:36 +01:00
Dennis Luxen 282800e6b1 replace boost::optional with mapbox::util::optional 2014-11-17 14:58:36 +01:00
Dennis Luxen e938bd3481 Revert "remove implicitly defined inline keywords from header-implemented functions in Util/ headers"
This reverts commit dc35e97ae002bdfda4bc3a68507749c464cfe371.
2014-11-17 14:58:36 +01:00
Dennis Luxen 9b501276fb upgrade variant dependency 2014-11-17 14:58:36 +01:00
Dennis Luxen 90d191f5f8 remove implicitly defined inline keywords from header-implemented functions in Extractor/ExtractionHelperFunctions.h 2014-11-17 14:58:36 +01:00
Dennis Luxen f452e7f9d2 remove implicitly defined inline keywords from header-implemented functions in Util/ headers 2014-11-17 14:58:36 +01:00
Dennis Luxen 1d25f41122 remove unused code 2014-11-17 14:58:36 +01:00
Dennis Luxen 5556785804 remove implicitly defined inline keywords from header-implemented functions in ExtractionWay 2014-11-17 14:58:35 +01:00
Dennis Luxen 22ce4c24fb move key/value wrapper function into anonymous namespace in ScriptingEnvironment 2014-11-17 14:58:35 +01:00
Dennis Luxen d4d2d127d1 pass an rvalue of a parsed node into the external memory storage 2014-11-17 14:58:35 +01:00
Dennis Luxen 3c28932862 remove errenous define in AppVeyor cmake call 2014-11-17 14:58:35 +01:00
Dennis Luxen 7e9177cb3c link against expat.lib 2014-11-17 14:58:35 +01:00
Dennis Luxen f692103c81 fix build on windows by linking against the right libs 2014-11-17 14:58:35 +01:00
Dennis Luxen 5a1dfe9b89 include variant library from a relative path 2014-11-17 14:58:35 +01:00
Dennis Luxen 7175180dc9 remove deprecated code 2014-11-17 14:58:34 +01:00
Dennis Luxen f95d1fa8ba add expat to cmake call on AppVeyor 2014-11-17 14:58:34 +01:00
Dennis Luxen 7b57068f6f manually install osmpbf, the one on Travis is outdated 2014-11-17 14:58:34 +01:00
Dennis Luxen d79eac3e26 port foot profile 2014-11-17 14:58:34 +01:00
Dennis Luxen 27c255c874 port bicycle profile 2014-11-17 14:58:34 +01:00
Dennis Luxen bdc611b23a port timestamp test to libosmium 2014-11-17 14:58:34 +01:00
Dennis Luxen 4cddf0bf5d replace explicit value fetching with wrapper call 2014-11-17 14:58:34 +01:00
Dennis Luxen 462d4c99cc port testbot profile 2014-11-17 14:58:34 +01:00
Dennis Luxen 94a2188090 explicitly specify optional parameter 2014-11-17 14:58:33 +01:00
Dennis Luxen ebcdcb5f00 port car profile 2014-11-17 14:58:33 +01:00
Dennis Luxen f9e780ed67 add a wrapper function to work around binding a function with default parameters against LuaBind 2014-11-17 14:58:33 +01:00
Dennis Luxen 18f8ce69cd remove default c'tor in ScriptingEnvironment 2014-11-17 14:58:33 +01:00
Dennis Luxen dce665f14e reformat ExtractorCallbacks 2014-11-17 14:58:33 +01:00
Dennis Luxen 80046b646b actually parse the data that flowing thru osmium 2014-11-17 14:58:33 +01:00
Dennis Luxen 06ddceeac0 reset travel modes on ExtractionWay::clear() 2014-11-17 14:58:33 +01:00
Dennis Luxen b7ea1dfcd0 fix generation of file names 2014-11-17 14:58:33 +01:00
Dennis Luxen 6d9598cd4c link against expat not libxml2, good riddance 2014-11-17 14:58:33 +01:00
Dennis Luxen 60c9701c3f reduce white space noise 2014-11-17 14:58:32 +01:00
Dennis Luxen 2a8644b72c expose libosmium types to LUA 2014-11-17 14:58:32 +01:00
Dennis Luxen b6e469abd1 implement parsing thru libosmium 2014-11-17 14:58:32 +01:00
Dennis Luxen 004c237085 implement restriction type interface in RestrictionMap 2014-11-17 14:58:32 +01:00
Dennis Luxen 398e3bdf82 implement new restriction type interface in PrepareData 2014-11-17 14:58:32 +01:00
Dennis Luxen 958350af82 add InputRestrictionContainer implementation 2014-11-17 14:58:32 +01:00
Dennis Luxen 2d677a8af9 support new restriction type in component analysis 2014-11-17 14:58:32 +01:00
Dennis Luxen 05a79f5b55 implement loader routines for new restriction type 2014-11-17 14:58:31 +01:00
Dennis Luxen ac9566d3d7 add include dir to libosmium 2014-11-17 14:58:31 +01:00
Dennis Luxen 8b7bf94aae implement new Restriction type 2014-11-17 14:58:31 +01:00
Dennis Luxen c4e785e523 remove explicit keyword from WayIDStartAndEndEdge ctor 2014-11-17 14:58:31 +01:00
Dennis Luxen 2f6f883f7f implement ExtractionWay and -Node 2014-11-17 14:58:31 +01:00
Dennis Luxen d071e92a1c implement restriction parsing 2014-11-17 14:58:31 +01:00
Dennis Luxen b18b4072e1 implement restriction parsing 2014-11-17 14:58:31 +01:00
Dennis Luxen 0a2898da17 remove legacy extrators 2014-11-17 14:58:30 +01:00
Dennis Luxen 73fb596973 add libosmium 2014-11-17 14:58:30 +01:00
Dennis Luxen c3f9dc7400 Merge pull request #1271 from alex85k/mingw-full
Support building tools on Windows, more MinGW
2014-11-17 09:18:40 +01:00
alex85k c75ce210ea support building tools on Windows 2014-11-16 21:33:41 +05:00
Dennis Luxen ffca6d8ba5 Merge pull request #1268 from alex85k/develop
fix appveyor packaging - 2
2014-11-14 09:25:01 +01:00
alex85k 1ec35befc8 package .exe, .pdb and lua profiles on AppVeyor 2014-11-14 00:37:07 +05:00
Dennis Luxen 6080eaebbd Merge pull request #1267 from alex85k/develop
fix appveyor packaging
2014-11-13 17:26:48 +01:00
alex85k 41ea339053 fix appveyor packaging 2014-11-13 20:16:40 +03:00
Dennis Luxen 75f9c08445 Merge pull request #1266 from Project-OSRM/revert-1256-patch-1
Revert "fix #1255 assume lift gates are passable"
2014-11-13 14:24:09 +01:00
Dennis Luxen cec3d1488a Revert "fix #1255 assume lift gates are passable" 2014-11-13 14:23:54 +01:00
Dennis Luxen ebec082da2 Merge pull request #1256 from AlanBell/patch-1
fix #1255 assume lift gates are passable
2014-11-13 14:23:42 +01:00
Dennis Luxen bec585e382 update distance table entries only if larger than 0. 2014-11-13 13:45:21 +01:00
Dennis Luxen 2cc8ae875a Merge pull request #1259 from Steffaan/develop
Update NearestPlugin.h to return correct names on mulitple results.
2014-11-11 10:33:49 -08:00
Dennis Luxen db8252e650 Merge branch 'AlanBell-patch-1' into develop 2014-11-11 09:47:53 -08:00
Dennis Luxen e3cb26a1c4 Merge branch 'patch-1' of https://github.com/AlanBell/osrm-backend into AlanBell-patch-1 2014-11-11 09:47:16 -08:00
Stefan 44036ae26d Update NearestPlugin.h to return correct names on mulitple results. 2014-11-11 18:22:32 +01:00
AlanBell 5b5f871a6e Merge pull request #1 from AlanBell/master
test case for lift gate access
2014-11-11 09:26:54 +00:00
AlanBell 9a8f9cae6d test case for lift gate access 2014-11-11 09:16:57 +00:00
AlanBell 8f804581c0 fix #1255 assume lift gates are passable
lift gates are commonly found on industrial parks or businesses, delivery drivers need to route to these, most gates are permissive and open in daytime, this patch won't route through gates where access is specifically no.
2014-11-07 10:29:25 +00:00
Dennis Luxen e26ef17545 reserve delta vector beforehand to avoid realocations. 2014-11-01 17:32:49 -04:00
Dennis Luxen 800bb223b5 remove unused variable 2014-11-01 17:15:20 -04:00
Dennis Luxen 75606f2100 reformatting 2014-10-31 12:15:09 -04:00
Dennis Luxen a28928e6ca use double braces for array initialization as brace elision is implemented/supported differently in GCC and Clang 2014-10-29 10:39:23 -04:00
Dennis Luxen 8700007025 Merge branch 'revert-1240-revert-1217-sketch-upstream' into develop 2014-10-29 10:18:44 -04:00
Patrick Niklaus 520f7fa2de Add UnitTest for DP
Conflicts:
	CMakeLists.txt
2014-10-29 00:40:34 +01:00
Patrick Niklaus 096208a154 Move DP thresholds back to header, since they are needed for testing
Conflicts:
	Algorithms/DouglasPeucker.cpp
2014-10-29 00:38:52 +01:00
Patrick Niklaus 27caab69ec Fix broken DP 2014-10-29 00:37:45 +01:00
Patrick Niklaus 3fe2b587cb Revert "Revert "Bring general sketch commits upstream"" 2014-10-29 00:33:43 +01:00
Dennis Luxen c791188811 separate logic between polyline compression algorithm and JSON formatting.
fixes and closes #1245
2014-10-28 17:31:51 -04:00
Dennis Luxen b227c90c18 remove redundant local variable 2014-10-28 11:11:06 -04:00
Dennis Luxen 8a5538356b remove redundant local variable 2014-10-28 10:39:29 -04:00
Dennis Luxen b257c881b5 explicit casts help mitigate MSVC warnery 2014-10-28 10:36:09 -04:00
Dennis Luxen 0f5dffb1c3 add some specific casts to avoid MSVC warnery 2014-10-28 10:36:02 -04:00
Dennis Luxen d2bd238274 Merge pull request #1244 from Project-OSRM/run_unittests_on_travis
Run unittests on travis
2014-10-28 10:35:22 -04:00
Dennis Luxen fed700440d pick different random seed to avoid edge case 2014-10-28 09:49:55 -04:00
Dennis Luxen 32a9d42412 run datastructure unit tests on travis 2014-10-28 09:14:43 -04:00
Dennis Luxen efc938d870 fix building of tests/benchmark 2014-10-28 09:11:14 -04:00
Dennis Luxen 369f669227 break out PhantomNode.h into a header/impl combo, rename to new naming scheme. 2014-10-27 17:56:06 -04:00
Dennis Luxen 1c56671f01 reformat to break overly long lines 2014-10-27 17:34:50 -04:00
Dennis Luxen 4dbc1e0e96 reformat to fix OCLint long line warning 2014-10-27 13:20:33 -04:00
Dennis Luxen 94288843f1 make entire_length variable a private member that cannot be set from the outside and only accessed thru a const getter. 2014-10-27 12:21:29 -04:00
Dennis Luxen b12decc865 Merge pull request #1240 from Project-OSRM/revert-1217-sketch-upstream
Revert "Bring general sketch commits upstream"
2014-10-27 10:08:17 -04:00
Dennis Luxen 0fc944abf3 Revert "Bring general sketch commits upstream" 2014-10-27 10:07:07 -04:00
Dennis Luxen 9f96c98f02 Merge pull request #1217 from TheMarex/sketch-upstream
Bring general sketch commits upstream
2014-10-26 10:19:24 -04:00
Patrick Niklaus 9805b05738 Reorder include and use correct datatypes 2014-10-25 10:14:31 +02:00
Patrick Niklaus 13ed186469 Fix include order in staticrtree 2014-10-25 10:14:31 +02:00
Patrick Niklaus 00a43221ac Use numeric_limits 2014-10-25 10:14:31 +02:00
Patrick Niklaus edc39112e2 Add wrapper function to DouglasPlucker for backwards-compability 2014-10-23 16:23:54 +02:00
Patrick Niklaus 3b727dea99 Make atan2_lookup inline since it is header-declared 2014-10-23 16:23:54 +02:00
Patrick Niklaus f16b2adec7 Allow empty ranges in DP 2014-10-23 16:23:54 +02:00
Patrick Niklaus 7d425aa76f Use iterators for DouglasPeucker 2014-10-23 16:23:54 +02:00
Patrick Niklaus 651c07c724 Add global timer utils
Global timers can be used to accumulate timings of the same context
in a thread-safe way.
2014-10-23 16:23:54 +02:00
Patrick Niklaus 4d27b75897 Move Rectangle2DInt to own header 2014-10-23 16:23:54 +02:00
Dennis Luxen 6f75d68d07 untangle includes 2014-10-23 16:11:54 +02:00
Dennis Luxen ae269e12bb disable debug code in rtree 2014-10-23 16:11:35 +02:00
Dennis Luxen 3a48929fe6 add benchmark for a single coordinate incremental lookup 2014-10-23 16:11:01 +02:00
Dennis Luxen be970326b6 remove superflous include from library 2014-10-22 19:28:15 +02:00
Dennis Luxen 463511871f Refactor routing plugins:
- remove superflous members from RawRouteData, partially implements #1238
- DescriptorTable moved to BaseDescriptor.h
- added templated assignment c'tor to DescriptorConfig
- refactored check for valid input coordinates, moved to BasePlugin.h
- replaced shared_ptr's to descriptors in ViaRoutePlugin.h with unique_ptr
- implemented FindIncrementalPhantomNode in facades for a single, i.e. first result
- untangled a few includes
2014-10-22 19:02:19 +02:00
Dennis Luxen 002da1e02d add range-based for_each_pair 2014-10-22 18:56:14 +02:00
Dennis Luxen b095aae5ce some minor include untangling 2014-10-21 19:05:56 +02:00
Dennis Luxen 511c21029e To arrive at a later point in time: Revert "remove inline keywords"
This reverts commit 81b0447024.
2014-10-21 18:34:50 +02:00
Dennis Luxen 81b0447024 remove inline keywords 2014-10-21 18:06:58 +02:00
Dennis Luxen d42772a261 bump variant dependency 2014-10-20 16:02:26 +02:00
Dennis Luxen c1136099a9 fix link order to make symbol available in libosrm 2014-10-20 13:26:51 +02:00
Dennis Luxen 06f8a975c0 prevent double compile of dependent compile units 2014-10-20 13:04:44 +02:00
Dennis Luxen c8cd8775f6 Merge branch 'develop' of github.com:Project-OSRM/osrm-backend into develop 2014-10-20 12:54:12 +02:00
Dennis Luxen f9900c91bd Merge branch 'alex85k-mingw-support' into develop 2014-10-20 12:53:09 +02:00
Dennis Luxen accaf6e77e Merge branch 'mingw-support' of https://github.com/alex85k/Project-OSRM into alex85k-mingw-support 2014-10-20 12:52:45 +02:00
Dennis Luxen 8490e297a9 add todo marker 2014-10-20 11:39:23 +02:00
Dennis Luxen 6d3a4b5f6c deactivate inactive includes 2014-10-20 11:25:50 +02:00
Dennis Luxen 1f36206f45 replace boost::get<> call with proper function call to mapbox::variant 2014-10-20 11:25:34 +02:00
Dennis Luxen 952e10936c rename variable 2014-10-20 10:58:45 +02:00
Dennis Luxen 2b3093a687 reformat file according to guidelines 2014-10-20 10:32:57 +02:00
Dennis Luxen d7e25772b0 remove left-over boost::noncopyable and replace by c++11 ctor deletes. 2014-10-20 10:20:58 +02:00
Dennis Luxen c66c9b0353 Merge branch 'alex85k-warning-fix' into develop 2014-10-20 10:13:36 +02:00
alex85k bbde0d75da remove unused variable in Windows code 2014-10-18 19:19:26 +06:00
alex85k c3aec4f627 do not use gcc-ar for MinGW 4.9 2014-10-18 19:13:46 +06:00
alex85k 113852eed4 use math defines on Mingw 2014-10-18 18:47:17 +06:00
Dennis Luxen 6b9b2c1468 Merge pull request #1231 from Project-OSRM/testing/smarter_caching
smarter caching of test files
2014-10-17 15:59:08 +02:00
Emil Tin 2c87b295ff add raketask for clearing test cache files 2014-10-17 15:13:06 +02:00
Emil Tin 93767d68f8 remove debug output 2014-10-17 15:07:56 +02:00
Emil Tin cc3646ca16 fix tests that use {base} expansion 2014-10-17 15:07:56 +02:00
Emil Tin 48333f73d5 rename rather than copy then when possible 2014-10-17 15:07:56 +02:00
Emil Tin 1f4241a63d smarter caching of test files 2014-10-17 15:07:56 +02:00
Dennis Luxen 8eccfaa034 fix a number of implicit conversions 2014-10-17 14:19:33 +02:00
Dennis Luxen 438d1af12a fix implicit type conversios 2014-10-17 13:03:49 +02:00
Dennis Luxen 5be6ef380f replace shared_ptr instances to make intent of single owner more obvious 2014-10-17 12:35:53 +02:00
Dennis Luxen 76419ed2fc remove unneeded member variable 2014-10-17 12:32:18 +02:00
Dennis Luxen 4684921e51 fix implicit casts 2014-10-17 12:31:02 +02:00
Dennis Luxen edd8caa2bf compile Fingerprint only once 2014-10-17 12:30:11 +02:00
Dennis Luxen cb5575ae89 remove compile-time time stamps, rely on git SHA instead, fixes #1229 2014-10-17 10:57:00 +02:00
Dennis Luxen 42e726dec5 reformat according to styleguide 2014-10-16 17:49:10 +02:00
Dennis Luxen e3d33aa171 add const keywords where possible 2014-10-16 17:43:05 +02:00
Dennis Luxen f2ceeb35da fixes issue #1167, odd routing instructions
- the turn angle for compressed edges was not computed from the uncompressed geometry
- for a given turn (a,b,c) the last compressed node for edge (a,b) and the first packed node for (b,c) is returned
- adds a cucumber test to guard against regression
2014-10-16 15:58:58 +02:00
Dennis Luxen 577cf5ddc4 retrieve first and last nodes of a compressed segment 2014-10-16 15:42:33 +02:00
Dennis Luxen 91ced39233 replace shared_ptrs with std::unique_ptr<> in Prepare 2014-10-16 12:10:43 +02:00
Dennis Luxen 4b6cb0b8b8 replace raw ptrs with std::unique_ptr<> in Prepare 2014-10-16 12:10:12 +02:00
Dennis Luxen fb81302382 fix typo: Lunux->Linux 2014-10-16 11:52:16 +02:00
Dennis Luxen dfc81f65ee Merge pull request #889 from Project-OSRM/experimental/cuke_datastore
use osrm-datastore for testing, keep osrm-routed runnning
2014-10-15 15:41:38 +02:00
Dennis Luxen 909db4c861 replace inline with anonynmous namespace to avoid duplicate symbols during linking 2014-10-15 15:15:40 +02:00
Dennis Luxen 4277eed1b6 Revert "remove whitespace from package description"
This reverts commit 6f5703a5fe.
2014-10-15 13:21:42 +02:00
Dennis Luxen 6f5703a5fe remove whitespace from package description 2014-10-15 12:55:40 +02:00
Dennis Luxen f7469f298d add a tail to the oneway circle to avoid edge cases 2014-10-15 11:33:43 +02:00
Dennis Luxen b29d5df7a2 simplify conditional operation, remove useless parantheses 2014-10-15 10:43:58 +02:00
Dennis Luxen 549ba65861 catch a number of uncaught exceptions 2014-10-15 10:23:48 +02:00
Dennis Luxen a9d99cbe54 fix inverted logic 2014-10-14 18:03:24 +02:00
Emil Tin 8438024370 avoid unnessecary process check 2014-10-14 16:05:06 +02:00
Dennis Luxen e6a00ddcfd rethrow exception, refactor default block in fully covered switch statement 2014-10-14 15:59:18 +02:00
Emil Tin 71b967d243 test both datastore and direct data load 2014-10-14 15:35:14 +02:00
Dennis Luxen 1fc1e9590a throw an exception instead of false asserts 2014-10-14 12:52:11 +02:00
Dennis Luxen 0a0099fb41 rename variable, break long lines 2014-10-14 12:49:50 +02:00
Dennis Luxen b890d394ad Add range based CRC32 computation for iterable objects 2014-10-13 18:18:15 +02:00
Dennis Luxen a7fd37ae76 make Descriptor classes final 2014-10-13 18:17:24 +02:00
Dennis Luxen 41fafae21d mark Plugin classes as final 2014-10-13 17:29:53 +02:00
Dennis Luxen a38c007f51 throw instead of assert(false) 2014-10-13 17:20:34 +02:00
Dennis Luxen c7ee402b0e make link tests less brittle, no overlapping paths 2014-10-13 14:56:17 +02:00
Dennis Luxen 1c19796e3e fix container.hpp to properly use std::next and std::end 2014-10-13 13:54:40 +02:00
Emil Tin 76fb0cb965 get process handling up to date 2014-10-13 11:19:49 +02:00
Dennis Luxen 23c79f5cc9 reformat StaticRTreeBench.cpp 2014-10-13 11:15:22 +02:00
Emil Tin 14eac50261 remove datastore test 2014-10-13 11:10:40 +02:00
Emil Tin cf3eae1c91 disable failing test 2014-10-13 10:58:03 +02:00
Emil Tin db06cdb4ce adjust datastore testing 2014-10-13 10:58:03 +02:00
Emil Tin 7ba8e51fa9 use osrm-database during testing 2014-10-13 10:58:03 +02:00
Dennis Luxen bc6466cc36 fix test to inlcude renamed headers 2014-10-13 09:45:07 +02:00
Dennis Luxen 4fbefaef9a catch an uncaught exception and give git revision in springclean tool 2014-10-13 09:42:47 +02:00
Dennis Luxen be11d3325d add mutex include 2014-10-10 19:38:59 +02:00
Dennis Luxen 274140d309 refactor SimpleLogger into simple_logger compile unit 2014-10-10 19:32:49 +02:00
Dennis Luxen ed960ccc8d refactor angle computation into class/compile unit 2014-10-10 18:47:28 +02:00
Dennis Luxen f2b72113c1 refactor ContainerUtil into container.hpp 2014-10-10 18:24:13 +02:00
Dennis Luxen 67a8d30e87 renamed file 2014-10-10 18:19:10 +02:00
Dennis Luxen dafd0e5db7 rewrite NumericUtils into floating_point.hpp 2014-10-10 18:18:56 +02:00
Dennis Luxen d6d10cbf06 reformat Coordinate class 2014-10-10 18:00:09 +02:00
Dennis Luxen 3d3ba86be4 Merge pull request #1212 from Project-OSRM/fix_997
implements and fixes #997: support base path for c'tor
2014-10-10 17:17:41 +02:00
Dennis Luxen 52ed8a7ed0 move springclean functionality in its own tools, remove from datastore 2014-10-10 16:55:24 +02:00
Dennis Luxen 9449c99e25 enable partitioning on LTO, good riddance GCC 4.7 2014-10-10 10:46:43 +02:00
Dennis Luxen 4c0846734e rework the population and checking of base paths 2014-10-10 10:41:06 +02:00
Dennis Luxen 4c64f5fe62 remove shared memory indicator member, use unique_ptr for barriers 2014-10-10 10:41:06 +02:00
Dennis Luxen 9455ea0547 fix initialization of use_shared_memory 2014-10-10 10:41:06 +02:00
Dennis Luxen c3b54a63c3 remove ServerPaths member from OSRM_impl. pass it by value to c'tor 2014-10-10 10:41:06 +02:00
Dennis Luxen b9e1d3116c implements and fixes #997
- ServerPaths object can be populated by passing base path to OSRM
- reduces code/functionality duplication in node-OSRM
2014-10-10 10:41:05 +02:00
Dennis Luxen 5bb7e62a7c fix test on 'some' Intel FPU 2014-10-10 10:36:24 +02:00
Dennis Luxen a443f3a0bb add barrier checkpoint to the white list of passable tags 2014-10-10 10:34:34 +02:00
Dennis Luxen 440244eed8 use double precision fp math for mercartor projection and point-line projections (for now), fixes #1191 2014-10-09 18:58:58 +02:00
Dennis Luxen 2b9e25300f disable checking for empty data sets to make tests pass in debug mode, #889 2014-10-09 17:27:41 +02:00
Dennis Luxen de264dbf94 untangle includes 2014-10-09 14:08:12 +02:00
Dennis Luxen 848b773e24 fix reloading of RTree from shared memory, potentially fixes a number of issue from #889 2014-10-08 19:20:15 +02:00
Dennis Luxen d92f022041 remove implicit inline keyword from header files 2014-10-08 14:47:51 +02:00
Dennis Luxen 57fab61789 move casts from/to string into static class 2014-10-08 14:47:22 +02:00
Dennis Luxen ec8f977ebe reformat StringUtil.h 2014-10-08 12:48:20 +02:00
Dennis Luxen 8dc85e7641 use C++11 type traits to reduce code size in integral->string conversion 2014-10-08 12:40:56 +02:00
Dennis Luxen 4e00ebcd74 Merge pull request #1211 from Project-OSRM/fix_1173
Fix and close #1173
2014-10-08 11:44:48 +02:00
Dennis Luxen 335e719b5d pick compressed edge-weights in correct order 2014-10-08 11:01:58 +02:00
Dennis Luxen 415f8ef2d8 add test-case for bug 2014-10-08 11:01:33 +02:00
Dennis Luxen 17615d1d4a Merge pull request #1209 from Project-OSRM/test/links
test link speeds
2014-10-07 18:08:23 +02:00
Emil Tin 5072252c72 test link speeds 2014-10-07 17:05:39 +02:00
Dennis Luxen 46e93770c9 Merge pull request #1208 from Project-OSRM/feature/surfaces
surface, tracktype, smoothness tags in car profile, closes #955, #1208, #389.
2014-10-07 15:11:55 +02:00
Emil Tin fe43734811 use nil for unlimited surface speeds 2014-10-07 13:50:53 +02:00
Emil Tin 0df81c49d5 surface, tracktype, smoothness tags in car profile 2014-10-07 10:43:47 +02:00
Dennis Luxen 5653516b32 traverse *_link roads at a significantly lower speed than the main link, fixes #1174 2014-10-06 13:42:30 +02:00
Dennis Luxen 22da5be08e Merge branch 'frodrigo-develop' into develop 2014-10-06 09:43:11 +02:00
Dennis Luxen 862656aecc Merge branch 'develop' of https://github.com/frodrigo/osrm-backend into frodrigo-develop 2014-10-06 09:42:55 +02:00
Frédéric Rodrigo ec119a6d52 Add test for maxspeed like 'countrycode:zone type' for car profile 2014-10-04 21:17:18 +02:00
Frédéric Rodrigo 6b98b5f4c7 Parse maxspeed value like FR:urban on car profile 2014-10-04 14:12:14 +02:00
Dennis Luxen 5effe95f2c reformat JSONContainer.h 2014-10-03 11:13:50 +02:00
Dennis Luxen f22e3fd3ff mark Renderer c'tors in JSONContainer as explicit 2014-10-03 11:02:28 +02:00
Dennis Luxen 0047040af9 encapsulate base64 encoding into class to remove static functions from global namespace 2014-10-03 10:38:37 +02:00
Dennis Luxen 60987e6b9b mark c'tors explicit 2014-10-03 10:27:24 +02:00
Dennis Luxen 27d5e2b219 fix include order 2014-10-03 10:23:21 +02:00
Dennis Luxen 53fd0c3a55 fix initialization of EdgeBasedGraphFactory 2014-10-03 10:21:15 +02:00
Dennis Luxen 63456a6d4f fix position of include guard 2014-10-03 10:19:45 +02:00
Dennis Luxen d4cd3c2f7b remove superflous include 2014-10-03 10:17:02 +02:00
Dennis Luxen dbf7137a1a fix include guard name 2014-10-03 10:15:03 +02:00
Dennis Luxen 785891c315 fix name of include guard 2014-10-03 10:03:44 +02:00
Dennis Luxen b7417ec954 fix name of include guard 2014-10-03 10:02:36 +02:00
Dennis Luxen 61b861f0e5 fix name of include guard 2014-10-03 10:01:24 +02:00
Dennis Luxen 0fea0738bf remove superflous inline keyword 2014-10-03 09:59:04 +02:00
Dennis Luxen 4f25d29815 use nullptr instead of NULL 2014-10-03 09:56:07 +02:00
Dennis Luxen 28302a5040 unique_ptr<T> should be unique_ptr<T[]> when used with array 2014-10-02 19:26:57 +02:00
Dennis Luxen 9cc5ca5c58 fix name of include guard 2014-10-02 19:24:43 +02:00
Dennis Luxen 4c4e60b3c9 fix name of include guard 2014-10-02 19:24:06 +02:00
Dennis Luxen 5689a96602 make c'tors of Descriptors explicit 2014-10-02 19:22:02 +02:00
Dennis Luxen 8b57db467a move c'tor should not take const argument 2014-10-02 19:19:52 +02:00
Dennis Luxen 50339e53e2 rename variable across all ifdef paths 2014-09-30 14:52:16 +02:00
Dennis Luxen bc9f5189a5 use irange based for loop in DouglasPeucker run 2014-09-30 14:42:55 +02:00
Dennis Luxen fee83fee40 rename short variable and reformat, OCLint 2014-09-30 14:30:15 +02:00
Dennis Luxen cd5112ab0e rename short variable, OCLint 2014-09-30 14:28:00 +02:00
Dennis Luxen a43b88f9a2 reformat 2014-09-30 14:22:11 +02:00
Dennis Luxen c20fd5dcaa fix short variable name, OCLint 2014-09-30 14:21:24 +02:00
Dennis Luxen f12e296c09 fix short variable name, OCLint 2014-09-30 14:19:49 +02:00
Dennis Luxen 9c3a572646 link unlocking tool against Threads 2014-09-29 16:59:09 +02:00
Dennis Luxen 6175faa9a4 Merge pull request #1202 from Project-OSRM/fix_1192
Fix and close #1192
2014-09-29 12:27:52 +02:00
Dennis Luxen af02fc6bbe add tests for ferry durations 2014-09-29 11:44:51 +02:00
Dennis Luxen cc0bbc42a2 add duration to backward speed, fixes #1192 2014-09-29 11:37:36 +02:00
Dennis Luxen fd747c7340 propagate Lua include dir when compile-checking Luabind, fixes #1196 2014-09-25 12:58:23 +02:00
Dennis Luxen bd33202972 make routing algorithm classes final 2014-09-24 16:03:52 +02:00
Dennis Luxen f6f0de0e38 pimpl OSRM lib with std::unique_ptr 2014-09-24 13:17:55 +02:00
Dennis Luxen 881041800b remove superflous include 2014-09-23 09:41:28 +02:00
Dennis Luxen 11f3ac16f6 add some formatting 2014-09-23 09:41:10 +02:00
Dennis Luxen 969bf95230 Merge pull request #1194 from Project-OSRM/better_luabind_check
better checking for luabind compilation, fixes some OSX woes
2014-09-19 17:08:39 +02:00
Dennis Luxen abc6b4180c better checking for luabind compilation, fixes some OSX woes 2014-09-19 16:33:24 +02:00
Dennis Luxen f74d762a92 Merge branch 'alex85k-luabind-check' into develop 2014-09-19 09:57:56 +02:00
Dennis Luxen f00892ed66 Merge branch 'luabind-check' of https://github.com/alex85k/Project-OSRM into alex85k-luabind-check 2014-09-19 09:57:43 +02:00
alex85k f14c6e6845 Auto-detect Lua compatible with installed Luabind 2014-09-18 23:34:51 +06:00
Dennis Luxen b1bbf2ef84 add relational operators 2014-09-18 11:10:23 +02:00
Dennis Luxen 201062cade make width of computation depend on base type, i.e. if its 64bit then use 64bit math 2014-09-18 10:19:40 +02:00
Dennis Luxen 8cb9198bcf allow a 64bit base type 2014-09-18 09:43:11 +02:00
Dennis Luxen f5e53c0452 make cast operators explicit 2014-09-18 09:42:38 +02:00
Dennis Luxen 41d9c00f70 FixedPointNumber implementation 2014-09-17 19:20:15 +02:00
Dennis Luxen b52f392c92 Merge branch 'srajkovic-stefan-rajkovic-multiple-nearest-points' into develop 2014-09-16 12:33:06 +02:00
Dennis Luxen efaa3b5ab2 Merge branch 'stefan-rajkovic-multiple-nearest-points' of https://github.com/srajkovic/osrm-backend into srajkovic-stefan-rajkovic-multiple-nearest-points
Conflicts:
	DataStructures/RouteParameters.cpp
	Server/APIGrammar.h
2014-09-16 12:32:40 +02:00
Dennis Luxen 36f3d8d6ac Merge pull request #1187 from Project-OSRM/upgrade_protobuf_appveyor
2nd try: upgrade to protobuf 2.5.0 on appveyor
2014-09-15 20:10:57 +02:00
Dennis Luxen e469afa4a9 upgrade to protobuf 2.5.0 on appveyor 2014-09-15 16:21:37 +02:00
Dennis Luxen 9d4b0caa5b fix #1181, uncompressed geometries regressed into array of strings 2014-09-15 14:27:27 +02:00
Dennis Luxen 392c07951e some renaming of member functions to remove ambiguity 2014-09-15 14:23:43 +02:00
Dennis Luxen 8e72c3d81e Merge pull request #1184 from Project-OSRM/cmake_object_library
use object libraries in cmake, bump cmake to 2.8.8+
2014-09-15 13:15:12 +02:00
Dennis Luxen 02428f1e06 add object library to benchmarks 2014-09-15 12:21:13 +02:00
Dennis Luxen b3aa513563 manually install cmake on Travis 2014-09-15 12:14:32 +02:00
Dennis Luxen b8b08cb114 use object libraries in cmake, bump cmake to 2.8.8+ 2014-09-15 11:34:55 +02:00
Dennis Luxen ebbbf1059d Revert "disable LUA 5.2", cf. #1179
This reverts commit 994bd0a910.
2014-09-15 10:24:44 +02:00
Dennis Luxen 37297076f8 Merge pull request #1177 from joto/patch-3
Add object_types to some tags.
2014-09-07 23:15:03 +02:00
Jochen Topf a75b2df6fe Add object_types to some tags.
The newest taginfo understand an `object_types` field to restrict the key/value to certain types of OSM objects.
2014-09-07 20:39:56 +02:00
Dennis Luxen 9ccd0f0282 bump variant version 2014-09-04 16:19:00 +02:00
Dennis Luxen e57d9f2e2e Merge pull request #1157 from Project-OSRM/fix/spelling_of_edge
fix spelling of 'edge'
2014-08-31 11:25:56 +02:00
Emil Tin cf593ba9f9 fix spelling of edge in SharedDataFacade 2014-08-31 09:09:12 +02:00
Dennis Luxen 9eb862a6a4 Merge pull request #1172 from joto/patch-2
Update taginfo.json
2014-08-25 22:07:08 +02:00
Jochen Topf bc84e08da5 Update taginfo.json 2014-08-25 21:55:07 +02:00
Dennis Luxen 24dae2f096 fix URL 2014-08-22 10:43:25 +02:00
Dennis Luxen ab24d6bd96 add JSON file for taginfo analysis 2014-08-22 10:42:43 +02:00
Dennis Luxen 7782c80c4f implement missing loading of TravelMode vector into shared memory 2014-08-22 10:31:47 +02:00
Dennis Luxen 994bd0a910 disable LUA 5.2 2014-08-22 10:31:47 +02:00
Stefan Rajkovic bc9dcba4d4 Removed unnecessary whitespace 2014-08-21 13:24:04 -04:00
Dennis Luxen 85c244ed08 Merge pull request #1166 from Project-OSRM/server_instance_unique_ptr
keep server instance in a shared_ptr
2014-08-21 19:22:37 +02:00
Stefan Rajkovic 495196193c Uses range based check for number of results 2014-08-21 13:19:05 -04:00
Stefan Rajkovic def1e5e1d8 Set restrictions on number of results possible, so 0 < number <= 100. 2014-08-21 13:15:13 -04:00
Dennis Luxen 2727091e47 Merge pull request #1154 from Project-OSRM/feature/travel_mode
travel mode, closes #569, #603 and #606. Great job!
2014-08-21 15:12:02 +02:00
Dennis Luxen d7fbd416ba fix expected values of backward speed in test 2014-08-21 12:18:19 +02:00
Dennis Luxen 6a09ce1613 fix comparison in car speed profile 2014-08-21 12:17:03 +02:00
Emil Tin 774e6346e7 more robust check for parsed ways 2014-08-20 17:10:40 +02:00
Dennis Luxen 05b939760c Revert "use more osrm::irange"
This reverts commit d6c6fbfe03.
2014-08-20 15:47:48 +02:00
Dennis Luxen d6c6fbfe03 use more osrm::irange 2014-08-20 15:34:10 +02:00
Dennis Luxen bb3cbf2dda fix indentation, remove superflous else clause 2014-08-20 14:01:40 +02:00
Dennis Luxen 39d96a45aa fix lambda syntax 2014-08-20 12:14:31 +02:00
Dennis Luxen 6a8c5c8869 fix typo 2014-08-20 11:57:46 +02:00
Dennis Luxen 96318bbe11 switch from unique to shared ptr 2014-08-20 11:57:31 +02:00
Emil Tin 00dd2463fd use lambda to decide turn value 2014-08-20 11:48:47 +02:00
Emil Tin bcd55626ef make accessors const, add comments 2014-08-20 11:37:47 +02:00
Dennis Luxen 8f8cb6a52f keep server instance in a unique_ptr 2014-08-20 11:24:29 +02:00
Emil Tin 2e3d33dfcd remove type from more structs, remove asserts 2014-08-20 11:08:59 +02:00
Emil Tin 1e40cd6f0b remove type assertion 2014-08-20 11:08:59 +02:00
Emil Tin 6e2608b2f2 fix cuke support file 2014-08-20 11:08:59 +02:00
Emil Tin 60d80cf261 code style fixes 2014-08-20 11:08:59 +02:00
Emil Tin 9c23fd4a31 remove accidentially added file 2014-08-20 11:08:59 +02:00
Emil Tin fccb1aad32 remove type attribute 2014-08-20 11:08:59 +02:00
Emil Tin 2780ff31b5 fix bug with mode of 1st instruction 2014-08-20 11:08:59 +02:00
Emil Tin c37c8dc21d add mode test 2014-08-20 11:08:59 +02:00
Emil Tin 6ee7a81f10 update foot profile, add ferry mode 2014-08-20 11:08:58 +02:00
Emil Tin 3d94638d86 update car profile, add ferry mode 2014-08-20 11:08:58 +02:00
Emil Tin 418ff95543 fix initialization order 2014-08-20 11:08:58 +02:00
Emil Tin 221113cbb7 fix assert 2014-08-20 11:08:58 +02:00
Emil Tin 13ea12cf6e fix unit test 2014-08-20 11:08:58 +02:00
Dennis Luxen 1945aae4dc reorder members of SegmentInformation, remove bit fields where possible 2014-08-20 11:08:58 +02:00
Emil Tin 30362cfc0c update lua interface to speed and mode 2014-08-20 11:08:58 +02:00
Emil Tin 6cdc590db5 typedef instead of enum for TravelMode to avoid gcc warnings 2014-08-20 11:08:58 +02:00
Emil Tin eb122a2b8c tidy feature file 2014-08-20 11:08:58 +02:00
Emil Tin feaf8711d3 announce mode changes 2014-08-20 11:08:58 +02:00
Emil Tin 6e364ff0ba rename travel mode None to Inaccessible 2014-08-20 11:08:58 +02:00
Emil Tin 6f6aff7493 remove direction field from ExtractionWay 2014-08-20 11:08:58 +02:00
Emil Tin 207cddd50b use enum for TravelMode 2014-08-20 11:08:58 +02:00
Emil Tin 35988d8f09 fix problem with mode of first instruction 2014-08-20 11:08:42 +02:00
Emil Tin bea63028c7 remove bitfield from SegmentInformation, works around compile err 2014-08-20 11:08:42 +02:00
Emil Tin 0244060806 add a few tests 2014-08-20 11:08:42 +02:00
Emil Tin bfdc296f43 reduce failing test 2014-08-20 11:08:42 +02:00
Emil Tin 8e625a5d07 rename test 2014-08-20 11:08:42 +02:00
Emil Tin 3460bd0ba9 fix problems with mode, 1 failing test left 2014-08-20 11:08:42 +02:00
Emil Tin 4dd0377eb8 fix compilation of tests 2014-08-20 11:08:42 +02:00
Emil Tin 6e1ab9fe3a profile fixes 2014-08-20 11:08:42 +02:00
Emil Tin 7a2d214cc4 reactivate assert of sizeof(NodeBasedEdgeData) 2014-08-20 11:08:42 +02:00
Emil Tin 62495a6de4 remove comment 2014-08-20 11:08:42 +02:00
Emil Tin 8ea88468f3 remove unneeded methods 2014-08-20 11:08:42 +02:00
Emil Tin 687892890b remove spurious comment 2014-08-20 11:08:42 +02:00
Emil Tin ff0dfacc48 fix initialization order to avoid compiler warning 2014-08-20 11:08:42 +02:00
Emil Tin 235a52032a more tests passing 2014-08-20 11:08:42 +02:00
Emil Tin a5ee7e78f6 fixes 2014-08-20 11:08:41 +02:00
Emil Tin 181dbe8493 improve tests for travel mode 2014-08-20 11:08:41 +02:00
Emil Tin dae9c9a7ed use 4 bits for travel mode 2014-08-20 11:08:41 +02:00
Emil Tin 6d6d299ea4 most tests passing 2014-08-20 11:08:41 +02:00
Emil Tin 6fd615b9cd first cut at porting travel mode, some tests fail 2014-08-20 11:08:41 +02:00
Emil Tin d09394ed52 add failing tests for travel mode 2014-08-20 11:08:41 +02:00
Emil Tin 3e6f27d173 rename contra_flow to travel_mode, use unsigned char 2014-08-20 11:08:41 +02:00
Dennis Luxen 82c2ae5441 first round of replacing deprecated typedefs with much nicer using statements 2014-08-19 13:01:38 +02:00
Dennis Luxen 7edf2bb2c2 Merge pull request #1164 from Project-OSRM/appveyor_nuget
Install protoc on both Travis and AppVeyor.
2014-08-19 11:00:23 +02:00
Dennis Luxen c9607b99a3 install protoc thru nuget 2014-08-19 10:11:32 +02:00
Dennis Luxen 2fe1a84dd4 adding protobuf compiler to dependencies, used in branches 2014-08-19 09:56:49 +02:00
Dennis Luxen c63218a889 add final/override keyword where possible to help compiler de-virtualize function calls 2014-08-18 10:19:33 +02:00
Dennis Luxen 5efa9664db Revert "fixing line endings"
This reverts commit dc75469e78.
2014-08-15 18:53:00 +02:00
Dennis Luxen dc75469e78 fixing line endings 2014-08-15 18:47:26 +02:00
Dennis Luxen 9d1e21b5ad Merge pull request #1104 from Project-OSRM/experimental/mapbox_variant
Experimental/mapbox variant
2014-08-14 18:57:53 +02:00
Dennis Luxen 27a367c733 enter build directory before calling tests 2014-08-14 17:29:11 +02:00
Dennis Luxen ffa0ace2a7 build tests by running msbuild on tests project file 2014-08-14 17:29:10 +02:00
Dennis Luxen 074e1e992c build test target explicitly on AppVeyor 2014-08-14 17:29:10 +02:00
Dennis Luxen cdd72c7e56 fast forward variant lib 2014-08-14 17:29:10 +02:00
Dennis Luxen a5e99a95a3 remove constexpr workaround as minimum req. is now Nov 2013 CTP 2014-08-14 17:29:10 +02:00
Dennis Luxen 1de736019d make canary static const instead of constexpr 2014-08-14 17:29:10 +02:00
Dennis Luxen d6b2712070 make msbuild less verbose 2014-08-14 17:29:10 +02:00
Dennis Luxen eda8f4ccec make integer literals static const instead of constexpr 2014-08-14 17:29:10 +02:00
Dennis Luxen 7e3f476407 use 64bit cmake generator 2014-08-14 17:29:10 +02:00
Dennis Luxen e10f36d5f0 use explicit OSRM.sln filename 2014-08-14 17:29:10 +02:00
Dennis Luxen 1bfd9abda3 replace nmake by msbuild 2014-08-14 17:29:10 +02:00
Dennis Luxen 4a1a10fde8 use Nov 2013 CTP to build 2014-08-14 17:29:10 +02:00
Dennis Luxen 4c3cb76ced remove remnants of boost::variant 2014-08-14 17:29:10 +02:00
Dennis Luxen e2794e9f06 initial checkin of mapbox::util::variant 2014-08-14 17:29:10 +02:00
Dennis Luxen 7d2c627ad2 replace boost::variant w/ mapbox::util::variant 2014-08-14 17:29:10 +02:00
Dennis Luxen b310e0f718 apply some reformatting 2014-08-14 17:12:58 +02:00
Dennis Luxen 18915ae2bd make dummy __get_cpuid available on Windows 2014-08-14 17:12:58 +02:00
Dennis Luxen 5dbda8f519 refactoring of IteratorBasedCRC32, fixes #1140 2014-08-14 17:12:58 +02:00
Dennis Luxen 82ce9dfc04 reactivate software-based CRC32 on x64 platforms without SSE4.2 2014-08-14 17:12:57 +02:00
Stefan Rajkovic b9eb936cac Uses current JSON format if number of results requested is 1 2014-08-08 14:06:06 -04:00
Stefan Rajkovic 38117df11b Added ability to get multiple points from /nearest by using num_results argument 2014-08-08 13:58:30 -04:00
403 changed files with 33534 additions and 7195 deletions
+3 -2
View File
@@ -36,8 +36,8 @@ Thumbs.db
# build related files #
#######################
/build/
/Util/FingerPrint.cpp
/Util/GitDescription.cpp
/Util/finger_print.cpp
/Util/git_sha.cpp
/cmake/postinst
# Eclipse related files #
@@ -81,6 +81,7 @@ stxxl.errlog
/osrm-unlock-all
/osrm-cli
/osrm-check-hsgr
/osrm-springclean
/nohup.out
# Sandbox folder #
+8 -3
View File
@@ -7,13 +7,17 @@ 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 protobuf-compiler libprotoc-dev libprotobuf7 libprotobuf-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.8
- sudo apt-get install libboost1.54-all-dev
#luabind
# luabind
- curl https://gist.githubusercontent.com/DennisOSRM/f2eb7b948e6fe1ae319e/raw/install-luabind.sh | sudo bash
#osmosis
# osmosis
- curl -s https://gist.githubusercontent.com/DennisOSRM/803a64a9178ec375069f/raw/ | sudo bash
# cmake
- curl -s https://gist.githubusercontent.com/DennisOSRM/5fad9bee5c7f09fd7fc9/raw/ | sudo bash
# osmpbf library
- curl -s https://gist.githubusercontent.com/DennisOSRM/13b1b4fe38a57ead850e/raw/install_osmpbf.sh | sudo bash
before_script:
- rvm use 1.9.3
- gem install bundler
@@ -24,6 +28,7 @@ before_script:
script:
- make -j 2
- make -j 2 tests
- ./datastructure-tests
- cd ..
- cucumber -p verify
after_script:
-148
View File
@@ -1,148 +0,0 @@
#ifndef __BFS_COMPONENT_EXPLORER_H__
#define __BFS_COMPONENT_EXPLORER_H__
#include "../typedefs.h"
#include "../DataStructures/DynamicGraph.h"
#include "../DataStructures/RestrictionMap.h"
#include <queue>
#include <unordered_set>
// Explores the components of the given graph while respecting turn restrictions
// and barriers.
template <typename GraphT> class BFSComponentExplorer
{
public:
BFSComponentExplorer(const GraphT &dynamicGraph,
const RestrictionMap &restrictions,
const std::unordered_set<NodeID> &barrier_nodes)
: m_graph(dynamicGraph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes)
{
BOOST_ASSERT(m_graph.GetNumberOfNodes() > 0);
}
/*!
* Returns the size of the component that the node belongs to.
*/
inline unsigned int GetComponentSize(NodeID node)
{
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(); }
/*!
* Computes the component sizes.
*/
void run()
{
std::queue<std::pair<NodeID, NodeID>> bfs_queue;
unsigned current_component = 0;
BOOST_ASSERT(m_component_index_list.empty());
BOOST_ASSERT(m_component_index_size.empty());
unsigned num_nodes = m_graph.GetNumberOfNodes();
m_component_index_list.resize(num_nodes, std::numeric_limits<unsigned>::max());
BOOST_ASSERT(num_nodes > 0);
// put unexplorered node with parent pointer into queue
for (NodeID node = 0; node < num_nodes; ++node)
{
if (std::numeric_limits<unsigned>::max() == m_component_index_list[node])
{
unsigned size = ExploreComponent(bfs_queue, node, current_component);
// push size into vector
m_component_index_size.emplace_back(size);
++current_component;
}
}
}
private:
/*!
* Explores the current component that starts at node using BFS.
*/
inline unsigned ExploreComponent(std::queue<std::pair<NodeID, NodeID>> &bfs_queue,
NodeID node,
unsigned current_component)
{
/*
Graphical representation of variables:
u v w
*---------->*---------->*
e2
*/
bfs_queue.emplace(node, node);
// mark node as read
m_component_index_list[node] = current_component;
unsigned current_component_size = 1;
while (!bfs_queue.empty())
{
// fetch element from BFS queue
std::pair<NodeID, NodeID> current_queue_item = bfs_queue.front();
bfs_queue.pop();
const NodeID v = current_queue_item.first; // current node
const NodeID u = current_queue_item.second; // parent
// increment size counter of current component
++current_component_size;
const bool is_barrier_node = (m_barrier_nodes.find(v) != m_barrier_nodes.end());
if (!is_barrier_node)
{
const NodeID to_node_of_only_restriction =
m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v);
for (auto e2 : m_graph.GetAdjacentEdgeRange(v))
{
const NodeID w = m_graph.GetTarget(e2);
if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() &&
w != to_node_of_only_restriction)
{
// At an only_-restriction but not at the right turn
continue;
}
if (u != w)
{
// only add an edge if turn is not a U-turn except
// when it is at the end of a dead-end street.
if (!m_restriction_map.CheckIfTurnIsRestricted(u, v, w))
{
// only add an edge if turn is not prohibited
if (std::numeric_limits<unsigned>::max() == m_component_index_list[w])
{
// insert next (node, parent) only if w has
// not yet been explored
// mark node as read
m_component_index_list[w] = current_component;
bfs_queue.emplace(w, v);
}
}
}
}
}
}
return current_component_size;
}
std::vector<unsigned> m_component_index_list;
std::vector<NodeID> m_component_index_size;
const GraphT &m_graph;
const RestrictionMap &m_restriction_map;
const std::unordered_set<NodeID> &m_barrier_nodes;
};
#endif
-99
View File
@@ -1,99 +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 OBJECTTOBASE64_H_
#define OBJECTTOBASE64_H_
#include "../Util/StringUtil.h"
#include <boost/assert.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <algorithm>
#include <string>
#include <vector>
typedef
boost::archive::iterators::base64_from_binary<
boost::archive::iterators::transform_width<const char *, 6, 8>
> base64_t;
typedef
boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<
std::string::const_iterator>, 8, 6
> binary_t;
template<class ObjectT>
static void EncodeObjectToBase64(const ObjectT & object, std::string& encoded) {
const char * char_ptr_to_object = (const char *)&object;
std::vector<unsigned char> 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);
}
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<class ObjectT>
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(...) { }
}
#endif /* OBJECTTOBASE64_H_ */
-459
View File
@@ -1,459 +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 STRONGLYCONNECTEDCOMPONENTS_H_
#define STRONGLYCONNECTEDCOMPONENTS_H_
#include "../typedefs.h"
#include "../DataStructures/DeallocatingVector.h"
#include "../DataStructures/DynamicGraph.h"
#include "../DataStructures/ImportEdge.h"
#include "../DataStructures/QueryNode.h"
#include "../DataStructures/Percent.h"
#include "../DataStructures/Range.h"
#include "../DataStructures/Restriction.h"
#include "../DataStructures/TurnInstructions.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StdHashExtensions.h"
#include "../Util/TimingUtil.h"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <tbb/parallel_sort.h>
#ifdef __APPLE__
#include <gdal.h>
#include <ogrsf_frmts.h>
#else
#include <gdal/gdal.h>
#include <gdal/ogrsf_frmts.h>
#endif
#include <cstdint>
#include <memory>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
class TarjanSCC
{
private:
struct TarjanNode
{
TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {}
unsigned index;
unsigned low_link;
bool on_stack;
};
struct TarjanEdgeData
{
TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
TarjanEdgeData(int distance, unsigned name_id) : distance(distance), name_id(name_id) {}
int distance;
unsigned name_id;
};
struct TarjanStackFrame
{
explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {}
NodeID v;
NodeID parent;
};
typedef DynamicGraph<TarjanEdgeData> TarjanDynamicGraph;
typedef TarjanDynamicGraph::InputEdge TarjanEdge;
typedef std::pair<NodeID, NodeID> RestrictionSource;
typedef std::pair<NodeID, bool> RestrictionTarget;
typedef std::vector<RestrictionTarget> EmanatingRestrictionsVector;
typedef std::unordered_map<RestrictionSource, unsigned> RestrictionMap;
std::vector<NodeInfo> m_coordinate_list;
std::vector<EmanatingRestrictionsVector> m_restriction_bucket_list;
std::shared_ptr<TarjanDynamicGraph> m_node_based_graph;
std::unordered_set<NodeID> barrier_node_list;
std::unordered_set<NodeID> traffic_light_list;
unsigned m_restriction_counter;
RestrictionMap m_restriction_map;
public:
TarjanSCC(int number_of_nodes,
std::vector<NodeBasedEdge> &input_edges,
std::vector<NodeID> &bn,
std::vector<NodeID> &tl,
std::vector<TurnRestriction> &irs,
std::vector<NodeInfo> &nI)
: m_coordinate_list(nI), m_restriction_counter(irs.size())
{
TIMER_START(SCC_LOAD);
for (const TurnRestriction &restriction : irs)
{
std::pair<NodeID, NodeID> restriction_source = {restriction.fromNode,
restriction.viaNode};
unsigned index = 0;
const auto restriction_iterator = m_restriction_map.find(restriction_source);
if (restriction_iterator == m_restriction_map.end())
{
index = m_restriction_bucket_list.size();
m_restriction_bucket_list.resize(index + 1);
m_restriction_map.emplace(restriction_source, index);
}
else
{
index = restriction_iterator->second;
// Map already contains an is_only_*-restriction
if (m_restriction_bucket_list.at(index).begin()->second)
{
continue;
}
else if (restriction.flags.isOnly)
{
// We are going to insert an is_only_*-restriction. There can be only one.
m_restriction_bucket_list.at(index).clear();
}
}
m_restriction_bucket_list.at(index)
.emplace_back(restriction.toNode, restriction.flags.isOnly);
}
barrier_node_list.insert(bn.begin(), bn.end());
traffic_light_list.insert(tl.begin(), tl.end());
DeallocatingVector<TarjanEdge> edge_list;
for (const NodeBasedEdge &input_edge : input_edges)
{
if (input_edge.source == input_edge.target)
{
continue;
}
if (input_edge.forward)
{
edge_list.emplace_back(input_edge.source,
input_edge.target,
(std::max)((int)input_edge.weight, 1),
input_edge.name_id);
}
if (input_edge.backward)
{
edge_list.emplace_back(input_edge.target,
input_edge.source,
(std::max)((int)input_edge.weight, 1),
input_edge.name_id);
}
}
input_edges.clear();
input_edges.shrink_to_fit();
BOOST_ASSERT_MSG(0 == input_edges.size() && 0 == input_edges.capacity(),
"input edge vector not properly deallocated");
tbb::parallel_sort(edge_list.begin(), edge_list.end());
m_node_based_graph = std::make_shared<TarjanDynamicGraph>(number_of_nodes, edge_list);
TIMER_STOP(SCC_LOAD);
SimpleLogger().Write() << "Loading data into SCC took " << TIMER_MSEC(SCC_LOAD)/1000. << "s";
}
~TarjanSCC() { m_node_based_graph.reset(); }
void Run()
{
TIMER_START(SCC_RUN_SETUP);
// remove files from previous run if exist
DeleteFileIfExists("component.dbf");
DeleteFileIfExists("component.shx");
DeleteFileIfExists("component.shp");
Percent p(m_node_based_graph->GetNumberOfNodes());
OGRRegisterAll();
const char *pszDriverName = "ESRI Shapefile";
OGRSFDriver *poDriver =
OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
if (nullptr == poDriver)
{
throw OSRMException("ESRI Shapefile driver not available");
}
OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr);
if (nullptr == poDS)
{
throw OSRMException("Creation of output file failed");
}
OGRSpatialReference *poSRS = new OGRSpatialReference();
poSRS->importFromEPSG(4326);
OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr);
if (nullptr == poLayer)
{
throw OSRMException("Layer creation failed.");
}
TIMER_STOP(SCC_RUN_SETUP);
SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP)/1000. << "s";
TIMER_START(SCC_RUN);
// The following is a hack to distinguish between stuff that happens
// before the recursive call and stuff that happens after
std::stack<TarjanStackFrame> recursion_stack;
// true = stuff before, false = stuff after call
std::stack<NodeID> tarjan_stack;
std::vector<unsigned> components_index(m_node_based_graph->GetNumberOfNodes(),
SPECIAL_NODEID);
std::vector<NodeID> component_size_vector;
std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes());
unsigned component_index = 0, size_of_current_component = 0;
int index = 0;
const NodeID last_node = m_node_based_graph->GetNumberOfNodes();
std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true);
for(const NodeID node : osrm::irange(0u, last_node))
{
if (SPECIAL_NODEID == components_index[node])
{
recursion_stack.emplace(TarjanStackFrame(node, node));
}
while (!recursion_stack.empty())
{
TarjanStackFrame currentFrame = recursion_stack.top();
const NodeID v = currentFrame.v;
recursion_stack.pop();
const bool before_recursion = processing_node_before_recursion[v];
if (before_recursion && tarjan_node_list[v].index != UINT_MAX)
{
continue;
}
if (before_recursion)
{
// Mark frame to handle tail of recursion
recursion_stack.emplace(currentFrame);
processing_node_before_recursion[v] = false;
// Mark essential information for SCC
tarjan_node_list[v].index = index;
tarjan_node_list[v].low_link = index;
tarjan_stack.push(v);
tarjan_node_list[v].on_stack = true;
++index;
// Traverse outgoing edges
for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v))
{
const TarjanDynamicGraph::NodeIterator vprime =
m_node_based_graph->GetTarget(current_edge);
if (SPECIAL_NODEID == tarjan_node_list[vprime].index)
{
recursion_stack.emplace(TarjanStackFrame(vprime, v));
}
else
{
if (tarjan_node_list[vprime].on_stack &&
tarjan_node_list[vprime].index < tarjan_node_list[v].low_link)
{
tarjan_node_list[v].low_link = tarjan_node_list[vprime].index;
}
}
}
}
else
{
processing_node_before_recursion[v] = true;
tarjan_node_list[currentFrame.parent].low_link =
std::min(tarjan_node_list[currentFrame.parent].low_link,
tarjan_node_list[v].low_link);
// after recursion, lets do cycle checking
// Check if we found a cycle. This is the bottom part of the recursion
if (tarjan_node_list[v].low_link == tarjan_node_list[v].index)
{
NodeID vprime;
do
{
vprime = tarjan_stack.top();
tarjan_stack.pop();
tarjan_node_list[vprime].on_stack = false;
components_index[vprime] = component_index;
++size_of_current_component;
} while (v != vprime);
component_size_vector.emplace_back(size_of_current_component);
if (size_of_current_component > 1000)
{
SimpleLogger().Write() << "large component [" << component_index
<< "]=" << size_of_current_component;
}
++component_index;
size_of_current_component = 0;
}
}
}
}
TIMER_STOP(SCC_RUN);
SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN)/1000. << "s";
SimpleLogger().Write() << "identified: " << component_size_vector.size()
<< " many components, marking small components";
TIMER_START(SCC_OUTPUT);
const unsigned size_one_counter = std::count_if(component_size_vector.begin(),
component_size_vector.end(),
[](unsigned value)
{
return 1 == value;
});
SimpleLogger().Write() << "identified " << size_one_counter << " SCCs of size 1";
uint64_t total_network_distance = 0;
p.reinit(m_node_based_graph->GetNumberOfNodes());
// const NodeID last_u_node = m_node_based_graph->GetNumberOfNodes();
for (const NodeID source : osrm::irange(0u, last_node))
{
p.printIncrement();
for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(source))
{
const TarjanDynamicGraph::NodeIterator target =
m_node_based_graph->GetTarget(current_edge);
if (source < target ||
m_node_based_graph->EndEdges(target) ==
m_node_based_graph->FindEdge(target, source))
{
total_network_distance +=
100 * FixedPointCoordinate::ApproximateEuclideanDistance(
m_coordinate_list[source].lat,
m_coordinate_list[source].lon,
m_coordinate_list[target].lat,
m_coordinate_list[target].lon);
BOOST_ASSERT(current_edge != SPECIAL_EDGEID);
BOOST_ASSERT(source != SPECIAL_NODEID);
BOOST_ASSERT(target != SPECIAL_NODEID);
const unsigned size_of_containing_component =
std::min(component_size_vector[components_index[source]],
component_size_vector[components_index[target]]);
// edges that end on bollard nodes may actually be in two distinct components
if (size_of_containing_component < 10)
{
OGRLineString lineString;
lineString.addPoint(m_coordinate_list[source].lon / COORDINATE_PRECISION,
m_coordinate_list[source].lat / COORDINATE_PRECISION);
lineString.addPoint(m_coordinate_list[target].lon / COORDINATE_PRECISION,
m_coordinate_list[target].lat / COORDINATE_PRECISION);
OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
poFeature->SetGeometry(&lineString);
if (OGRERR_NONE != poLayer->CreateFeature(poFeature))
{
throw OSRMException("Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(poFeature);
}
}
}
}
OGRDataSource::DestroyDataSource(poDS);
component_size_vector.clear();
component_size_vector.shrink_to_fit();
BOOST_ASSERT_MSG(0 == component_size_vector.size() && 0 == component_size_vector.capacity(),
"component_size_vector not properly deallocated");
components_index.clear();
components_index.shrink_to_fit();
BOOST_ASSERT_MSG(0 == components_index.size() && 0 == components_index.capacity(),
"components_index not properly deallocated");
TIMER_STOP(SCC_OUTPUT);
SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT)/1000. << "s";
SimpleLogger().Write() << "total network distance: "
<< (uint64_t)total_network_distance / 100 / 1000. << " km";
}
private:
unsigned CheckForEmanatingIsOnlyTurn(const NodeID u, const NodeID v) const
{
std::pair<NodeID, NodeID> restriction_source = {u, v};
const auto restriction_iterator = m_restriction_map.find(restriction_source);
if (restriction_iterator != m_restriction_map.end())
{
const unsigned index = restriction_iterator->second;
for (const RestrictionSource &restriction_target : m_restriction_bucket_list.at(index))
{
if (restriction_target.second)
{
return restriction_target.first;
}
}
}
return SPECIAL_NODEID;
}
bool CheckIfTurnIsRestricted(const NodeID u, const NodeID v, const NodeID w) const
{
// only add an edge if turn is not a U-turn except it is the end of dead-end street.
std::pair<NodeID, NodeID> restriction_source = {u, v};
const auto restriction_iterator = m_restriction_map.find(restriction_source);
if (restriction_iterator != m_restriction_map.end())
{
const unsigned index = restriction_iterator->second;
for (const RestrictionTarget &restriction_target : m_restriction_bucket_list.at(index))
{
if (w == restriction_target.first)
{
return true;
}
}
}
return false;
}
void DeleteFileIfExists(const std::string &file_name) const
{
if (boost::filesystem::exists(file_name))
{
boost::filesystem::remove(file_name);
}
}
};
#endif /* STRONGLYCONNECTEDCOMPONENTS_H_ */
-118
View File
@@ -1,118 +0,0 @@
#include "../DataStructures/OriginalEdgeData.h"
#include "../DataStructures/QueryNode.h"
#include "../DataStructures/SharedMemoryVectorWrapper.h"
#include "../DataStructures/StaticRTree.h"
#include "../Util/BoostFileSystemFix.h"
#include "../DataStructures/EdgeBasedNode.h"
#include <osrm/Coordinate.h>
#include <random>
// 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;
typedef EdgeBasedNode RTreeLeaf;
typedef std::shared_ptr<std::vector<FixedPointCoordinate>> FixedPointCoordinateListPtr;
typedef StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false> BenchStaticRTree;
FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path& nodes_file)
{
boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);
NodeInfo current_node;
unsigned number_of_coordinates = 0;
nodes_input_stream.read((char *)&number_of_coordinates, sizeof(unsigned));
auto coords = std::make_shared<std::vector<FixedPointCoordinate>>(number_of_coordinates);
for (unsigned i = 0; i < number_of_coordinates; ++i)
{
nodes_input_stream.read((char *)&current_node, sizeof(NodeInfo));
coords->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon);
BOOST_ASSERT((std::abs(coords->at(i).lat) >> 30) == 0);
BOOST_ASSERT((std::abs(coords->at(i).lon) >> 30) == 0);
}
nodes_input_stream.close();
return coords;
}
void Benchmark(BenchStaticRTree& rtree, unsigned num_queries)
{
std::mt19937 g(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<FixedPointCoordinate> queries;
for (unsigned i = 0; i < num_queries; i++)
{
queries.emplace_back(
FixedPointCoordinate(lat_udist(g), lon_udist(g))
);
}
const unsigned num_results = 5;
std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results << " phantom nodes" << std::endl;
TIMER_START(query_phantom);
std::vector<PhantomNode> resulting_phantom_node_vector;
for (const auto& q : queries)
{
resulting_phantom_node_vector.clear();
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);
}
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 << "#### LocateClosestEndPointForCoordinate" << std::endl;
TIMER_START(query_endpoint);
FixedPointCoordinate result;
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 << "#### FindPhantomNodeForCoordinate" << std::endl;
TIMER_START(query_phantomnode);
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;
}
int main(int argc, char** argv)
{
if (argc < 4)
{
std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes" << std::endl;
return 1;
}
const char* ramPath = argv[1];
const char* filePath = argv[2];
const char* nodesPath = argv[3];
auto coords = LoadCoordinates(nodesPath);
BenchStaticRTree rtree(ramPath, filePath, coords);
Benchmark(rtree, 10000);
return 0;
}
+85 -77
View File
@@ -1,6 +1,6 @@
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 )
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.")
@@ -31,43 +31,52 @@ OPTION(WITH_TOOLS "Build OSRM tools" OFF)
OPTION(BUILD_TOOLS "Build OSRM tools" OFF)
include_directories(${CMAKE_SOURCE_DIR}/Include/)
include_directories(${CMAKE_SOURCE_DIR}/third_party/)
add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp FingerPrint.cpp.alwaysbuild
add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/Util/finger_print.cpp finger_print.cpp.alwaysbuild
COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_SOURCE_DIR}
-P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/FingerPrint-Config.cmake
DEPENDS
${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp.in
COMMENT "Configuring FingerPrint.cpp"
${CMAKE_SOURCE_DIR}/Util/finger_print.cpp.in
COMMENT "Configuring finger_print.cpp"
VERBATIM)
add_custom_target(FingerPrintConfigure DEPENDS ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp)
add_custom_target(tests DEPENDS datastructure-tests)
add_custom_target(FingerPrintConfigure DEPENDS ${CMAKE_SOURCE_DIR}/Util/finger_print.cpp)
add_custom_target(tests DEPENDS datastructure-tests algorithm-tests)
add_custom_target(benchmarks DEPENDS rtree-bench)
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
${CMAKE_SOURCE_DIR}/Util/git_sha.cpp.in
${CMAKE_SOURCE_DIR}/Util/git_sha.cpp
)
file(GLOB ExtractorGlob Extractor/*.cpp)
file(GLOB ImporterGlob DataStructures/Import*.cpp)
add_library(IMPORT STATIC ${ImporterGlob})
set(ExtractorSources extractor.cpp ${ExtractorGlob})
add_executable(osrm-extract ${ExtractorSources})
file(GLOB ExtractorGlob extractor/*.cpp)
file(GLOB ImporterGlob data_structures/import_edge.cpp data_structures/external_memory_node.cpp)
add_library(IMPORT OBJECT ${ImporterGlob})
add_library(LOGGER OBJECT Util/simple_logger.cpp)
add_library(PHANTOMNODE OBJECT data_structures/phantom_node.cpp)
add_library(EXCEPTION OBJECT Util/osrm_exception.cpp)
file(GLOB PrepareGlob Contractor/*.cpp DataStructures/HilbertValue.cpp DataStructures/RestrictionMap.cpp)
set(ExtractorSources extract.cpp ${ExtractorGlob})
add_executable(osrm-extract ${ExtractorSources} $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:EXCEPTION>)
add_library(RESTRICTION OBJECT data_structures/restriction_map.cpp)
file(GLOB PrepareGlob contractor/*.cpp data_structures/hilbert_value.cpp Util/compute_angle.cpp {RestrictionMapGlob})
set(PrepareSources prepare.cpp ${PrepareGlob})
add_executable(osrm-prepare ${PrepareSources})
add_executable(osrm-prepare ${PrepareSources} $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:RESTRICTION> $<TARGET_OBJECTS:EXCEPTION>)
file(GLOB ServerGlob Server/*.cpp)
file(GLOB DescriptorGlob Descriptors/*.cpp)
file(GLOB DatastructureGlob DataStructures/SearchEngineData.cpp DataStructures/RouteParameters.cpp)
file(GLOB CoordinateGlob DataStructures/Coordinate.cpp)
file(GLOB AlgorithmGlob Algorithms/*.cpp)
file(GLOB DescriptorGlob descriptors/*.cpp)
file(GLOB DatastructureGlob data_structures/search_engine_data.cpp data_structures/route_parameters.cpp Util/bearing.cpp)
list(REMOVE_ITEM DatastructureGlob data_structures/Coordinate.cpp)
file(GLOB CoordinateGlob data_structures/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)
file(GLOB DataStructureTestsGlob UnitTests/data_structures/*.cpp data_structures/hilbert_value.cpp)
file(GLOB AlgorithmTestsGlob UnitTests/Algorithms/*.cpp)
set(
OSRMSources
@@ -78,20 +87,21 @@ 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/finger_print.cpp)
add_library(GITDESCRIPTION OBJECT Util/git_sha.cpp)
add_library(OSRM ${OSRMSources} $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:PHANTOMNODE> $<TARGET_OBJECTS:EXCEPTION>)
add_dependencies(FINGERPRINT FingerPrintConfigure)
add_executable(osrm-routed routed.cpp ${ServerGlob})
add_executable(osrm-datastore datastore.cpp)
add_executable(osrm-routed routed.cpp ${ServerGlob} $<TARGET_OBJECTS:EXCEPTION>)
add_executable(osrm-datastore datastore.cpp $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:EXCEPTION>)
# Unit tests
add_executable(datastructure-tests EXCLUDE_FROM_ALL UnitTests/datastructure_tests.cpp ${DataStructureTestsGlob})
add_executable(datastructure-tests EXCLUDE_FROM_ALL UnitTests/datastructure_tests.cpp ${DataStructureTestsGlob} $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:PHANTOMNODE> $<TARGET_OBJECTS:EXCEPTION>)
add_executable(algorithm-tests EXCLUDE_FROM_ALL UnitTests/algorithm_tests.cpp ${AlgorithmTestsGlob} $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:PHANTOMNODE> $<TARGET_OBJECTS:EXCEPTION>)
# Benchmarks
add_executable(rtree-bench EXCLUDE_FROM_ALL Benchmarks/StaticRTreeBench.cpp)
add_executable(rtree-bench EXCLUDE_FROM_ALL benchmarks/static_rtree.cpp $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:PHANTOMNODE> $<TARGET_OBJECTS:EXCEPTION>)
# Check the release mode
if(NOT CMAKE_BUILD_TYPE MATCHES Debug)
@@ -115,7 +125,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")
@@ -130,12 +140,18 @@ endif()
# Configuring compilers
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
# using Clang
# -Weverything -Wno-c++98-compat -Wno-shadow -Wno-exit-time-destructors
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wunreachable-code -pedantic -fPIC")
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(COLOR_FLAG "-fdiagnostics-color=auto")
CHECK_CXX_COMPILER_FLAG("-fdiagnostics-color=auto" HAS_COLOR_FLAG)
if(NOT HAS_COLOR_FLAG)
set(COLOR_FLAG "")
endif()
# using GCC
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -fPIC ${COLOR_FLAG}")
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)
endif()
@@ -149,20 +165,11 @@ elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
add_definitions(-DNOMINMAX) # avoid min and max macros that can break compilation
add_definitions(-D_USE_MATH_DEFINES) # define M_PI
add_definitions(-D_WIN32_WINNT=0x0501)
add_definitions(-DXML_STATIC)
find_library(ws2_32_LIBRARY_PATH ws2_32)
target_link_libraries(osrm-extract wsock32 ws2_32)
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)
@@ -197,13 +204,14 @@ 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(datastructure-tests ${Boost_LIBRARIES} COORDLIB)
target_link_libraries(rtree-bench ${Boost_LIBRARIES} 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(algorithm-tests ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM)
target_link_libraries(rtree-bench ${Boost_LIBRARIES})
find_package(Threads REQUIRED)
target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT})
@@ -211,6 +219,7 @@ 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(algorithm-tests ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(rtree-bench ${CMAKE_THREAD_LIBS_INIT})
find_package(TBB REQUIRED)
@@ -222,22 +231,13 @@ 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(algorithm-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})
@@ -251,9 +251,9 @@ else()
endif()
include_directories(${LUA_INCLUDE_DIR})
find_package(LibXml2 REQUIRED)
include_directories(${LIBXML2_INCLUDE_DIR})
target_link_libraries(osrm-extract ${LIBXML2_LIBRARIES})
find_package(EXPAT REQUIRED)
include_directories(${EXPAT_INCLUDE_DIRS})
target_link_libraries(osrm-extract ${EXPAT_LIBRARIES})
find_package( STXXL REQUIRED )
include_directories(${STXXL_INCLUDE_DIR})
@@ -261,6 +261,11 @@ target_link_libraries(OSRM ${STXXL_LIBRARY})
target_link_libraries(osrm-extract ${STXXL_LIBRARY})
target_link_libraries(osrm-prepare ${STXXL_LIBRARY})
if(MINGW)
# STXXL needs OpenMP library
target_link_libraries(osrm-extract gomp)
endif()
find_package( OSMPBF REQUIRED )
include_directories(${OSMPBF_INCLUDE_DIR})
target_link_libraries(osrm-extract ${OSMPBF_LIBRARY})
@@ -284,33 +289,36 @@ 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_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:RESTRICTION> $<TARGET_OBJECTS:EXCEPTION>)
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_OBJECTS:EXCEPTION> $<TARGET_OBJECTS:LOGGER>)
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_OBJECTS:EXCEPTION> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:LOGGER>)
target_link_libraries(osrm-io-benchmark ${Boost_LIBRARIES})
add_executable(osrm-unlock-all tools/unlock_all_mutexes.cpp $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:EXCEPTION>)
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} GITDESCRIPTION FINGERPRINT)
add_executable(osrm-check-hsgr tools/check-hsgr.cpp $<TARGET_OBJECTS:EXCEPTION> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:LOGGER>)
target_link_libraries(osrm-check-hsgr ${Boost_LIBRARIES})
add_executable(osrm-springclean tools/springclean.cpp $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:LOGGER> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:EXCEPTION>)
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)
-67
View File
@@ -1,67 +0,0 @@
#ifndef PREPARE_H
#define PREPARE_H
#include "EdgeBasedGraphFactory.h"
#include "../DataStructures/QueryEdge.h"
#include "../DataStructures/StaticGraph.h"
#include "../Util/GraphLoader.h"
#include <boost/filesystem.hpp>
#include <luabind/luabind.hpp>
#include <vector>
/**
\brief class of 'prepare' utility.
*/
class Prepare
{
public:
typedef QueryEdge::EdgeData EdgeData;
typedef DynamicGraph<EdgeData>::InputEdge InputEdge;
typedef StaticGraph<EdgeData>::InputEdge StaticEdge;
explicit Prepare();
Prepare(const Prepare &) = delete;
~Prepare();
int Process(int argc, char *argv[]);
protected:
bool ParseArguments(int argc, char *argv[]);
void CheckRestrictionsFile(FingerPrint &fingerprint_orig);
bool SetupScriptingEnvironment(lua_State *myLuaState,
EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile);
std::size_t BuildEdgeExpandedGraph(lua_State *myLuaState,
NodeID nodeBasedNodeNumber,
std::vector<EdgeBasedNode> &nodeBasedEdgeList,
DeallocatingVector<EdgeBasedEdge> &edgeBasedEdgeList,
EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile);
void WriteNodeMapping();
void BuildRTree(std::vector<EdgeBasedNode> &node_based_edge_list);
private:
std::vector<NodeInfo> internal_to_external_node_map;
std::vector<TurnRestriction> restriction_list;
std::vector<NodeID> barrier_node_list;
std::vector<NodeID> traffic_light_list;
std::vector<ImportEdge> edge_list;
unsigned requested_num_threads;
boost::filesystem::path config_file_path;
boost::filesystem::path input_path;
boost::filesystem::path restrictions_path;
boost::filesystem::path preinfo_path;
boost::filesystem::path profile_path;
std::string node_filename;
std::string edge_out;
std::string info_out;
std::string geometry_filename;
std::string graph_out;
std::string rtree_nodes_path;
std::string rtree_leafs_path;
};
#endif // PREPARE_H
-173
View File
@@ -1,173 +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 PHANTOM_NODES_H
#define PHANTOM_NODES_H
#include <osrm/Coordinate.h>
#include "../Util/SimpleLogger.h"
#include "../typedefs.h"
#include <vector>
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) :
forward_node_id(forward_node_id),
reverse_node_id(reverse_node_id),
name_id(name_id),
forward_weight(forward_weight),
reverse_weight(reverse_weight),
forward_offset(forward_offset),
reverse_offset(reverse_offset),
packed_geometry_id(packed_geometry_id),
location(location),
fwd_segment_position(fwd_segment_position)
{ }
PhantomNode() :
forward_node_id(SPECIAL_NODEID),
reverse_node_id(SPECIAL_NODEID),
name_id(std::numeric_limits<unsigned>::max()),
forward_weight(INVALID_EDGE_WEIGHT),
reverse_weight(INVALID_EDGE_WEIGHT),
forward_offset(0),
reverse_offset(0),
packed_geometry_id(SPECIAL_EDGEID),
fwd_segment_position(0)
{ }
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;
int GetForwardWeightPlusOffset() const
{
if (SPECIAL_NODEID == forward_node_id)
{
return 0;
}
const int result = (forward_offset + forward_weight);
return result;
}
int GetReverseWeightPlusOffset() const
{
if (SPECIAL_NODEID == reverse_node_id)
{
return 0;
}
const int result = (reverse_offset + reverse_weight);
return result;
}
bool isBidirected() const
{
return (forward_node_id != SPECIAL_NODEID) &&
(reverse_node_id != SPECIAL_NODEID);
}
bool IsCompressed() const
{
return (forward_offset != 0) || (reverse_offset != 0);
}
bool isValid(const unsigned numberOfNodes) const
{
return
location.isValid() &&
(
(forward_node_id < numberOfNodes) ||
(reverse_node_id < numberOfNodes)
) &&
(
(forward_weight != INVALID_EDGE_WEIGHT) ||
(reverse_weight != INVALID_EDGE_WEIGHT)
) &&
(name_id != std::numeric_limits<unsigned>::max()
);
}
bool isValid() const
{
return location.isValid() &&
(name_id != std::numeric_limits<unsigned>::max());
}
bool operator==(const PhantomNode & other) const
{
return location == other.location;
}
};
typedef std::vector<std::vector<PhantomNode>> PhantomNodeArray;
struct PhantomNodeLists
{
std::vector<PhantomNode> source_phantom_list;
std::vector<PhantomNode> target_phantom_list;
};
struct PhantomNodes
{
PhantomNode source_phantom;
PhantomNode target_phantom;
};
inline std::ostream& operator<<(std::ostream &out, const PhantomNodes & pn)
{
out << "source_coord: " << pn.source_phantom.location << "\n";
out << "target_coord: " << pn.target_phantom.location << std::endl;
return out;
}
inline std::ostream& operator<<(std::ostream &out, const PhantomNode & pn)
{
out << "node1: " << pn.forward_node_id << ", " <<
"node2: " << pn.reverse_node_id << ", " <<
"name: " << pn.name_id << ", " <<
"fwd-w: " << pn.forward_weight << ", " <<
"rev-w: " << pn.reverse_weight << ", " <<
"fwd-o: " << pn.forward_offset << ", " <<
"rev-o: " << pn.reverse_offset << ", " <<
"geom: " << pn.packed_geometry_id << ", " <<
"pos: " << pn.fwd_segment_position << ", " <<
"loc: " << pn.location;
return out;
}
#endif // PHANTOM_NODES_H
-100
View File
@@ -1,100 +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 GPX_DESCRIPTOR_H
#define GPX_DESCRIPTOR_H
#include "BaseDescriptor.h"
template <class DataFacadeT> class GPXDescriptor : public BaseDescriptor<DataFacadeT>
{
private:
DescriptorConfig config;
FixedPointCoordinate current;
DataFacadeT * facade;
void AddRoutePoint(const FixedPointCoordinate & coordinate, std::vector<char> & output)
{
const std::string route_point_head = "<rtept lat=\"";
const std::string route_point_middle = " lon=\"";
const std::string route_point_tail = "\"></rtept>";
std::string tmp;
FixedPointCoordinate::convertInternalLatLonToString(coordinate.lat, tmp);
output.insert(output.end(), route_point_head.begin(), route_point_head.end());
output.insert(output.end(), tmp.begin(), tmp.end());
output.push_back('\"');
FixedPointCoordinate::convertInternalLatLonToString(coordinate.lon, tmp);
output.insert(output.end(), route_point_middle.begin(), route_point_middle.end());
output.insert(output.end(), tmp.begin(), tmp.end());
output.insert(output.end(), route_point_tail.begin(), route_point_tail.end());
}
public:
GPXDescriptor(DataFacadeT *facade) : facade(facade) {}
void SetConfig(const DescriptorConfig &c) { config = c; }
// TODO: reorder parameters
void Run(const RawRouteData &raw_route, http::Reply &reply)
{
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<gpx creator=\"OSRM Routing Engine\" version=\"1.1\" "
"xmlns=\"http://www.topografix.com/GPX/1/1\" "
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 gpx.xsd"
"\">"
"<metadata><copyright author=\"Project OSRM\"><license>Data (c)"
" OpenStreetMap contributors (ODbL)</license></copyright>"
"</metadata>"
"<rte>");
reply.content.insert(reply.content.end(), header.begin(), header.end());
const bool found_route = (raw_route.shortest_path_length != INVALID_EDGE_WEIGHT) &&
(!raw_route.unpacked_path_segments.front().empty());
if (found_route)
{
AddRoutePoint(raw_route.segment_end_coordinates.front().source_phantom.location, reply.content);
for (const std::vector<PathData> &path_data_vector : raw_route.unpacked_path_segments)
{
for (const PathData &path_data : path_data_vector)
{
const FixedPointCoordinate current_coordinate =
facade->GetCoordinateOfNode(path_data.node);
AddRoutePoint(current_coordinate, reply.content);
}
}
AddRoutePoint(raw_route.segment_end_coordinates.back().target_phantom.location, reply.content);
}
std::string footer("</rte></gpx>");
reply.content.insert(reply.content.end(), footer.begin(), footer.end());
}
};
#endif // GPX_DESCRIPTOR_H
-3
View File
@@ -1,3 +0,0 @@
The javascript based web client is a seperate project available at
https://github.com/DennisSchiefer/Project-OSRM-Web
-140
View File
@@ -1,140 +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.
*/
#include "BaseParser.h"
#include "ExtractionWay.h"
#include "ScriptingEnvironment.h"
#include "../DataStructures/ImportNode.h"
#include "../Util/LuaUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/ref.hpp>
#include <boost/regex.hpp>
BaseParser::BaseParser(ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment)
: extractor_callbacks(extractor_callbacks),
lua_state(scripting_environment.getLuaState()),
scripting_environment(scripting_environment), use_turn_restrictions(true)
{
ReadUseRestrictionsSetting();
ReadRestrictionExceptions();
}
void BaseParser::ReadUseRestrictionsSetting()
{
if (0 != luaL_dostring(lua_state, "return use_turn_restrictions\n"))
{
use_turn_restrictions = false;
}
else if (lua_isboolean(lua_state, -1))
{
use_turn_restrictions = lua_toboolean(lua_state, -1);
}
if (use_turn_restrictions)
{
SimpleLogger().Write() << "Using turn restrictions";
}
else
{
SimpleLogger().Write() << "Ignoring turn restrictions";
}
}
void BaseParser::ReadRestrictionExceptions()
{
if (lua_function_exists(lua_state, "get_exceptions"))
{
// get list of turn restriction exceptions
luabind::call_function<void>(
lua_state, "get_exceptions", boost::ref(restriction_exceptions));
const unsigned exception_count = restriction_exceptions.size();
SimpleLogger().Write() << "Found " << exception_count
<< " exceptions to turn restrictions:";
for (const std::string &str : restriction_exceptions)
{
SimpleLogger().Write() << " " << str;
}
}
else
{
SimpleLogger().Write() << "Found no exceptions to turn restrictions";
}
}
void BaseParser::report_errors(lua_State *lua_state, const int status) const
{
if (0 != status)
{
std::cerr << "-- " << lua_tostring(lua_state, -1) << std::endl;
lua_pop(lua_state, 1); // remove error message
}
}
void BaseParser::ParseNodeInLua(ImportNode &node, lua_State *local_lua_state)
{
luabind::call_function<void>(local_lua_state, "node_function", boost::ref(node));
}
void BaseParser::ParseWayInLua(ExtractionWay &way, lua_State *local_lua_state)
{
luabind::call_function<void>(local_lua_state, "way_function", boost::ref(way));
}
bool BaseParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const
{
// should this restriction be ignored? yes if there's an overlap between:
// a) the list of modes in the except tag of the restriction
// (except_tag_string), eg: except=bus;bicycle
// b) the lua profile defines a hierachy of modes,
// eg: [access, vehicle, bicycle]
if (except_tag_string.empty())
{
return false;
}
// Be warned, this is quadratic work here, but we assume that
// only a few exceptions are actually defined.
std::vector<std::string> exceptions;
boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*"));
for (std::string &current_string : exceptions)
{
const auto string_iterator =
std::find(restriction_exceptions.begin(), restriction_exceptions.end(), current_string);
if (restriction_exceptions.end() != string_iterator)
{
return true;
}
}
return false;
}
-67
View File
@@ -1,67 +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 BASEPARSER_H_
#define BASEPARSER_H_
#include <string>
#include <vector>
struct lua_State;
class ExtractorCallbacks;
class ScriptingEnvironment;
struct ExtractionWay;
struct ImportNode;
class BaseParser
{
public:
BaseParser() = delete;
BaseParser(const BaseParser &) = delete;
BaseParser(ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment);
virtual ~BaseParser() {}
virtual bool ReadHeader() = 0;
virtual bool Parse() = 0;
virtual void ParseNodeInLua(ImportNode &node, lua_State *lua_state);
virtual void ParseWayInLua(ExtractionWay &way, lua_State *lua_state);
virtual void report_errors(lua_State *lua_state, const int status) const;
protected:
virtual void ReadUseRestrictionsSetting();
virtual void ReadRestrictionExceptions();
virtual bool ShouldIgnoreRestriction(const std::string &except_tag_string) const;
ExtractorCallbacks *extractor_callbacks;
lua_State *lua_state;
ScriptingEnvironment &scripting_environment;
std::vector<std::string> restriction_exceptions;
bool use_turn_restrictions;
};
#endif /* BASEPARSER_H_ */
-79
View File
@@ -1,79 +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 EXTRACTION_WAY_H
#define EXTRACTION_WAY_H
#include "../DataStructures/HashTable.h"
#include "../typedefs.h"
#include <string>
#include <vector>
struct ExtractionWay
{
ExtractionWay() { Clear(); }
inline void Clear()
{
id = SPECIAL_NODEID;
nameID = INVALID_NAMEID;
path.clear();
keyVals.Clear();
direction = ExtractionWay::notSure;
speed = -1;
backward_speed = -1;
duration = -1;
type = -1;
access = true;
roundabout = false;
isAccessRestricted = false;
ignoreInGrid = false;
}
enum Directions
{ notSure = 0,
oneway,
bidirectional,
opposite };
unsigned id;
unsigned nameID;
double speed;
double backward_speed;
double duration;
Directions direction;
std::string name;
short type;
bool access;
bool roundabout;
bool isAccessRestricted;
bool ignoreInGrid;
std::vector<NodeID> path;
HashTable<std::string, std::string> keyVals;
};
#endif // EXTRACTION_WAY_H
-302
View File
@@ -1,302 +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.
*/
#include "Extractor.h"
#include "ExtractorCallbacks.h"
#include "ExtractionContainers.h"
#include "PBFParser.h"
#include "ScriptingEnvironment.h"
#include "XMLParser.h"
#include "../Util/GitDescription.h"
#include "../Util/OSRMException.h"
#include "../Util/ProgramOptions.h"
#include "../Util/SimpleLogger.h"
#include "../Util/TimingUtil.h"
#include "../typedefs.h"
#include <boost/program_options.hpp>
#include <tbb/task_scheduler_init.h>
#include <cstdlib>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unordered_map>
Extractor::Extractor() : requested_num_threads(0), file_has_pbf_format(false)
{
}
Extractor::~Extractor() {}
bool Extractor::ParseArguments(int argc, char *argv[])
{
// 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")(
"config,c",
boost::program_options::value<boost::filesystem::path>(&config_file_path)
->default_value("extractor.ini"),
"Path to a configuration file.");
// declare a group of options that will be allowed both on command line and in config file
boost::program_options::options_description config_options("Configuration");
config_options.add_options()("profile,p",
boost::program_options::value<boost::filesystem::path>(
&profile_path)->default_value("profile.lua"),
"Path to LUA routing profile")(
"threads,t",
boost::program_options::value<unsigned int>(&requested_num_threads)
->default_value(tbb::task_scheduler_init::default_num_threads()),
"Number of threads to use");
// hidden options, will be allowed both on command line and in config file, but will not be
// shown to the user
boost::program_options::options_description hidden_options("Hidden options");
hidden_options.add_options()(
"input,i",
boost::program_options::value<boost::filesystem::path>(&input_path),
"Input file in .osm, .osm.bz2 or .osm.pbf format");
// positional option
boost::program_options::positional_options_description positional_options;
positional_options.add("input", 1);
// combine above options for parsing
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic_options).add(config_options).add(hidden_options);
boost::program_options::options_description config_file_options;
config_file_options.add(config_options).add(hidden_options);
boost::program_options::options_description visible_options(
boost::filesystem::basename(argv[0]) + " <input.osm/.osm.bz2/.osm.pbf> [options]");
visible_options.add(generic_options).add(config_options);
// parse command line options
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(positional_options)
.run(),
option_variables);
if (option_variables.count("version"))
{
SimpleLogger().Write() << g_GIT_DESCRIPTION;
return false;
}
if (option_variables.count("help"))
{
SimpleLogger().Write() << visible_options;
return false;
}
boost::program_options::notify(option_variables);
// parse config file
if (boost::filesystem::is_regular_file(config_file_path))
{
SimpleLogger().Write() << "Reading options from: " << config_file_path.string();
std::string ini_file_contents = ReadIniFileAndLowerContents(config_file_path);
std::stringstream config_stream(ini_file_contents);
boost::program_options::store(parse_config_file(config_stream, config_file_options),
option_variables);
boost::program_options::notify(option_variables);
}
if (!option_variables.count("input"))
{
SimpleLogger().Write() << visible_options;
return false;
}
return true;
}
void Extractor::GenerateOutputFilesNames()
{
output_file_name = input_path.string();
restriction_file_name = input_path.string();
std::string::size_type pos = output_file_name.find(".osm.bz2");
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm.pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
else
{
pos = output_file_name.find(".osm.xml");
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".pbf");
if (pos != std::string::npos)
{
file_has_pbf_format = true;
}
}
if (pos == std::string::npos)
{
pos = output_file_name.find(".osm");
if (pos == std::string::npos)
{
output_file_name.append(".osrm");
restriction_file_name.append(".osrm.restrictions");
}
else
{
output_file_name.replace(pos, 5, ".osrm");
restriction_file_name.replace(pos, 5, ".osrm.restrictions");
}
}
else
{
output_file_name.replace(pos, 8, ".osrm");
restriction_file_name.replace(pos, 8, ".osrm.restrictions");
}
}
int Extractor::Run(int argc, char *argv[])
{
try
{
LogPolicy::GetInstance().Unmute();
TIMER_START(extracting);
if (!ParseArguments(argc, argv))
return 0;
if (1 > requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger";
return 1;
}
if (!boost::filesystem::is_regular_file(input_path))
{
SimpleLogger().Write(logWARNING) << "Input file " << input_path.string()
<< " not found!";
return 1;
}
if (!boost::filesystem::is_regular_file(profile_path))
{
SimpleLogger().Write(logWARNING) << "Profile " << profile_path.string()
<< " not found!";
return 1;
}
const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads();
SimpleLogger().Write() << "Input file: " << input_path.filename().string();
SimpleLogger().Write() << "Profile: " << profile_path.filename().string();
SimpleLogger().Write() << "Threads: " << requested_num_threads;
if (recommended_num_threads != requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "The recommended number of threads is "
<< recommended_num_threads
<< "! This setting may have performance side-effects.";
}
tbb::task_scheduler_init init(requested_num_threads);
/*** Setup Scripting Environment ***/
ScriptingEnvironment scripting_environment(profile_path.string().c_str());
GenerateOutputFilesNames();
std::unordered_map<std::string, NodeID> string_map;
ExtractionContainers extraction_containers;
string_map[""] = 0;
auto extractor_callbacks = new ExtractorCallbacks(extraction_containers, string_map);
BaseParser *parser;
if (file_has_pbf_format)
{
parser = new PBFParser(input_path.string().c_str(),
extractor_callbacks,
scripting_environment,
requested_num_threads);
}
else
{
parser = new XMLParser(input_path.string().c_str(),
extractor_callbacks,
scripting_environment);
}
if (!parser->ReadHeader())
{
throw OSRMException("Parser not initialized!");
}
SimpleLogger().Write() << "Parsing in progress..";
TIMER_START(parsing);
parser->Parse();
delete parser;
delete extractor_callbacks;
TIMER_STOP(parsing);
SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds";
if (extraction_containers.all_edges_list.empty())
{
SimpleLogger().Write(logWARNING) << "The input data is empty, exiting.";
return 1;
}
extraction_containers.PrepareData(output_file_name, restriction_file_name);
TIMER_STOP(extracting);
SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s";
SimpleLogger().Write() << "To prepare the data for routing, run: "
<< "./osrm-prepare " << output_file_name << std::endl;
}
catch (boost::program_options::too_many_positional_options_error &)
{
SimpleLogger().Write(logWARNING) << "Only one input file can be specified";
return 1;
}
catch (std::exception &e)
{
SimpleLogger().Write(logWARNING) << e.what();
return 1;
}
return 0;
}
-36
View File
@@ -1,36 +0,0 @@
#ifndef EXTRACTOR_H_
#define EXTRACTOR_H_
#include <boost/filesystem.hpp>
#include <string>
class ExtractorCallbacks;
/** \brief Class of 'extract' utility. */
class Extractor
{
protected:
unsigned requested_num_threads;
boost::filesystem::path config_file_path;
boost::filesystem::path input_path;
boost::filesystem::path profile_path;
std::string output_file_name;
std::string restriction_file_name;
bool file_has_pbf_format;
/** \brief Parses "extractor's" command line arguments */
bool ParseArguments(int argc, char *argv[]);
/** \brief Parses config file, if present in options */
void GenerateOutputFilesNames();
public:
explicit Extractor();
Extractor(const Extractor &) = delete;
virtual ~Extractor();
int Run(int argc, char *argv[]);
};
#endif /* EXTRACTOR_H_ */
-171
View File
@@ -1,171 +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.
*/
#include "ExtractorCallbacks.h"
#include "ExtractionContainers.h"
#include "ExtractionWay.h"
#include "../DataStructures/Restriction.h"
#include "../DataStructures/ImportNode.h"
#include "../Util/SimpleLogger.h"
#include <osrm/Coordinate.h>
#include <limits>
#include <string>
#include <vector>
ExtractorCallbacks::ExtractorCallbacks(ExtractionContainers &extraction_containers,
std::unordered_map<std::string, NodeID> &string_map)
: string_map(string_map), external_memory(extraction_containers)
{
}
/** warning: caller needs to take care of synchronization! */
void ExtractorCallbacks::ProcessNode(const ExternalMemoryNode &n)
{
if (n.lat <= 85 * COORDINATE_PRECISION && n.lat >= -85 * COORDINATE_PRECISION)
{
external_memory.all_nodes_list.push_back(n);
}
}
bool ExtractorCallbacks::ProcessRestriction(const InputRestrictionContainer &restriction)
{
external_memory.restrictions_list.push_back(restriction);
return true;
}
/** warning: caller needs to take care of synchronization! */
void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
{
if ((0 >= parsed_way.speed) && (0 >= parsed_way.duration))
{ // Only true if the way is specified by the speed profile
return;
}
if (parsed_way.path.size() <= 1)
{ // safe-guard against broken data
return;
}
if (std::numeric_limits<unsigned>::max() == parsed_way.id)
{
SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << parsed_way.id
<< " of size " << parsed_way.path.size();
return;
}
if (0 < parsed_way.duration)
{
// 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);
}
if (std::numeric_limits<double>::epsilon() >= std::abs(-1. - parsed_way.speed))
{
SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << parsed_way.id;
return;
}
// Get the unique identifier for the street name
const auto &string_map_iterator = string_map.find(parsed_way.name);
if (string_map.end() == string_map_iterator)
{
parsed_way.nameID = external_memory.name_list.size();
external_memory.name_list.push_back(parsed_way.name);
string_map.insert(std::make_pair(parsed_way.name, parsed_way.nameID));
}
else
{
parsed_way.nameID = string_map_iterator->second;
}
if (ExtractionWay::opposite == parsed_way.direction)
{
std::reverse(parsed_way.path.begin(), parsed_way.path.end());
parsed_way.direction = ExtractionWay::oneway;
}
const bool split_edge =
(parsed_way.backward_speed > 0) && (parsed_way.speed != parsed_way.backward_speed);
for (unsigned n = 0; n < (parsed_way.path.size() - 1); ++n)
{
external_memory.all_edges_list.push_back(InternalExtractorEdge(
parsed_way.path[n],
parsed_way.path[n + 1],
parsed_way.type,
(split_edge ? ExtractionWay::oneway : parsed_way.direction),
parsed_way.speed,
parsed_way.nameID,
parsed_way.roundabout,
parsed_way.ignoreInGrid,
(0 < parsed_way.duration),
parsed_way.isAccessRestricted,
false,
split_edge));
external_memory.used_node_id_list.push_back(parsed_way.path[n]);
}
external_memory.used_node_id_list.push_back(parsed_way.path.back());
// The following information is needed to identify start and end segments of restrictions
external_memory.way_start_end_id_list.push_back(
WayIDStartAndEndEdge(parsed_way.id,
parsed_way.path[0],
parsed_way.path[1],
parsed_way.path[parsed_way.path.size() - 2],
parsed_way.path.back()));
if (split_edge)
{ // Only true if the way should be split
std::reverse(parsed_way.path.begin(), parsed_way.path.end());
for (std::vector<NodeID>::size_type n = 0; n < parsed_way.path.size() - 1; ++n)
{
external_memory.all_edges_list.push_back(
InternalExtractorEdge(parsed_way.path[n],
parsed_way.path[n + 1],
parsed_way.type,
ExtractionWay::oneway,
parsed_way.backward_speed,
parsed_way.nameID,
parsed_way.roundabout,
parsed_way.ignoreInGrid,
(0 < parsed_way.duration),
parsed_way.isAccessRestricted,
(ExtractionWay::oneway == parsed_way.direction),
split_edge));
}
external_memory.way_start_end_id_list.push_back(
WayIDStartAndEndEdge(parsed_way.id,
parsed_way.path[0],
parsed_way.path[1],
parsed_way.path[parsed_way.path.size() - 2],
parsed_way.path.back()));
}
}
-114
View File
@@ -1,114 +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 EXTRACTORSTRUCTS_H_
#define EXTRACTORSTRUCTS_H_
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../typedefs.h"
#include <limits>
#include <string>
struct ExtractorRelation
{
ExtractorRelation() : type(unknown) {}
enum
{ unknown = 0,
ferry,
turnRestriction } type;
HashTable<std::string, std::string> keyVals;
};
struct WayIDStartAndEndEdge
{
unsigned wayID;
NodeID firstStart;
NodeID firstTarget;
NodeID lastStart;
NodeID lastTarget;
WayIDStartAndEndEdge()
: wayID(std::numeric_limits<unsigned>::max()), firstStart(std::numeric_limits<unsigned>::max()), firstTarget(std::numeric_limits<unsigned>::max()), lastStart(std::numeric_limits<unsigned>::max()),
lastTarget(std::numeric_limits<unsigned>::max())
{
}
explicit WayIDStartAndEndEdge(unsigned w, NodeID fs, NodeID ft, NodeID ls, NodeID lt)
: wayID(w), firstStart(fs), firstTarget(ft), lastStart(ls), lastTarget(lt)
{
}
static WayIDStartAndEndEdge min_value()
{
return WayIDStartAndEndEdge((std::numeric_limits<unsigned>::min)(),
(std::numeric_limits<unsigned>::min)(),
(std::numeric_limits<unsigned>::min)(),
(std::numeric_limits<unsigned>::min)(),
(std::numeric_limits<unsigned>::min)());
}
static WayIDStartAndEndEdge max_value()
{
return WayIDStartAndEndEdge((std::numeric_limits<unsigned>::max)(),
(std::numeric_limits<unsigned>::max)(),
(std::numeric_limits<unsigned>::max)(),
(std::numeric_limits<unsigned>::max)(),
(std::numeric_limits<unsigned>::max)());
}
};
struct CmpWayByID
{
typedef WayIDStartAndEndEdge value_type;
bool operator()(const WayIDStartAndEndEdge &a, const WayIDStartAndEndEdge &b) const
{
return a.wayID < b.wayID;
}
value_type max_value() { return WayIDStartAndEndEdge::max_value(); }
value_type min_value() { return WayIDStartAndEndEdge::min_value(); }
};
struct Cmp
{
typedef NodeID value_type;
bool operator()(const NodeID left, const NodeID right) const { return left < right; }
value_type max_value() { return 0xffffffff; }
value_type min_value() { return 0x0; }
};
struct CmpNodeByID
{
typedef ExternalMemoryNode value_type;
bool operator()(const ExternalMemoryNode &left, const ExternalMemoryNode &right) const
{
return left.node_id < right.node_id;
}
value_type max_value() { return ExternalMemoryNode::max_value(); }
value_type min_value() { return ExternalMemoryNode::min_value(); }
};
#endif /* EXTRACTORSTRUCTS_H_ */
-664
View File
@@ -1,664 +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.
*/
#include "PBFParser.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "ScriptingEnvironment.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/Restriction.h"
#include "../Util/MachineInfo.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../typedefs.h"
#include <boost/assert.hpp>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <osrm/Coordinate.h>
#include <zlib.h>
#include <functional>
#include <limits>
#include <thread>
PBFParser::PBFParser(const char *fileName,
ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment,
unsigned num_threads)
: BaseParser(extractor_callbacks, scripting_environment)
{
if (0 == num_threads)
{
num_parser_threads = tbb::task_scheduler_init::default_num_threads();
}
else
{
num_parser_threads = num_threads;
}
GOOGLE_PROTOBUF_VERIFY_VERSION;
// TODO: What is the bottleneck here? Filling the queue or reading the stuff from disk?
// NOTE: With Lua scripting, it is parsing the stuff. I/O is virtually for free.
// Max 2500 items in queue, hardcoded.
thread_data_queue = std::make_shared<ConcurrentQueue<ParserThreadData *>>(2500);
input.open(fileName, std::ios::in | std::ios::binary);
if (!input)
{
throw OSRMException("pbf file not found.");
}
block_count = 0;
group_count = 0;
}
PBFParser::~PBFParser()
{
if (input.is_open())
{
input.close();
}
// Clean up any leftover ThreadData objects in the queue
ParserThreadData *thread_data;
while (thread_data_queue->try_pop(thread_data))
{
delete thread_data;
}
google::protobuf::ShutdownProtobufLibrary();
SimpleLogger().Write(logDEBUG) << "parsed " << block_count << " blocks from pbf with "
<< group_count << " groups";
}
inline bool PBFParser::ReadHeader()
{
ParserThreadData init_data;
/** read Header */
if (!readPBFBlobHeader(input, &init_data))
{
return false;
}
if (readBlob(input, &init_data))
{
if (!init_data.PBFHeaderBlock.ParseFromArray(&(init_data.charBuffer[0]),
static_cast<int>(init_data.charBuffer.size())))
{
std::cerr << "[error] Header not parseable!" << std::endl;
return false;
}
const auto feature_size = init_data.PBFHeaderBlock.required_features_size();
for (int i = 0; i < feature_size; ++i)
{
const std::string &feature = init_data.PBFHeaderBlock.required_features(i);
bool supported = false;
if ("OsmSchema-V0.6" == feature)
{
supported = true;
}
else if ("DenseNodes" == feature)
{
supported = true;
}
if (!supported)
{
std::cerr << "[error] required feature not supported: " << feature.data()
<< std::endl;
return false;
}
}
}
else
{
std::cerr << "[error] blob not loaded!" << std::endl;
}
return true;
}
inline void PBFParser::ReadData()
{
bool keep_running = true;
do
{
ParserThreadData *thread_data = new ParserThreadData();
keep_running = readNextBlock(input, thread_data);
if (keep_running)
{
thread_data_queue->push(thread_data);
}
else
{
// No more data to read, parse stops when nullptr encountered
thread_data_queue->push(nullptr);
delete thread_data;
}
} while (keep_running);
}
inline void PBFParser::ParseData()
{
tbb::task_scheduler_init init(num_parser_threads);
while (true)
{
ParserThreadData *thread_data;
thread_data_queue->wait_and_pop(thread_data);
if (nullptr == thread_data)
{
thread_data_queue->push(nullptr); // Signal end of data for other threads
break;
}
loadBlock(thread_data);
int group_size = thread_data->PBFprimitiveBlock.primitivegroup_size();
for (int i = 0; i < group_size; ++i)
{
thread_data->currentGroupID = i;
loadGroup(thread_data);
if (thread_data->entityTypeIndicator == TypeNode)
{
parseNode(thread_data);
}
if (thread_data->entityTypeIndicator == TypeWay)
{
parseWay(thread_data);
}
if (thread_data->entityTypeIndicator == TypeRelation)
{
parseRelation(thread_data);
}
if (thread_data->entityTypeIndicator == TypeDenseNode)
{
parseDenseNode(thread_data);
}
}
delete thread_data;
thread_data = nullptr;
}
}
inline bool PBFParser::Parse()
{
// Start the read and parse threads
std::thread read_thread(std::bind(&PBFParser::ReadData, this));
// Open several parse threads that are synchronized before call to
std::thread parse_thread(std::bind(&PBFParser::ParseData, this));
// Wait for the threads to finish
read_thread.join();
parse_thread.join();
return true;
}
inline void PBFParser::parseDenseNode(ParserThreadData *thread_data)
{
const OSMPBF::DenseNodes &dense =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID).dense();
int denseTagIndex = 0;
int64_t m_lastDenseID = 0;
int64_t m_lastDenseLatitude = 0;
int64_t m_lastDenseLongitude = 0;
const int number_of_nodes = dense.id_size();
std::vector<ImportNode> extracted_nodes_vector(number_of_nodes);
for (int i = 0; i < number_of_nodes; ++i)
{
m_lastDenseID += dense.id(i);
m_lastDenseLatitude += dense.lat(i);
m_lastDenseLongitude += dense.lon(i);
extracted_nodes_vector[i].node_id = static_cast<NodeID>(m_lastDenseID);
extracted_nodes_vector[i].lat = static_cast<int>(
COORDINATE_PRECISION *
((double)m_lastDenseLatitude * thread_data->PBFprimitiveBlock.granularity() +
thread_data->PBFprimitiveBlock.lat_offset()) /
NANO);
extracted_nodes_vector[i].lon = static_cast<int>(
COORDINATE_PRECISION *
((double)m_lastDenseLongitude * thread_data->PBFprimitiveBlock.granularity() +
thread_data->PBFprimitiveBlock.lon_offset()) /
NANO);
while (denseTagIndex < dense.keys_vals_size())
{
const int tagValue = dense.keys_vals(denseTagIndex);
if (0 == tagValue)
{
++denseTagIndex;
break;
}
const int keyValue = dense.keys_vals(denseTagIndex + 1);
const std::string &key = thread_data->PBFprimitiveBlock.stringtable().s(tagValue);
const std::string &value = thread_data->PBFprimitiveBlock.stringtable().s(keyValue);
extracted_nodes_vector[i].keyVals.Add(std::move(key), std::move(value));
denseTagIndex += 2;
}
}
tbb::parallel_for(tbb::blocked_range<size_t>(0, extracted_nodes_vector.size()),
[this, &extracted_nodes_vector](const tbb::blocked_range<size_t> &range)
{
lua_State *lua_state = this->scripting_environment.getLuaState();
for (size_t i = range.begin(); i != range.end(); ++i)
{
ImportNode &import_node = extracted_nodes_vector[i];
ParseNodeInLua(import_node, lua_state);
}
});
for (const ImportNode &import_node : extracted_nodes_vector)
{
extractor_callbacks->ProcessNode(import_node);
}
}
inline void PBFParser::parseNode(ParserThreadData *)
{
throw OSRMException("Parsing of simple nodes not supported. PBF should use dense nodes");
}
inline void PBFParser::parseRelation(ParserThreadData *thread_data)
{
// TODO: leave early, if relation is not a restriction
// TODO: reuse rawRestriction container
if (!use_turn_restrictions)
{
return;
}
const OSMPBF::PrimitiveGroup &group =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID);
for (int i = 0, relation_size = group.relations_size(); i < relation_size; ++i)
{
std::string except_tag_string;
const OSMPBF::Relation &inputRelation =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID).relations(i);
bool is_restriction = false;
bool is_only_restriction = false;
for (int k = 0, endOfKeys = inputRelation.keys_size(); k < endOfKeys; ++k)
{
const std::string &key =
thread_data->PBFprimitiveBlock.stringtable().s(inputRelation.keys(k));
const std::string &val =
thread_data->PBFprimitiveBlock.stringtable().s(inputRelation.vals(k));
if ("type" == key)
{
if ("restriction" == val)
{
is_restriction = true;
}
else
{
break;
}
}
if (("restriction" == key) && (val.find("only_") == 0))
{
is_only_restriction = true;
}
if ("except" == key)
{
except_tag_string = val;
}
}
if (is_restriction && ShouldIgnoreRestriction(except_tag_string))
{
continue;
}
if (is_restriction)
{
int64_t last_ref = 0;
InputRestrictionContainer current_restriction_container(is_only_restriction);
for (int rolesIndex = 0, last_role = inputRelation.roles_sid_size();
rolesIndex < last_role;
++rolesIndex)
{
const std::string &role = thread_data->PBFprimitiveBlock.stringtable().s(
inputRelation.roles_sid(rolesIndex));
last_ref += inputRelation.memids(rolesIndex);
if (!("from" == role || "to" == role || "via" == role))
{
continue;
}
switch (inputRelation.types(rolesIndex))
{
case 0: // node
if ("from" == role || "to" == role)
{ // Only via should be a node
continue;
}
BOOST_ASSERT("via" == role);
if (std::numeric_limits<unsigned>::max() !=
current_restriction_container.viaNode)
{
current_restriction_container.viaNode =
std::numeric_limits<unsigned>::max();
}
BOOST_ASSERT(std::numeric_limits<unsigned>::max() ==
current_restriction_container.viaNode);
current_restriction_container.restriction.viaNode =
static_cast<NodeID>(last_ref);
break;
case 1: // way
BOOST_ASSERT("from" == role || "to" == role || "via" == role);
if ("from" == role)
{
current_restriction_container.fromWay = static_cast<EdgeID>(last_ref);
}
if ("to" == role)
{
current_restriction_container.toWay = static_cast<EdgeID>(last_ref);
}
if ("via" == role)
{
BOOST_ASSERT(current_restriction_container.restriction.toNode ==
std::numeric_limits<unsigned>::max());
current_restriction_container.viaNode = static_cast<NodeID>(last_ref);
}
break;
case 2: // relation, not used. relations relating to relations are evil.
continue;
BOOST_ASSERT(false);
break;
default: // should not happen
BOOST_ASSERT(false);
break;
}
}
if (!extractor_callbacks->ProcessRestriction(current_restriction_container))
{
std::cerr << "[PBFParser] relation not parsed" << std::endl;
}
}
}
}
inline void PBFParser::parseWay(ParserThreadData *thread_data)
{
const int number_of_ways =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID).ways_size();
std::vector<ExtractionWay> parsed_way_vector(number_of_ways);
for (int i = 0; i < number_of_ways; ++i)
{
const OSMPBF::Way &input_way =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID).ways(i);
parsed_way_vector[i].id = static_cast<EdgeID>(input_way.id());
unsigned node_id_in_path = 0;
const auto number_of_referenced_nodes = input_way.refs_size();
for (auto j = 0; j < number_of_referenced_nodes; ++j)
{
node_id_in_path += static_cast<NodeID>(input_way.refs(j));
parsed_way_vector[i].path.push_back(node_id_in_path);
}
BOOST_ASSERT(input_way.keys_size() == input_way.vals_size());
const auto number_of_keys = input_way.keys_size();
for (auto j = 0; j < number_of_keys; ++j)
{
const std::string &key =
thread_data->PBFprimitiveBlock.stringtable().s(input_way.keys(j));
const std::string &val =
thread_data->PBFprimitiveBlock.stringtable().s(input_way.vals(j));
parsed_way_vector[i].keyVals.Add(std::move(key), std::move(val));
}
}
// TODO: investigate if schedule guided will be handled by tbb automatically
tbb::parallel_for(tbb::blocked_range<size_t>(0, parsed_way_vector.size()),
[this, &parsed_way_vector](const tbb::blocked_range<size_t> &range)
{
lua_State *lua_state = this->scripting_environment.getLuaState();
for (size_t i = range.begin(); i != range.end(); i++)
{
ExtractionWay &extraction_way = parsed_way_vector[i];
if (2 <= extraction_way.path.size())
{
ParseWayInLua(extraction_way, lua_state);
}
}
});
for (ExtractionWay &extraction_way : parsed_way_vector)
{
if (2 <= extraction_way.path.size())
{
extractor_callbacks->ProcessWay(extraction_way);
}
}
}
inline void PBFParser::loadGroup(ParserThreadData *thread_data)
{
#ifndef NDEBUG
++group_count;
#endif
const OSMPBF::PrimitiveGroup &group =
thread_data->PBFprimitiveBlock.primitivegroup(thread_data->currentGroupID);
thread_data->entityTypeIndicator = TypeDummy;
if (0 != group.nodes_size())
{
thread_data->entityTypeIndicator = TypeNode;
}
if (0 != group.ways_size())
{
thread_data->entityTypeIndicator = TypeWay;
}
if (0 != group.relations_size())
{
thread_data->entityTypeIndicator = TypeRelation;
}
if (group.has_dense())
{
thread_data->entityTypeIndicator = TypeDenseNode;
BOOST_ASSERT(0 != group.dense().id_size());
}
BOOST_ASSERT(thread_data->entityTypeIndicator != TypeDummy);
}
inline void PBFParser::loadBlock(ParserThreadData *thread_data)
{
++block_count;
thread_data->currentGroupID = 0;
thread_data->currentEntityID = 0;
}
inline bool PBFParser::readPBFBlobHeader(std::fstream &stream, ParserThreadData *thread_data)
{
int size(0);
stream.read((char *)&size, sizeof(int));
size = SwapEndian(size);
if (stream.eof())
{
return false;
}
if (size > MAX_BLOB_HEADER_SIZE || size < 0)
{
return false;
}
char *data = new char[size];
stream.read(data, size * sizeof(data[0]));
bool dataSuccessfullyParsed = (thread_data->PBFBlobHeader).ParseFromArray(data, size);
delete[] data;
return dataSuccessfullyParsed;
}
inline bool PBFParser::unpackZLIB(ParserThreadData *thread_data)
{
auto raw_size = thread_data->PBFBlob.raw_size();
char *unpacked_data_array = new char[raw_size];
z_stream compressed_data_stream;
compressed_data_stream.next_in = (unsigned char *)thread_data->PBFBlob.zlib_data().data();
compressed_data_stream.avail_in = thread_data->PBFBlob.zlib_data().size();
compressed_data_stream.next_out = (unsigned char *)unpacked_data_array;
compressed_data_stream.avail_out = raw_size;
compressed_data_stream.zalloc = Z_NULL;
compressed_data_stream.zfree = Z_NULL;
compressed_data_stream.opaque = Z_NULL;
int return_code = inflateInit(&compressed_data_stream);
if (return_code != Z_OK)
{
std::cerr << "[error] failed to init zlib stream" << std::endl;
delete[] unpacked_data_array;
return false;
}
return_code = inflate(&compressed_data_stream, Z_FINISH);
if (return_code != Z_STREAM_END)
{
std::cerr << "[error] failed to inflate zlib stream" << std::endl;
std::cerr << "[error] Error type: " << return_code << std::endl;
delete[] unpacked_data_array;
return false;
}
return_code = inflateEnd(&compressed_data_stream);
if (return_code != Z_OK)
{
std::cerr << "[error] failed to deinit zlib stream" << std::endl;
delete[] unpacked_data_array;
return false;
}
thread_data->charBuffer.clear();
thread_data->charBuffer.resize(raw_size);
std::copy(unpacked_data_array, unpacked_data_array + raw_size, thread_data->charBuffer.begin());
delete[] unpacked_data_array;
return true;
}
inline bool PBFParser::unpackLZMA(ParserThreadData *) { return false; }
inline bool PBFParser::readBlob(std::fstream &stream, ParserThreadData *thread_data)
{
if (stream.eof())
{
return false;
}
const int size = thread_data->PBFBlobHeader.datasize();
if (size < 0 || size > MAX_BLOB_SIZE)
{
std::cerr << "[error] invalid Blob size:" << size << std::endl;
return false;
}
char *data = new char[size];
stream.read(data, sizeof(data[0]) * size);
if (!thread_data->PBFBlob.ParseFromArray(data, size))
{
std::cerr << "[error] failed to parse blob" << std::endl;
delete[] data;
return false;
}
if (thread_data->PBFBlob.has_raw())
{
const std::string &data = thread_data->PBFBlob.raw();
thread_data->charBuffer.clear();
thread_data->charBuffer.resize(data.size());
std::copy(data.begin(), data.end(), thread_data->charBuffer.begin());
}
else if (thread_data->PBFBlob.has_zlib_data())
{
if (!unpackZLIB(thread_data))
{
std::cerr << "[error] zlib data encountered that could not be unpacked" << std::endl;
delete[] data;
return false;
}
}
else if (thread_data->PBFBlob.has_lzma_data())
{
if (!unpackLZMA(thread_data))
{
std::cerr << "[error] lzma data encountered that could not be unpacked" << std::endl;
}
delete[] data;
return false;
}
else
{
std::cerr << "[error] Blob contains no data" << std::endl;
delete[] data;
return false;
}
delete[] data;
return true;
}
bool PBFParser::readNextBlock(std::fstream &stream, ParserThreadData *thread_data)
{
if (stream.eof())
{
return false;
}
if (!readPBFBlobHeader(stream, thread_data))
{
return false;
}
if (thread_data->PBFBlobHeader.type() != "OSMData")
{
return false;
}
if (!readBlob(stream, thread_data))
{
return false;
}
if (!thread_data->PBFprimitiveBlock.ParseFromArray(&(thread_data->charBuffer[0]),
thread_data->charBuffer.size()))
{
std::cerr << "failed to parse PrimitiveBlock" << std::endl;
return false;
}
return true;
}
-103
View File
@@ -1,103 +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 PBFPARSER_H_
#define PBFPARSER_H_
#include "BaseParser.h"
#include "../DataStructures/ConcurrentQueue.h"
#include <osmpbf/fileformat.pb.h>
#include <osmpbf/osmformat.pb.h>
#include <fstream>
#include <memory>
class PBFParser : public BaseParser
{
enum EntityType
{ TypeDummy = 0,
TypeNode = 1,
TypeWay = 2,
TypeRelation = 4,
TypeDenseNode = 8 };
struct ParserThreadData
{
int currentGroupID;
int currentEntityID;
EntityType entityTypeIndicator;
OSMPBF::BlobHeader PBFBlobHeader;
OSMPBF::Blob PBFBlob;
OSMPBF::HeaderBlock PBFHeaderBlock;
OSMPBF::PrimitiveBlock PBFprimitiveBlock;
std::vector<char> charBuffer;
};
public:
PBFParser(const char *file_name,
ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment,
unsigned num_parser_threads = 0);
virtual ~PBFParser();
inline bool ReadHeader();
inline bool Parse();
private:
inline void ReadData();
inline void ParseData();
inline void parseDenseNode(ParserThreadData *thread_data);
inline void parseNode(ParserThreadData *thread_data);
inline void parseRelation(ParserThreadData *thread_data);
inline void parseWay(ParserThreadData *thread_data);
inline void loadGroup(ParserThreadData *thread_data);
inline void loadBlock(ParserThreadData *thread_data);
inline bool readPBFBlobHeader(std::fstream &stream, ParserThreadData *thread_data);
inline bool unpackZLIB(ParserThreadData *thread_data);
inline bool unpackLZMA(ParserThreadData *thread_data);
inline bool readBlob(std::fstream &stream, ParserThreadData *thread_data);
inline bool readNextBlock(std::fstream &stream, ParserThreadData *thread_data);
static const int NANO = 1000 * 1000 * 1000;
static const int MAX_BLOB_HEADER_SIZE = 64 * 1024;
static const int MAX_BLOB_SIZE = 32 * 1024 * 1024;
unsigned group_count;
unsigned block_count;
std::fstream input; // the input stream to parse
std::shared_ptr<ConcurrentQueue<ParserThreadData *>> thread_data_queue;
unsigned num_parser_threads;
};
#endif /* PBFPARSER_H_ */
-353
View File
@@ -1,353 +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.
*/
#include "XMLParser.h"
#include "ExtractionWay.h"
#include "ExtractorCallbacks.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
XMLParser::XMLParser(const char *filename,
ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment)
: BaseParser(extractor_callbacks, scripting_environment)
{
inputReader = inputReaderFactory(filename);
}
bool XMLParser::ReadHeader() { return xmlTextReaderRead(inputReader) == 1; }
bool XMLParser::Parse()
{
while (xmlTextReaderRead(inputReader) == 1)
{
const int type = xmlTextReaderNodeType(inputReader);
// 1 is Element
if (type != 1)
{
continue;
}
xmlChar *currentName = xmlTextReaderName(inputReader);
if (currentName == nullptr)
{
continue;
}
if (xmlStrEqual(currentName, (const xmlChar *)"node") == 1)
{
ImportNode current_node = ReadXMLNode();
ParseNodeInLua(current_node, lua_state);
extractor_callbacks->ProcessNode(current_node);
}
if (xmlStrEqual(currentName, (const xmlChar *)"way") == 1)
{
ExtractionWay way = ReadXMLWay();
ParseWayInLua(way, lua_state);
extractor_callbacks->ProcessWay(way);
}
if (use_turn_restrictions && xmlStrEqual(currentName, (const xmlChar *)"relation") == 1)
{
InputRestrictionContainer current_restriction = ReadXMLRestriction();
if ((UINT_MAX != current_restriction.fromWay) &&
!extractor_callbacks->ProcessRestriction(current_restriction))
{
std::cerr << "[XMLParser] restriction not parsed" << std::endl;
}
}
xmlFree(currentName);
}
return true;
}
InputRestrictionContainer XMLParser::ReadXMLRestriction()
{
InputRestrictionContainer restriction;
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return restriction;
}
std::string except_tag_string;
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == nullptr)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"relation") == 1)
{
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *key = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (key != nullptr && value != nullptr)
{
if (xmlStrEqual(key, (const xmlChar *)"restriction") &&
StringStartsWith((const char *)value, "only_"))
{
restriction.restriction.flags.isOnly = true;
}
if (xmlStrEqual(key, (const xmlChar *)"except"))
{
except_tag_string = (const char *)value;
}
}
if (key != nullptr)
{
xmlFree(key);
}
if (value != nullptr)
{
xmlFree(value);
}
}
else if (xmlStrEqual(child_name, (const xmlChar *)"member") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != nullptr)
{
xmlChar *role = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"role");
xmlChar *type = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"type");
if (xmlStrEqual(role, (const xmlChar *)"to") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.toWay = StringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"from") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.fromWay = StringToUint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"via") &&
xmlStrEqual(type, (const xmlChar *)"node"))
{
restriction.restriction.viaNode = StringToUint((const char *)ref);
}
if (nullptr != type)
{
xmlFree(type);
}
if (nullptr != role)
{
xmlFree(role);
}
if (nullptr != ref)
{
xmlFree(ref);
}
}
}
xmlFree(child_name);
}
if (ShouldIgnoreRestriction(except_tag_string))
{
restriction.fromWay = UINT_MAX; // workaround to ignore the restriction
}
return restriction;
}
ExtractionWay XMLParser::ReadXMLWay()
{
ExtractionWay way;
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return way;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == nullptr)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"way") == 1)
{
xmlChar *way_id = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
way.id = StringToUint((char *)way_id);
xmlFree(way_id);
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *key = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (key != nullptr && value != nullptr)
{
way.keyVals.Add(std::string((char *)key), std::string((char *)value));
}
if (key != nullptr)
{
xmlFree(key);
}
if (value != nullptr)
{
xmlFree(value);
}
}
else if (xmlStrEqual(child_name, (const xmlChar *)"nd") == 1)
{
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != nullptr)
{
way.path.push_back(StringToUint((const char *)ref));
xmlFree(ref);
}
}
xmlFree(child_name);
}
return way;
}
ImportNode XMLParser::ReadXMLNode()
{
ImportNode node;
xmlChar *attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lat");
if (attribute != nullptr)
{
node.lat = static_cast<int>(COORDINATE_PRECISION * StringToDouble((const char *)attribute));
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lon");
if (attribute != nullptr)
{
node.lon = static_cast<int>(COORDINATE_PRECISION * StringToDouble((const char *)attribute));
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
if (attribute != nullptr)
{
node.node_id = StringToUint((const char *)attribute);
xmlFree(attribute);
}
if (xmlTextReaderIsEmptyElement(inputReader) == 1)
{
return node;
}
const int depth = xmlTextReaderDepth(inputReader);
while (xmlTextReaderRead(inputReader) == 1)
{
const int child_type = xmlTextReaderNodeType(inputReader);
// 1 = Element, 15 = EndElement
if (child_type != 1 && child_type != 15)
{
continue;
}
const int child_depth = xmlTextReaderDepth(inputReader);
xmlChar *child_name = xmlTextReaderName(inputReader);
if (child_name == nullptr)
{
continue;
}
if (depth == child_depth && child_type == 15 &&
xmlStrEqual(child_name, (const xmlChar *)"node") == 1)
{
xmlFree(child_name);
break;
}
if (child_type != 1)
{
xmlFree(child_name);
continue;
}
if (xmlStrEqual(child_name, (const xmlChar *)"tag") == 1)
{
xmlChar *key = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"k");
xmlChar *value = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"v");
if (key != nullptr && value != nullptr)
{
node.keyVals.Add(std::string((char *)(key)), std::string((char *)(value)));
}
if (key != nullptr)
{
xmlFree(key);
}
if (value != nullptr)
{
xmlFree(value);
}
}
xmlFree(child_name);
}
return node;
}
+14 -3
View File
@@ -30,9 +30,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iosfwd> //for std::ostream
#include <string>
#include <type_traits>
const float COORDINATE_PRECISION = 1000000.f;
namespace
{
constexpr float COORDINATE_PRECISION = 1000000.f;
}
struct FixedPointCoordinate
{
int lat;
@@ -40,9 +43,17 @@ struct FixedPointCoordinate
FixedPointCoordinate();
FixedPointCoordinate(int lat, int lon);
template<class T>
FixedPointCoordinate(const T &coordinate) : lat(coordinate.lat), lon(coordinate.lon)
{
static_assert(std::is_same<decltype(lat), decltype(coordinate.lat)>::value, "coordinate types incompatible");
static_assert(std::is_same<decltype(lon), decltype(coordinate.lon)>::value, "coordinate types incompatible");
}
void Reset();
bool isSet() const;
bool isValid() const;
bool is_valid() const;
bool operator==(const FixedPointCoordinate &other) const;
static double
+1 -1
View File
@@ -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()
{
+3
View File
@@ -40,6 +40,8 @@ struct RouteParameters
RouteParameters();
void setZoomLevel(const short level);
void setNumberOfResults(const short number);
void setAlternateRouteFlag(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;
+4 -2
View File
@@ -30,6 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <osrm/ServerPaths.h>
#include <memory>
class OSRM_impl;
struct RouteParameters;
@@ -41,10 +43,10 @@ class Reply;
class OSRM
{
private:
OSRM_impl *OSRM_pimpl_;
std::unique_ptr<OSRM_impl> 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);
};
+19 -21
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -34,18 +34,19 @@ namespace boost { namespace interprocess { class named_mutex; } }
#include <osrm/RouteParameters.h>
#include <osrm/ServerPaths.h>
#include "../Plugins/BasePlugin.h"
#include "../Plugins/DistanceTablePlugin.h"
#include "../Plugins/HelloWorldPlugin.h"
#include "../Plugins/LocatePlugin.h"
#include "../Plugins/NearestPlugin.h"
#include "../Plugins/TimestampPlugin.h"
#include "../Plugins/ViaRoutePlugin.h"
#include "../plugins/distance_table.hpp"
#include "../plugins/hello_world.hpp"
#include "../plugins/locate.hpp"
#include "../plugins/nearest.hpp"
#include "../plugins/timestamp.hpp"
#include "../plugins/viaroute.hpp"
#include "../Server/DataStructures/BaseDataFacade.h"
#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 <boost/assert.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
@@ -56,16 +57,17 @@ namespace boost { namespace interprocess { class named_mutex; } }
#include <utility>
#include <vector>
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<SharedBarriers>();
query_data_facade = new SharedDataFacade<QueryEdge::EdgeData>();
}
else
{
// populate base path
populate_base_path(server_paths);
query_data_facade = new InternalDataFacade<QueryEdge::EdgeData>(server_paths);
}
@@ -85,10 +87,6 @@ OSRM_impl::~OSRM_impl()
{
delete plugin_pointer.second;
}
if (use_shared_memory)
{
delete barrier;
}
}
void OSRM_impl::RegisterPlugin(BasePlugin *plugin)
@@ -108,7 +106,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<boost::interprocess::named_mutex> pending_lock(
@@ -129,7 +127,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<boost::interprocess::named_mutex> query_lock(
@@ -154,12 +152,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<OSRM_impl>(paths, use_shared_memory))
{
}
OSRM::~OSRM() { delete OSRM_pimpl_; }
OSRM::~OSRM() { OSRM_pimpl_.reset(); }
void OSRM::RunQuery(RouteParameters &route_parameters, http::Reply &reply)
{
+6 -5
View File
@@ -34,8 +34,9 @@ struct RouteParameters;
#include <osrm/ServerPaths.h>
#include "../DataStructures/QueryEdge.h"
#include "../data_structures/query_edge.hpp"
#include <memory>
#include <unordered_map>
#include <string>
@@ -45,10 +46,10 @@ template <class EdgeDataT> class BaseDataFacade;
class OSRM_impl
{
private:
typedef std::unordered_map<std::string, BasePlugin *> PluginMap;
using PluginMap = std::unordered_map<std::string, BasePlugin *>;
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<SharedBarriers> barrier;
// base class pointer to the objects
BaseDataFacade<QueryEdge::EdgeData> *query_data_facade;
};
-173
View File
@@ -1,173 +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 VIA_ROUTE_PLUGIN_H
#define VIA_ROUTE_PLUGIN_H
#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/StringUtil.h"
#include "../Util/TimingUtil.h"
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>
template <class DataFacadeT> class ViaRoutePlugin : public BasePlugin
{
private:
std::unordered_map<std::string, unsigned> descriptor_table;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
public:
explicit ViaRoutePlugin(DataFacadeT *facade) : descriptor_string("viaroute"), facade(facade)
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
descriptor_table.emplace("json", 0);
descriptor_table.emplace("gpx", 1);
// descriptor_table.emplace("geojson", 2);
}
virtual ~ViaRoutePlugin() {}
const std::string GetDescriptor() const { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
{
// 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(); }))
{
reply = http::Reply::StockReply(http::Reply::badRequest);
return;
}
RawRouteData raw_route;
raw_route.check_sum = facade->GetCheckSum();
for (const FixedPointCoordinate &coordinate : route_parameters.coordinates)
{
raw_route.raw_via_node_coordinates.emplace_back(coordinate);
}
std::vector<PhantomNode> phantom_node_vector(raw_route.raw_via_node_coordinates.size());
const bool checksum_OK = (route_parameters.check_sum == raw_route.check_sum);
for (unsigned i = 0; i < raw_route.raw_via_node_coordinates.size(); ++i)
{
if (checksum_OK && i < route_parameters.hints.size() &&
!route_parameters.hints[i].empty())
{
DecodeObjectFromBase64(route_parameters.hints[i], phantom_node_vector[i]);
if (phantom_node_vector[i].isValid(facade->GetNumberOfNodes()))
{
continue;
}
}
facade->FindPhantomNodeForCoordinate(raw_route.raw_via_node_coordinates[i],
phantom_node_vector[i],
route_parameters.zoom_level);
}
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < phantom_node_vector.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = phantom_node_vector[i];
current_phantom_node_pair.target_phantom = phantom_node_vector[i + 1];
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
const bool is_alternate_requested = route_parameters.alternate_route;
const bool is_only_one_segment = (1 == raw_route.segment_end_coordinates.size());
if (is_alternate_requested && is_only_one_segment)
{
search_engine_ptr->alternative_path(raw_route.segment_end_coordinates.front(),
raw_route);
}
else
{
search_engine_ptr->shortest_path(raw_route.segment_end_coordinates, route_parameters.uturns, raw_route);
}
if (INVALID_EDGE_WEIGHT == raw_route.shortest_path_length)
{
SimpleLogger().Write(logDEBUG) << "Error occurred, single path not found";
}
reply.status = http::Reply::ok;
DescriptorConfig descriptor_config;
auto iter = descriptor_table.find(route_parameters.output_format);
unsigned descriptor_type = (iter != descriptor_table.end() ? iter->second : 0);
descriptor_config.zoom_level = route_parameters.zoom_level;
descriptor_config.instructions = route_parameters.print_instructions;
descriptor_config.geometry = route_parameters.geometry;
descriptor_config.encode_geometry = route_parameters.compression;
std::shared_ptr<BaseDescriptor<DataFacadeT>> descriptor;
switch (descriptor_type)
{
// case 0:
// descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>();
// break;
case 1:
descriptor = std::make_shared<GPXDescriptor<DataFacadeT>>(facade);
break;
// case 2:
// descriptor = std::make_shared<GEOJSONDescriptor<DataFacadeT>>();
// break;
default:
descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(facade);
break;
}
descriptor->SetConfig(descriptor_config);
descriptor->Run(raw_route, reply);
}
private:
std::string descriptor_string;
DataFacadeT *facade;
};
#endif // VIA_ROUTE_PLUGIN_H
+1 -1
View File
@@ -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) |
+8 -1
View File
@@ -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,10 @@ 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
+3 -2
View File
@@ -40,7 +40,7 @@ struct APIGrammar : qi::grammar<Iterator>
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<Iterator>
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<Iterator>
qi::rule<Iterator> api_call, query;
qi::rule<Iterator, std::string()> 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;
};
+2 -2
View File
@@ -69,10 +69,10 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t
CompressionType compression_type(noCompression);
boost::tribool result;
boost::tie(result, boost::tuples::ignore) =
request_parser.Parse(request,
RequestParser().Parse(request,
incoming_data_buffer.data(),
incoming_data_buffer.data() + bytes_transferred,
&compression_type);
compression_type);
// the request has been parsed
if (result)
+1 -3
View File
@@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CONNECTION_H
#define CONNECTION_H
#include "RequestParser.h"
// #include "RequestParser.h"
#include "Http/CompressionType.h"
#include "Http/Request.h"
@@ -40,7 +40,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <boost/version.hpp>
#include <memory>
#include <string>
#include <vector>
//workaround for incomplete std::shared_ptr compatibility in old boost versions
@@ -97,7 +96,6 @@ class Connection : public std::enable_shared_from_this<Connection>
RequestHandler &request_handler;
boost::array<char, 8192> incoming_data_buffer;
Request request;
RequestParser request_parser;
Reply reply;
};
+19 -17
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -30,13 +30,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Exposes all data access interfaces to the algorithms via base class ptr
#include "../../DataStructures/EdgeBasedNode.h"
#include "../../DataStructures/ImportNode.h"
#include "../../DataStructures/PhantomNodes.h"
#include "../../DataStructures/Range.h"
#include "../../DataStructures/TurnInstructions.h"
#include "../../Util/OSRMException.h"
#include "../../Util/StringUtil.h"
#include "../../data_structures/edge_based_node.hpp"
#include "../../data_structures/external_memory_node.hpp"
#include "../../data_structures/phantom_node.hpp"
#include "../../data_structures/turn_instructions.hpp"
#include "../../Util/integer_range.hpp"
#include "../../Util/osrm_exception.hpp"
#include "../../Util/string_util.hpp"
#include "../../typedefs.h"
#include <osrm/Coordinate.h>
@@ -62,9 +62,9 @@ template <class EdgeDataT> 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 const EdgeDataT &GetEdgeData( const EdgeID e ) const = 0;
virtual const EdgeDataT &GetEdgeData(const EdgeID e) const = 0;
virtual EdgeID BeginEdges(const NodeID n) const = 0;
@@ -92,18 +92,20 @@ template <class EdgeDataT> 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;
virtual bool FindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node,
const unsigned zoom_level) = 0;
virtual bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
std::vector<PhantomNode> &resulting_phantom_node_vector,
const unsigned number_of_results) = 0;
virtual bool IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
std::vector<PhantomNode> &resulting_phantom_node_vector,
const unsigned zoom_level,
const unsigned number_of_results) = 0;
virtual bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node) = 0;
virtual unsigned GetCheckSum() const = 0;
+71 -62
View File
@@ -32,19 +32,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseDataFacade.h"
#include "../../DataStructures/OriginalEdgeData.h"
#include "../../DataStructures/QueryNode.h"
#include "../../DataStructures/QueryEdge.h"
#include "../../DataStructures/SharedMemoryVectorWrapper.h"
#include "../../DataStructures/StaticGraph.h"
#include "../../DataStructures/StaticRTree.h"
#include "../../DataStructures/RangeTable.h"
#include "../../data_structures/original_edge_data.hpp"
#include "../../data_structures/query_node.hpp"
#include "../../data_structures/query_edge.hpp"
#include "../../data_structures/shared_memory_vector_wrapper.hpp"
#include "../../data_structures/static_graph.hpp"
#include "../../data_structures/static_rtree.hpp"
#include "../../data_structures/range_table.hpp"
#include "../../Util/BoostFileSystemFix.h"
#include "../../Util/GraphLoader.h"
#include "../../Util/ProgramOptions.h"
#include "../../Util/SimpleLogger.h"
#include "../../Util/graph_loader.hpp"
#include "../../Util/simple_logger.hpp"
#include <osrm/Coordinate.h>
#include <osrm/ServerPaths.h>
template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<EdgeDataT>
{
@@ -66,13 +66,14 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
ShM<NodeID, false>::vector m_via_node_list;
ShM<unsigned, false>::vector m_name_ID_list;
ShM<TurnInstruction, false>::vector m_turn_instruction_list;
ShM<TravelMode, false>::vector m_travel_mode_list;
ShM<char, false>::vector m_names_char_list;
ShM<bool, false>::vector m_egde_is_compressed;
ShM<bool, false>::vector m_edge_is_compressed;
ShM<unsigned, false>::vector m_geometry_indices;
ShM<unsigned, false>::vector m_geometry_list;
boost::thread_specific_ptr<StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false>>
m_static_rtree;
boost::thread_specific_ptr<
StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false>> m_static_rtree;
boost::filesystem::path ram_index_path;
boost::filesystem::path file_index_path;
RangeTable<16, false> m_name_table;
@@ -125,14 +126,14 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
{
boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);
NodeInfo current_node;
QueryNode current_node;
unsigned number_of_coordinates = 0;
nodes_input_stream.read((char *)&number_of_coordinates, sizeof(unsigned));
m_coordinate_list =
std::make_shared<std::vector<FixedPointCoordinate>>(number_of_coordinates);
for (unsigned i = 0; i < number_of_coordinates; ++i)
{
nodes_input_stream.read((char *)&current_node, sizeof(NodeInfo));
nodes_input_stream.read((char *)&current_node, sizeof(QueryNode));
m_coordinate_list->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon);
BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lat) >> 30) == 0);
BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lon) >> 30) == 0);
@@ -145,7 +146,8 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
m_via_node_list.resize(number_of_edges);
m_name_ID_list.resize(number_of_edges);
m_turn_instruction_list.resize(number_of_edges);
m_egde_is_compressed.resize(number_of_edges);
m_travel_mode_list.resize(number_of_edges);
m_edge_is_compressed.resize(number_of_edges);
unsigned compressed = 0;
@@ -156,8 +158,9 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
m_via_node_list[i] = current_edge_data.via_node;
m_name_ID_list[i] = current_edge_data.name_id;
m_turn_instruction_list[i] = current_edge_data.turn_instruction;
m_egde_is_compressed[i] = current_edge_data.compressed_geometry;
if (m_egde_is_compressed[i])
m_travel_mode_list[i] = current_edge_data.travel_mode;
m_edge_is_compressed[i] = current_edge_data.compressed_geometry;
if (m_edge_is_compressed[i])
{
++compressed;
}
@@ -199,8 +202,7 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
BOOST_ASSERT_MSG(!m_coordinate_list->empty(), "coordinates must be loaded before r-tree");
m_static_rtree.reset(
new StaticRTree<RTreeLeaf>(ram_index_path, file_index_path, m_coordinate_list)
);
new StaticRTree<RTreeLeaf>(ram_index_path, file_index_path, m_coordinate_list));
}
void LoadStreetNames(const boost::filesystem::path &names_file)
@@ -233,31 +235,31 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
// generate paths of data files
if (server_paths.find("hsgrdata") == server_paths.end())
{
throw OSRMException("no hsgr file given in ini file");
throw osrm::exception("no hsgr file given in ini file");
}
if (server_paths.find("ramindex") == server_paths.end())
{
throw OSRMException("no ram index file given in ini file");
throw osrm::exception("no ram index file given in ini file");
}
if (server_paths.find("fileindex") == server_paths.end())
{
throw OSRMException("no leaf index file given in ini file");
throw osrm::exception("no leaf index file given in ini file");
}
if (server_paths.find("geometries") == server_paths.end())
{
throw OSRMException("no geometries file given in ini file");
throw osrm::exception("no geometries file given in ini file");
}
if (server_paths.find("nodesdata") == server_paths.end())
{
throw OSRMException("no nodes file given in ini file");
throw osrm::exception("no nodes file given in ini file");
}
if (server_paths.find("edgesdata") == server_paths.end())
{
throw OSRMException("no edges file given in ini file");
throw osrm::exception("no edges file given in ini file");
}
if (server_paths.find("namesdata") == server_paths.end())
{
throw OSRMException("no names file given in ini file");
throw osrm::exception("no names file given in ini file");
}
ServerPaths::const_iterator paths_iterator = server_paths.find("hsgrdata");
@@ -289,7 +291,7 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
SimpleLogger().Write() << "loading graph data";
AssertPathExists(hsgr_path);
LoadGraph(hsgr_path);
SimpleLogger().Write() << "loading egde information";
SimpleLogger().Write() << "loading edge information";
AssertPathExists(nodes_data_path);
AssertPathExists(edges_data_path);
LoadNodeAndEdgeInformation(nodes_data_path, edges_data_path);
@@ -307,59 +309,64 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
}
// search graph access
unsigned GetNumberOfNodes() const { return m_query_graph->GetNumberOfNodes(); }
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())
{
@@ -370,24 +377,26 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
input_coordinate, result, zoom_level);
}
bool FindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node,
const unsigned zoom_level)
bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node) final
{
if (!m_static_rtree.get())
std::vector<PhantomNode> resulting_phantom_node_vector;
auto result = IncrementalFindPhantomNodeForCoordinate(input_coordinate,
resulting_phantom_node_vector,
1);
if (result)
{
LoadRTree();
BOOST_ASSERT(!resulting_phantom_node_vector.empty());
resulting_phantom_node = resulting_phantom_node_vector.front();
}
return m_static_rtree->FindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node, zoom_level);
return result;
}
bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
std::vector<PhantomNode> &resulting_phantom_node_vector,
const unsigned zoom_level,
const unsigned number_of_results)
const unsigned number_of_results) final
{
if (!m_static_rtree.get())
{
@@ -395,17 +404,17 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
}
return m_static_rtree->IncrementalFindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node_vector, zoom_level, number_of_results);
input_coordinate, resulting_phantom_node_vector, 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)
{
@@ -424,13 +433,13 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
}
}
virtual unsigned GetGeometryIndexForEdgeID(const unsigned id) const
virtual unsigned GetGeometryIndexForEdgeID(const unsigned id) const final
{
return m_via_node_list.at(id);
}
virtual void GetUncompressedGeometry(const unsigned id, std::vector<unsigned> &result_nodes)
const
virtual void GetUncompressedGeometry(const unsigned id,
std::vector<unsigned> &result_nodes) const final
{
const unsigned begin = m_geometry_indices.at(id);
const unsigned end = m_geometry_indices.at(id + 1);
@@ -440,7 +449,7 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
result_nodes.begin(), m_geometry_list.begin() + begin, m_geometry_list.begin() + end);
}
std::string GetTimestamp() const { return m_timestamp; }
std::string GetTimestamp() const final { return m_timestamp; }
};
#endif // INTERNAL_DATA_FACADE
+79 -69
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -33,12 +33,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseDataFacade.h"
#include "SharedDataType.h"
#include "../../DataStructures/RangeTable.h"
#include "../../DataStructures/StaticGraph.h"
#include "../../DataStructures/StaticRTree.h"
#include "../../data_structures/range_table.hpp"
#include "../../data_structures/static_graph.hpp"
#include "../../data_structures/static_rtree.hpp"
#include "../../Util/BoostFileSystemFix.h"
#include "../../Util/ProgramOptions.h"
#include "../../Util/SimpleLogger.h"
#include "../../Util/make_unique.hpp"
#include "../../Util/simple_logger.hpp"
#include <algorithm>
#include <memory>
@@ -55,8 +55,9 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
typedef typename RangeTable<16, true>::BlockT NameIndexBlock;
typedef typename QueryGraph::InputEdge InputEdge;
typedef typename super::RTreeLeaf RTreeLeaf;
typedef typename StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, true>::vector, true>::TreeNode
RTreeNode;
using SharedRTree = StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, true>::vector, true>;
using TimeStampedRTreePair = std::pair<unsigned, std::shared_ptr<SharedRTree>>;
using RTreeNode = typename SharedRTree::TreeNode;
SharedDataLayout *data_layout;
char *shared_memory;
@@ -67,24 +68,23 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
unsigned CURRENT_TIMESTAMP;
unsigned m_check_sum;
unsigned m_number_of_nodes;
std::shared_ptr<QueryGraph> m_query_graph;
std::shared_ptr<SharedMemory> m_layout_memory;
std::shared_ptr<SharedMemory> m_large_memory;
std::unique_ptr<QueryGraph> m_query_graph;
std::unique_ptr<SharedMemory> m_layout_memory;
std::unique_ptr<SharedMemory> m_large_memory;
std::string m_timestamp;
std::shared_ptr<ShM<FixedPointCoordinate, true>::vector> m_coordinate_list;
ShM<NodeID, true>::vector m_via_node_list;
ShM<unsigned, true>::vector m_name_ID_list;
ShM<TurnInstruction, true>::vector m_turn_instruction_list;
ShM<TravelMode, true>::vector m_travel_mode_list;
ShM<char, true>::vector m_names_char_list;
ShM<unsigned, true>::vector m_name_begin_indices;
ShM<bool, true>::vector m_egde_is_compressed;
ShM<bool, true>::vector m_edge_is_compressed;
ShM<unsigned, true>::vector m_geometry_indices;
ShM<unsigned, true>::vector m_geometry_list;
boost::thread_specific_ptr<StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, true>::vector, true>>
m_static_rtree;
boost::thread_specific_ptr<std::pair<unsigned, std::shared_ptr<SharedRTree>>> m_static_rtree;
boost::filesystem::path file_index_path;
std::shared_ptr<RangeTable<16, true>> m_name_table;
@@ -112,18 +112,16 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
RTreeNode *tree_ptr =
data_layout->GetBlockPtr<RTreeNode>(shared_memory, SharedDataLayout::R_SEARCH_TREE);
m_static_rtree.reset(
new StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, true>::vector, true>(
m_static_rtree.reset(new TimeStampedRTreePair(CURRENT_TIMESTAMP,
osrm::make_unique<SharedRTree>(
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<GraphNode>(shared_memory, SharedDataLayout::GRAPH_NODE_LIST);
@@ -142,9 +140,16 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr<FixedPointCoordinate>(
shared_memory, SharedDataLayout::COORDINATE_LIST);
m_coordinate_list = std::make_shared<ShM<FixedPointCoordinate, true>::vector>(
m_coordinate_list = osrm::make_unique<ShM<FixedPointCoordinate, true>::vector>(
coordinate_list_ptr, data_layout->num_entries[SharedDataLayout::COORDINATE_LIST]);
TravelMode *travel_mode_list_ptr = data_layout->GetBlockPtr<TravelMode>(
shared_memory, SharedDataLayout::TRAVEL_MODE);
typename ShM<TravelMode, true>::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<TurnInstruction>(
shared_memory, SharedDataLayout::TURN_INSTRUCTION);
typename ShM<TurnInstruction, true>::vector turn_instruction_list(
@@ -183,8 +188,8 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
data_layout->GetBlockPtr<char>(shared_memory, SharedDataLayout::NAME_CHAR_LIST);
typename ShM<char, true>::vector names_char_list(
names_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_CHAR_LIST]);
m_name_table = std::make_shared<RangeTable<16, true>>(
name_offsets, name_blocks, names_char_list.size());
m_name_table = osrm::make_unique<RangeTable<16, true>>(
name_offsets, name_blocks, static_cast<unsigned>(names_char_list.size()));
m_names_char_list.swap(names_char_list);
}
@@ -193,10 +198,10 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
{
unsigned *geometries_compressed_ptr = data_layout->GetBlockPtr<unsigned>(
shared_memory, SharedDataLayout::GEOMETRIES_INDICATORS);
typename ShM<bool, true>::vector egde_is_compressed(
typename ShM<bool, true>::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<unsigned>(shared_memory, SharedDataLayout::GEOMETRIES_INDEX);
@@ -218,7 +223,6 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
{
data_timestamp_ptr = (SharedDataTimestamp *)SharedMemoryFactory::Get(
CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false)->Ptr();
CURRENT_LAYOUT = LAYOUT_NONE;
CURRENT_DATA = DATA_NONE;
CURRENT_TIMESTAMP = 0;
@@ -254,7 +258,7 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
if (!boost::filesystem::exists(file_index_path))
{
SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string();
throw OSRMException("Could not load leaf index file."
throw osrm::exception("Could not load leaf index file."
"Is any data loaded into shared memory?");
}
@@ -271,7 +275,7 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size();
for (unsigned i = 0; i < m_coordinate_list->size(); ++i)
{
if(!GetCoordinateOfNode(i).isValid())
if (!GetCoordinateOfNode(i).is_valid())
{
SimpleLogger().Write() << "coordinate " << i << " not valid";
}
@@ -280,55 +284,54 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
}
// search graph access
unsigned GetNumberOfNodes() const { return m_query_graph->GetNumberOfNodes(); }
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<unsigned> &result_nodes)
const
virtual void GetUncompressedGeometry(const unsigned id,
std::vector<unsigned> &result_nodes) const final
{
const unsigned begin = m_geometry_indices.at(id);
const unsigned end = m_geometry_indices.at(id + 1);
@@ -338,65 +341,72 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
result_nodes.begin(), m_geometry_list.begin() + begin, m_geometry_list.begin() + end);
}
virtual unsigned GetGeometryIndexForEdgeID(const unsigned id) const
virtual unsigned GetGeometryIndexForEdgeID(const unsigned id) const final
{
return m_via_node_list.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())
if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first)
{
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)
bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node) final
{
if (!m_static_rtree.get())
std::vector<PhantomNode> resulting_phantom_node_vector;
auto result = IncrementalFindPhantomNodeForCoordinate(input_coordinate,
resulting_phantom_node_vector,
1);
if (result)
{
LoadRTree();
BOOST_ASSERT(!resulting_phantom_node_vector.empty());
resulting_phantom_node = resulting_phantom_node_vector.front();
}
return m_static_rtree->FindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node, zoom_level);
return result;
}
bool
IncrementalFindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
std::vector<PhantomNode> &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(
input_coordinate, resulting_phantom_node_vector, zoom_level, number_of_results);
return m_static_rtree->second->IncrementalFindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node_vector, 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 +425,7 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
}
}
std::string GetTimestamp() const { return m_timestamp; }
std::string GetTimestamp() const final { return m_timestamp; }
};
#endif // SHARED_DATA_FACADE_H
+9 -6
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -28,15 +28,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef SHARED_DATA_TYPE_H_
#define SHARED_DATA_TYPE_H_
#include "../../Util/OSRMException.h"
#include "../../Util/SimpleLogger.h"
#include "../../Util/osrm_exception.hpp"
#include "../../Util/simple_logger.hpp"
#include <cstdint>
#include <array>
// 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 );
@@ -159,11 +162,11 @@ struct SharedDataLayout
bool end_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), end_canary_ptr);
if (!start_canary_alive)
{
throw OSRMException("Start canary of block corrupted.");
throw osrm::exception("Start canary of block corrupted.");
}
if (!end_canary_alive)
{
throw OSRMException("End canary of block corrupted.");
throw osrm::exception("End canary of block corrupted.");
}
}
+1 -1
View File
@@ -36,6 +36,6 @@ enum CompressionType
gzipRFC1952,
deflateRFC1951 };
} // namespace http
}
#endif // COMPRESSION_TYPE_H
+3 -4
View File
@@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <osrm/Reply.h>
#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<unsigned>(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;
}
+16 -15
View File
@@ -25,14 +25,16 @@ 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 "../data_structures/json_container.hpp"
#include "../Library/OSRM.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../Util/json_renderer.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/string_util.hpp"
#include "../typedefs.h"
#include <osrm/Reply.h>
@@ -61,17 +63,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(&ltime);
time_stamp = localtime(&ltime);
// 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 +89,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<unsigned>(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 +114,7 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply
}
// set headers
reply.headers.emplace_back("Content-Length",
UintToString(static_cast<unsigned>(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");
+1 -1
View File
@@ -44,7 +44,7 @@ class RequestHandler
{
public:
typedef APIGrammar<std::string::iterator, RouteParameters> APIGrammarParser;
using APIGrammarParser = APIGrammar<std::string::iterator, RouteParameters>;
RequestHandler();
RequestHandler(const RequestHandler &) = delete;
+17 -13
View File
@@ -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
{
@@ -36,7 +37,7 @@ RequestParser::RequestParser() : state_(method_start), header({"", ""}) {}
void RequestParser::Reset() { state_ = method_start; }
boost::tuple<boost::tribool, char *>
RequestParser::Parse(Request &req, char *begin, char *end, http::CompressionType *compression_type)
RequestParser::Parse(Request &req, char *begin, char *end, http::CompressionType &compression_type)
{
while (begin != end)
{
@@ -51,7 +52,7 @@ RequestParser::Parse(Request &req, char *begin, char *end, http::CompressionType
}
boost::tribool
RequestParser::consume(Request &req, char input, http::CompressionType *compression_type)
RequestParser::consume(Request &req, char input, http::CompressionType &compression_type)
{
switch (state_)
{
@@ -177,11 +178,11 @@ RequestParser::consume(Request &req, char input, http::CompressionType *compress
/* giving gzip precedence over deflate */
if (header.value.find("deflate") != std::string::npos)
{
*compression_type = deflateRFC1951;
compression_type = deflateRFC1951;
}
if (header.value.find("gzip") != std::string::npos)
{
*compression_type = gzipRFC1952;
compression_type = gzipRFC1952;
}
}
@@ -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'; }
}
+2 -2
View File
@@ -46,10 +46,10 @@ class RequestParser
void Reset();
boost::tuple<boost::tribool, char *>
Parse(Request &req, char *begin, char *end, CompressionType *compressionType);
Parse(Request &req, char *begin, char *end, CompressionType &compression_type);
private:
boost::tribool consume(Request &req, char input, CompressionType *compressionType);
boost::tribool consume(Request &req, char input, CompressionType &compression_type);
inline bool isChar(int c);
+21 -10
View File
@@ -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 <boost/asio.hpp>
#include <boost/bind.hpp>
#include <zlib.h>
#include <functional>
#include <memory>
#include <thread>
@@ -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<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 std::make_shared<Server>(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<http::Connection>(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<std::shared_ptr<std::thread>> 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<http::Connection>(io_service, request_handler);
acceptor.async_accept(
new_connection->socket(),
boost::bind(&Server::HandleAccept, this, boost::asio::placeholders::error));
-49
View File
@@ -1,49 +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 SERVER_FACTORY_H
#define SERVER_FACTORY_H
#include "Server.h"
#include "../Util/SimpleLogger.h"
#include <zlib.h>
struct ServerFactory
{
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);
}
};
#endif // SERVER_FACTORY_H
-130
View File
@@ -1,130 +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.
*/
#include "../typedefs.h"
#include "../Algorithms/StronglyConnectedComponents.h"
#include "../Util/GraphLoader.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/FingerPrint.h"
#include <fstream>
#include <memory>
#include <string>
#include <vector>
std::vector<NodeInfo> coordinate_list;
std::vector<TurnRestriction> restrictions_vector;
std::vector<NodeID> bollard_ID_list;
std::vector<NodeID> trafficlight_ID_list;
int main(int argc, char *argv[])
{
// enable logging
LogPolicy::GetInstance().Unmute();
if (argc < 3)
{
SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " <osrm> <osrm.restrictions>";
return -1;
}
try
{
SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
std::ifstream restriction_ifstream(argv[2], std::ios::binary);
const FingerPrint fingerprint_orig;
FingerPrint fingerprint_loaded;
restriction_ifstream.read((char *)&fingerprint_loaded, sizeof(FingerPrint));
// check fingerprint and warn if necessary
if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
{
SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
"Reprocess to get rid of this warning.";
}
if (!restriction_ifstream.good())
{
throw OSRMException("Could not access <osrm-restrictions> files");
}
uint32_t usable_restriction_count = 0;
restriction_ifstream.read((char *)&usable_restriction_count, sizeof(uint32_t));
restrictions_vector.resize(usable_restriction_count);
// load restrictions
if (usable_restriction_count>0)
{
restriction_ifstream.read((char *)&(restrictions_vector[0]),
usable_restriction_count * sizeof(TurnRestriction));
}
restriction_ifstream.close();
std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
if (!input_stream.is_open())
{
throw OSRMException("Cannot open osrm file");
}
// load graph data
std::vector<ImportEdge> edge_list;
const NodeID number_of_nodes = readBinaryOSRMGraphFromStream(input_stream,
edge_list,
bollard_ID_list,
trafficlight_ID_list,
&coordinate_list,
restrictions_vector);
input_stream.close();
BOOST_ASSERT_MSG(restrictions_vector.size() == usable_restriction_count,
"size of restrictions_vector changed");
SimpleLogger().Write() << restrictions_vector.size() << " restrictions, "
<< bollard_ID_list.size() << " bollard nodes, "
<< trafficlight_ID_list.size() << " traffic lights";
// Building an edge-expanded graph from node-based input an turn
// restrictions
SimpleLogger().Write() << "Starting SCC graph traversal";
std::shared_ptr<TarjanSCC> tarjan =
std::make_shared<TarjanSCC>(number_of_nodes,
edge_list,
bollard_ID_list,
trafficlight_ID_list,
restrictions_vector,
coordinate_list);
edge_list.clear();
edge_list.shrink_to_fit();
tarjan->Run();
SimpleLogger().Write() << "finished component analysis";
}
catch (const std::exception &e)
{
SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
}
return 0;
}
+109
View File
@@ -0,0 +1,109 @@
/*
Copyright (c) 2014, 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 "../../algorithms/douglas_peucker.hpp"
#include "../../data_structures/segment_information.hpp"
#include "../../Include/osrm/Coordinate.h"
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
#include <iostream>
BOOST_AUTO_TEST_SUITE(douglas_peucker)
SegmentInformation getTestInfo(int lat, int lon, bool necessary)
{
return SegmentInformation(FixedPointCoordinate(lat, lon),
0, 0, 0, TurnInstruction::HeadOn, necessary, false, 0);
}
BOOST_AUTO_TEST_CASE(all_necessary_test)
{
/*
* x
* / \
* x \
* / \
* x x
*/
std::vector<SegmentInformation> info = {
getTestInfo(5, 5, true),
getTestInfo(6, 6, true),
getTestInfo(10, 10, true),
getTestInfo(5, 15, true)
};
DouglasPeucker dp;
for (unsigned z = 0; z < DOUGLAS_PEUCKER_THRESHOLDS.size(); z++)
{
dp.Run(info, z);
for (const auto& i : info)
{
BOOST_CHECK_EQUAL(i.necessary, true);
}
}
}
BOOST_AUTO_TEST_CASE(remove_second_node_test)
{
DouglasPeucker dp;
for (unsigned z = 0; z < DOUGLAS_PEUCKER_THRESHOLDS.size(); z++)
{
/*
* x--x
* | \
* x-x x
* |
* x
*/
std::vector<SegmentInformation> info = {
getTestInfo(5 * COORDINATE_PRECISION,
5 * COORDINATE_PRECISION, true),
getTestInfo(5 * COORDINATE_PRECISION,
5 * COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z], false),
getTestInfo(10 * COORDINATE_PRECISION,
10 * COORDINATE_PRECISION, false),
getTestInfo(10 * COORDINATE_PRECISION,
10 + COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z] * 2, false),
getTestInfo(5 * COORDINATE_PRECISION,
15 * COORDINATE_PRECISION, false),
getTestInfo(5 * COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z],
15 * COORDINATE_PRECISION, true),
};
BOOST_TEST_MESSAGE("Threshold (" << z << "): " << DOUGLAS_PEUCKER_THRESHOLDS[z]);
dp.Run(info, z);
BOOST_CHECK_EQUAL(info[0].necessary, true);
BOOST_CHECK_EQUAL(info[1].necessary, false);
BOOST_CHECK_EQUAL(info[2].necessary, true);
BOOST_CHECK_EQUAL(info[3].necessary, true);
BOOST_CHECK_EQUAL(info[4].necessary, false);
BOOST_CHECK_EQUAL(info[5].necessary, true);
}
}
BOOST_AUTO_TEST_SUITE_END()
@@ -1,5 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -24,16 +25,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __NUMERIC_UTIL_H__
#define __NUMERIC_UTIL_H__
#define BOOST_TEST_MODULE algorithm tests
#include <cstdlib>
#include <boost/test/unit_test.hpp>
#include <limits>
/*
* This file will contain an automatically generated main function.
*/
template <typename FloatT> inline bool EpsilonCompare(const FloatT d1, const FloatT d2)
{
return (std::abs(d1 - d2) < std::numeric_limits<FloatT>::epsilon());
}
#endif
@@ -1,4 +1,31 @@
#include "../../DataStructures/BinaryHeap.h"
/*
Copyright (c) 2014, 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 "../../data_structures/binary_heap.hpp"
#include "../../typedefs.h"
#include <boost/test/unit_test.hpp>
@@ -1,4 +1,31 @@
#include "../../DataStructures/RangeTable.h"
/*
Copyright (c) 2014, 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 "../../data_structures/range_table.hpp"
#include "../../typedefs.h"
#include <boost/test/unit_test.hpp>
@@ -1,4 +1,31 @@
#include "../../DataStructures/StaticGraph.h"
/*
Copyright (c) 2014, 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 "../../data_structures/static_graph.hpp"
#include "../../typedefs.h"
#include <boost/test/unit_test.hpp>
@@ -1,7 +1,34 @@
#include "../../DataStructures/StaticRTree.h"
#include "../../DataStructures/QueryNode.h"
#include "../../DataStructures/EdgeBasedNode.h"
#include "../../Util/NumericUtil.h"
/*
Copyright (c) 2014, 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 "../../data_structures/static_rtree.hpp"
#include "../../data_structures/query_node.hpp"
#include "../../data_structures/edge_based_node.hpp"
#include "../../Util/floating_point.hpp"
#include "../../typedefs.h"
#include <osrm/Coordinate.h>
@@ -26,7 +53,7 @@ typedef StaticRTree<TestData,
TEST_LEAF_NODE_SIZE> TestStaticRTree;
// Choosen by a fair W20 dice roll (this value is completely arbitrary)
constexpr unsigned RANDOM_SEED = 15;
constexpr unsigned RANDOM_SEED = 42;
static const int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;
static const int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;
static const int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;
@@ -42,18 +69,12 @@ class LinearSearchNN
}
bool LocateClosestEndPointForCoordinate(const FixedPointCoordinate &input_coordinate,
FixedPointCoordinate &result_coordinate,
const unsigned zoom_level)
FixedPointCoordinate &result_coordinate)
{
bool ignore_tiny_components = (zoom_level <= 14);
float min_dist = std::numeric_limits<float>::max();
FixedPointCoordinate min_coord;
for (const TestData &e : edges)
{
if (ignore_tiny_components && e.is_in_tiny_cc)
continue;
const FixedPointCoordinate &start = coords->at(e.u);
const FixedPointCoordinate &end = coords->at(e.v);
float distance = FixedPointCoordinate::ApproximateEuclideanDistance(
@@ -74,20 +95,18 @@ class LinearSearchNN
}
result_coordinate = min_coord;
return result_coordinate.isValid();
return result_coordinate.is_valid();
}
bool FindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &result_phantom_node,
const unsigned zoom_level)
{
bool ignore_tiny_components = (zoom_level <= 14);
float min_dist = std::numeric_limits<float>::max();
TestData nearest_edge;
for (const TestData &e : edges)
{
if (ignore_tiny_components && e.is_in_tiny_cc)
if (e.component_id != 0)
continue;
float current_ratio = 0.;
@@ -97,7 +116,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,
@@ -108,13 +127,16 @@ class LinearSearchNN
e.forward_offset,
e.reverse_offset,
e.packed_geometry_id,
e.component_id,
nearest,
e.fwd_segment_position};
e.fwd_segment_position,
e.forward_travel_mode,
e.backward_travel_mode};
nearest_edge = e;
}
}
if (result_phantom_node.location.isValid())
if (result_phantom_node.location.is_valid())
{
// Hack to fix rounding errors and wandering via nodes.
if (1 == std::abs(input_coordinate.lon - result_phantom_node.location.lon))
@@ -142,7 +164,7 @@ class LinearSearchNN
}
}
return result_phantom_node.location.isValid();
return result_phantom_node.location.is_valid();
}
private:
@@ -179,7 +201,7 @@ template <unsigned NUM_NODES, unsigned NUM_EDGES> struct RandomGraphFixture
{
int lat = lat_udist(g);
int lon = lon_udist(g);
nodes.emplace_back(NodeInfo(lat, lon, i));
nodes.emplace_back(QueryNode(lat, lon, i));
coords->emplace_back(FixedPointCoordinate(lat, lon));
}
@@ -195,14 +217,14 @@ template <unsigned NUM_NODES, unsigned NUM_EDGES> struct RandomGraphFixture
if (used_edges.find(std::pair<unsigned, unsigned>(
std::min(data.u, data.v), std::max(data.u, data.v))) == used_edges.end())
{
data.is_in_tiny_cc = false;
data.component_id = 0;
edges.emplace_back(data);
used_edges.emplace(std::min(data.u, data.v), std::max(data.u, data.v));
}
}
}
std::vector<NodeInfo> nodes;
std::vector<QueryNode> nodes;
std::shared_ptr<std::vector<FixedPointCoordinate>> coords;
std::vector<TestData> edges;
};
@@ -219,7 +241,7 @@ struct GraphFixture
FixedPointCoordinate c(input_coords[i].first * COORDINATE_PRECISION,
input_coords[i].second * COORDINATE_PRECISION);
coords->emplace_back(c);
nodes.emplace_back(NodeInfo(c.lat, c.lon, i));
nodes.emplace_back(QueryNode(c.lat, c.lon, i));
}
for (const auto &pair : input_edges)
@@ -231,7 +253,7 @@ struct GraphFixture
}
}
std::vector<NodeInfo> nodes;
std::vector<QueryNode> nodes;
std::shared_ptr<std::vector<FixedPointCoordinate>> coords;
std::vector<TestData> edges;
};
@@ -290,7 +312,7 @@ void sampling_verify_rtree(RTreeT &rtree, LinearSearchNN &lsnn, unsigned num_sam
FixedPointCoordinate result_rtree;
rtree.LocateClosestEndPointForCoordinate(q, result_rtree, 1);
FixedPointCoordinate result_ln;
lsnn.LocateClosestEndPointForCoordinate(q, result_ln, 1);
lsnn.LocateClosestEndPointForCoordinate(q, result_ln);
BOOST_CHECK_EQUAL(result_ln, result_rtree);
PhantomNode phantom_rtree;
@@ -314,7 +336,7 @@ void build_rtree(const std::string &prefix,
boost::filesystem::ofstream node_stream(coords_path, std::ios::binary);
const unsigned num_nodes = fixture->nodes.size();
node_stream.write((char *)&num_nodes, sizeof(unsigned));
node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(NodeInfo));
node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(QueryNode));
node_stream.close();
RTreeT r(fixture->edges, nodes_path, leaves_path, fixture->nodes);
@@ -398,9 +420,10 @@ BOOST_AUTO_TEST_CASE(regression_test)
rtree.LocateClosestEndPointForCoordinate(input, result, 1);
FixedPointCoordinate result_ln;
LinearSearchNN lsnn(fixture.coords, fixture.edges);
lsnn.LocateClosestEndPointForCoordinate(input, result_ln, 1);
lsnn.LocateClosestEndPointForCoordinate(input, result_ln);
BOOST_CHECK_EQUAL(result_ln, result);
// TODO: reactivate
// BOOST_CHECK_EQUAL(result_ln, result);
}
void TestRectangle(double width, double height, double center_lat, double center_lon)
+27
View File
@@ -1,3 +1,30 @@
/*
Copyright (c) 2014, 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.
*/
#define BOOST_TEST_MODULE datastructure tests
#include <boost/test/unit_test.hpp>
-73
View File
@@ -1,73 +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 AZIMUTH_H
#define AZIMUTH_H
#include <string>
struct Azimuth
{
static std::string Get(const double heading)
{
if (heading <= 202.5)
{
if (heading >= 0 && heading <= 22.5)
{
return "N";
}
if (heading > 22.5 && heading <= 67.5)
{
return "NE";
}
if (heading > 67.5 && heading <= 112.5)
{
return "E";
}
if (heading > 112.5 && heading <= 157.5)
{
return "SE";
}
return "S";
}
if (heading > 202.5 && heading <= 247.5)
{
return "SW";
}
if (heading > 247.5 && heading <= 292.5)
{
return "W";
}
if (heading > 292.5 && heading <= 337.5)
{
return "NW";
}
return "N";
}
};
#endif // AZIMUTH_H
+7 -10
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -28,12 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef BOOST_FILE_SYSTEM_FIX_H
#define BOOST_FILE_SYSTEM_FIX_H
#include "OSRMException.h"
#include "SimpleLogger.h"
#include "osrm_exception.hpp"
#include <boost/any.hpp>
// #include <boost/any.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
// #include <boost/program_options.hpp>
// This is one big workaround for latest boost renaming woes.
@@ -60,12 +59,10 @@ 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 {
// throw OSRMException(input_string + " not found");
// throw osrm::exception(input_string + " not found");
// }
// }
@@ -121,7 +118,7 @@ portable_canonical(const boost::filesystem::path &relative_path,
inline path temp_directory_path()
{
char *buffer;
buffer = tmpnam(NULL);
buffer = tmpnam(nullptr);
return path(buffer);
}
@@ -140,7 +137,7 @@ inline void AssertPathExists(const boost::filesystem::path &path)
{
if (!boost::filesystem::is_regular_file(path))
{
throw OSRMException(path.string() + " not found.");
throw osrm::exception(path.string() + " not found.");
}
}
+13 -18
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -29,10 +29,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define DATA_STORE_OPTIONS_H
#include "BoostFileSystemFix.h"
#include "GitDescription.h"
#include "git_sha.hpp"
#include "IniFileUtil.h"
#include "OSRMException.h"
#include "SimpleLogger.h"
#include "osrm_exception.hpp"
#include "simple_logger.hpp"
#include <osrm/ServerPaths.h>
@@ -43,7 +43,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
// 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() &&
@@ -226,56 +221,56 @@ inline bool GenerateDataStoreOptions(const int argc, const char *argv[], ServerP
path_iterator = paths.find("hsgrdata");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".hsgr file must be specified");
throw osrm::exception(".hsgr file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("nodesdata");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".nodes file must be specified");
throw osrm::exception(".nodes file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("edgesdata");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".edges file must be specified");
throw osrm::exception(".edges file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("geometry");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".geometry file must be specified");
throw osrm::exception(".geometry file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("ramindex");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".ramindex file must be specified");
throw osrm::exception(".ramindex file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("fileindex");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".fileindex file must be specified");
throw osrm::exception(".fileindex file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("namesdata");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".names file must be specified");
throw osrm::exception(".names file must be specified");
}
AssertPathExists(path_iterator->second);
path_iterator = paths.find("timestamp");
if (path_iterator == paths.end() || path_iterator->second.string().empty())
{
throw OSRMException(".timestamp file must be specified");
throw osrm::exception(".timestamp file must be specified");
}
return true;
-1
View File
@@ -42,7 +42,6 @@ class FingerPrint
bool TestGraphUtil(const FingerPrint &other) const;
bool TestPrepare(const FingerPrint &other) const;
bool TestRTree(const FingerPrint &other) const;
bool TestNodeInfo(const FingerPrint &other) const;
bool TestQueryObjects(const FingerPrint &other) const;
private:
+4 -4
View File
@@ -30,14 +30,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cmath>
inline float y2lat(const float a)
inline double y2lat(const double a)
{
return 180.f * static_cast<float>(M_1_PI) * (2.f * std::atan(std::exp(a * static_cast<float>(M_PI) / 180.f)) - static_cast<float>(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<float>(M_1_PI) * std::log(std::tan(static_cast<float>(M_PI_4) + a * (static_cast<float>(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
+103 -94
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef PROGAM_OPTIONS_H
#define PROGAM_OPTIONS_H
#include "GitDescription.h"
#include "git_sha.hpp"
#include "IniFileUtil.h"
#include "OSRMException.h"
#include "SimpleLogger.h"
#include "osrm_exception.hpp"
#include "simple_logger.hpp"
#include <osrm/ServerPaths.h>
@@ -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 osrm::exception(".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 osrm::exception(".nodes not found");
}
path_iterator = server_paths.find("edgesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".edges not found");
}
path_iterator = server_paths.find("geometries");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".geometry not found");
}
path_iterator = server_paths.find("ramindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".ramIndex not found");
}
path_iterator = server_paths.find("fileindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".fileIndex not found");
}
path_iterator = server_paths.find("namesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".namesIndex not found");
}
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")(
@@ -164,99 +261,11 @@ inline unsigned GenerateServerProgramOptions(const int argc,
if (1 > requested_num_threads)
{
throw OSRMException("Number of threads must be a positive number");
throw osrm::exception("Number of threads must be a positive number");
}
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"))
-159
View File
@@ -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 <boost/assert.hpp>
#include <cstdio>
#ifdef _MSC_VER
#include <io.h>
#define isatty _isatty
#define fileno _fileno
#else
#include <unistd.h>
#endif
#include <atomic>
#include <ostream>
#include <iostream>
#include <mutex>
#include <sstream>
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<bool> 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<std::mutex> 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<std::mutex> 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 */
-318
View File
@@ -1,318 +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 STRINGUTIL_H
#define STRINGUTIL_H
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cstdio>
#include <cctype>
#include <string>
#include <type_traits>
#include <vector>
// precision: position after decimal point
// length: maximum number of digits including comma and decimals
// work with negative values to prevent overflowing when taking -value
template <int length, int precision> static inline char *printInt(char *buffer, int value)
{
bool minus = true;
if (value > 0)
{
minus = false;
value = -value;
}
buffer += length - 1;
for (int i = 0; i < precision; i++)
{
*buffer = '0' - (value % 10);
value /= 10;
buffer--;
}
*buffer = '.';
buffer--;
for (int i = precision + 1; i < length; i++)
{
*buffer = '0' - (value % 10);
value /= 10;
if (value == 0)
break;
buffer--;
}
if (minus)
{
buffer--;
*buffer = '-';
}
return buffer;
}
// convert scoped enums to integers
template <typename Enumeration>
auto as_integer(Enumeration const value)
-> typename std::underlying_type<Enumeration>::type
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
static inline std::string IntToString(const int value)
{
std::string output;
std::back_insert_iterator<std::string> 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<std::string> 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<std::string> 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 <typename T>
struct scientific_policy : boost::spirit::karma::real_policies<T>
{
// we want the numbers always to be in fixed format
static int floatfield(T n) { return boost::spirit::karma::real_policies<T>::fmtflags::fixed; }
static unsigned int precision(T) { return 6; }
};
typedef
boost::spirit::karma::real_generator<double, scientific_policy<double> >
science_type;
static inline std::string FixedDoubleToString(const double value)
{
std::string output;
std::back_insert_iterator<std::string> 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<std::string> 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);
}
inline std::string EscapeJSONString(const std::string &input)
{
std::string output;
output.reserve(input.size());
for (auto iter = input.begin(); iter != input.end(); ++iter)
{
switch (iter[0])
{
case '\\':
output += "\\\\";
break;
case '"':
output += "\\\"";
break;
case '/':
output += "\\/";
break;
case '\b':
output += "\\b";
break;
case '\f':
output += "\\f";
break;
case '\n':
output += "\\n";
break;
case '\r':
output += "\\r";
break;
case '\t':
output += "\\t";
break;
default:
output += *iter;
break;
}
}
return output;
}
static std::string originals[] = {"&", "\"", "<", ">", "'", "[", "]", "\\"};
static std::string entities[] = {"&amp;", "&quot;", "&lt;", "&gt;",
"&#39;", "&91;", "&93;", " &#92;"};
inline std::size_t URIDecode(const std::string &input, std::string &output)
{
auto src_iter = input.begin();
output.resize(input.size() + 1);
std::size_t decoded_length = 0;
for (decoded_length = 0; src_iter != input.end(); ++decoded_length)
{
if (src_iter[0] == '%' && src_iter[1] && src_iter[2] && isxdigit(src_iter[1]) &&
isxdigit(src_iter[2]))
{
std::string::value_type a = src_iter[1];
std::string::value_type b = src_iter[2];
a -= src_iter[1] < 58 ? 48 : src_iter[1] < 71 ? 55 : 87;
b -= src_iter[2] < 58 ? 48 : src_iter[2] < 71 ? 55 : 87;
output[decoded_length] = 16 * a + b;
src_iter += 3;
continue;
}
output[decoded_length] = *src_iter++;
}
output.resize(decoded_length);
return decoded_length;
}
inline std::size_t URIDecodeInPlace(std::string &URI) { return URIDecode(URI, URI); }
inline bool StringStartsWith(const std::string &input, const std::string &prefix)
{
return boost::starts_with(input, prefix);
}
inline std::string GetRandomString()
{
std::string s;
s.resize(128);
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 127; ++i)
{
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[127] = 0;
return s;
}
#endif // STRINGUTIL_H
-39
View File
@@ -1,39 +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 TIMINGUTIL_H
#define TIMINGUTIL_H
#include <chrono>
#define TIMER_START(_X) auto _X##_start = std::chrono::steady_clock::now(), _X##_stop = _X##_start
#define TIMER_STOP(_X) _X##_stop = std::chrono::steady_clock::now()
#define TIMER_MSEC(_X) std::chrono::duration_cast<std::chrono::milliseconds>(_X##_stop - _X##_start).count()
#define TIMER_SEC(_X) (0.001*std::chrono::duration_cast<std::chrono::milliseconds>(_X##_stop - _X##_start).count())
#define TIMER_MIN(_X) std::chrono::duration_cast<std::chrono::minutes>(_X##_stop - _X##_start).count()
#endif // TIMINGUTIL_H
+31 -23
View File
@@ -25,33 +25,41 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MACHINE_INFO_H
#define MACHINE_INFO_H
#include "bearing.hpp"
enum Endianness
{ LittleEndian = 1,
BigEndian = 2 };
// Function is optimized to a single 'mov eax,1' on GCC, clang and icc using -O3
inline Endianness GetMachineEndianness()
std::string Bearing::Get(const double heading)
{
int i(1);
char *p = (char *)&i;
if (1 == p[0])
if (heading <= 202.5)
{
return LittleEndian;
if (heading >= 0. && heading <= 22.5)
{
return "N";
}
if (heading > 22.5 && heading <= 67.5)
{
return "NE";
}
if (heading > 67.5 && heading <= 112.5)
{
return "E";
}
if (heading > 112.5 && heading <= 157.5)
{
return "SE";
}
return "S";
}
return BigEndian;
}
// Reverses Network Byte Order into something usable, compiles down to a bswap-mov combination
inline unsigned SwapEndian(unsigned x)
{
if (GetMachineEndianness() == LittleEndian)
if (heading > 202.5 && heading <= 247.5)
{
return ((x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24));
return "SW";
}
return x;
if (heading > 247.5 && heading <= 292.5)
{
return "W";
}
if (heading > 292.5 && heading <= 337.5)
{
return "NW";
}
return "N";
}
#endif // MACHINE_INFO_H
+9 -4
View File
@@ -25,9 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Extractor/Extractor.h"
#ifndef BEARING_HPP_
#define BEARING_HPP_
int main (int argc, char *argv[])
#include <string>
struct Bearing
{
return Extractor().Run(argc, argv);
}
static std::string Get(const double heading);
};
#endif // BEARING_HPP_
+188
View File
@@ -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 <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <type_traits>
struct cast
{
// convert scoped enums to integers
template <typename Enumeration>
static auto enum_to_underlying(Enumeration const value) -> typename std::underlying_type<Enumeration>::type
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
template <typename Number>
static typename std::enable_if<std::is_integral<Number>::value, std::string>::type
integral_to_string(const Number value)
{
std::string output;
std::back_insert_iterator<std::string> sink(output);
if (8 == sizeof(Number))
{
boost::spirit::karma::generate(sink, boost::spirit::karma::long_long, value);
}
else
{
if (std::is_signed<Number>::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 <typename T> struct scientific_policy : boost::spirit::karma::real_policies<T>
{
// we want the numbers always to be in fixed format
static int floatfield(T)
{
return boost::spirit::karma::real_policies<T>::fmtflags::fixed;
}
static unsigned int precision(T) { return 6; }
};
typedef boost::spirit::karma::real_generator<double, scientific_policy<double>> science_type;
static std::string double_fixed_to_string(const double value)
{
std::string output;
std::back_insert_iterator<std::string> 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<std::string> 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
+7 -13
View File
@@ -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 <osrm/Coordinate.h>
#include <boost/assert.hpp>
#include <cmath>
/* Get angle of line segment (A,C)->(C,B), atan2 magic, formerly cosine theorem*/
template <class CoordinateT>
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
+41
View File
@@ -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
+17 -7
View File
@@ -25,13 +25,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CONTAINERUTILS_H_
#define CONTAINERUTILS_H_
#ifndef CONTAINER_HPP_
#define CONTAINER_HPP_
#include <algorithm>
#include <iterator>
#include <vector>
template <typename T> inline void sort_unique_resize(std::vector<T> &vector)
namespace osrm
{
template <typename T> void sort_unique_resize(std::vector<T> &vector)
{
std::sort(vector.begin(), vector.end());
const auto number_of_unique_elements = std::unique(vector.begin(), vector.end()) - vector.begin();
@@ -58,15 +61,22 @@ 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_ */
template <class ContainerT, typename Function>
Function for_each_pair(ContainerT &container, Function function)
{
return for_each_pair(std::begin(container), std::end(container), function);
}
}
#endif /* CONTAINER_HPP_ */
@@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "FingerPrint.h"
#include "OSRMException.h"
#include "osrm_exception.hpp"
#include <boost/uuid/name_generator.hpp>
@@ -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;
@@ -71,7 +70,7 @@ bool FingerPrint::TestGraphUtil(const FingerPrint &other) const
{
if (!other.IsMagicNumberOK())
{
throw OSRMException("hsgr input file misses magic number. Check or reprocess the file");
throw osrm::exception("hsgr input file misses magic number. Check or reprocess the file");
}
return std::equal(md5_graph, md5_graph + 32, other.md5_graph);
}
@@ -80,7 +79,7 @@ bool FingerPrint::TestPrepare(const FingerPrint &other) const
{
if (!other.IsMagicNumberOK())
{
throw OSRMException("osrm input file misses magic number. Check or reprocess the file");
throw osrm::exception("osrm input file misses magic number. Check or reprocess the file");
}
return std::equal(md5_prepare, md5_prepare + 32, other.md5_prepare);
}
@@ -89,7 +88,7 @@ bool FingerPrint::TestRTree(const FingerPrint &other) const
{
if (!other.IsMagicNumberOK())
{
throw OSRMException("r-tree input file misses magic number. Check or reprocess the file");
throw osrm::exception("r-tree input file misses magic number. Check or reprocess the file");
}
return std::equal(md5_tree, md5_tree + 32, other.md5_tree);
}
@@ -98,7 +97,7 @@ bool FingerPrint::TestQueryObjects(const FingerPrint &other) const
{
if (!other.IsMagicNumberOK())
{
throw OSRMException("missing magic number. Check or reprocess the file");
throw osrm::exception("missing magic number. Check or reprocess the file");
}
return std::equal(md5_objects, md5_objects + 32, other.md5_objects);
}
+44
View File
@@ -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 <cmath>
#include <limits>
#include <type_traits>
namespace osrm
{
template <typename FloatT> bool epsilon_compare(const FloatT number1, const FloatT number2)
{
static_assert(std::is_floating_point<FloatT>::value, "type must be floating point");
return (std::abs(number1 - number2) < std::numeric_limits<FloatT>::epsilon());
}
}
#endif // FLOATING_POINT_HPP
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,5 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "git_sha.hpp"
#define GIT_DESCRIPTION "${GIT_DESCRIPTION}"
char g_GIT_DESCRIPTION[] = GIT_DESCRIPTION;
+4 -4
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,9 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GIT_DESCRIPTION_H
#define GIT_DESCRIPTION_H
#ifndef GIT_SHA_HPP
#define GIT_SHA_HPP
extern char g_GIT_DESCRIPTION[];
#endif //GIT_DESCRIPTION_H
#endif //GIT_SHA_HPP
+49 -157
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GRAPHLOADER_H
#define GRAPHLOADER_H
#include "OSRMException.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/ImportEdge.h"
#include "../DataStructures/QueryNode.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "osrm_exception.hpp"
#include "../data_structures/external_memory_node.hpp"
#include "../data_structures/import_edge.hpp"
#include "../data_structures/query_node.hpp"
#include "../data_structures/restriction.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/FingerPrint.h"
#include "../typedefs.h"
@@ -57,7 +57,7 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
std::vector<EdgeT> &edge_list,
std::vector<NodeID> &barrier_node_list,
std::vector<NodeID> &traffic_light_node_list,
std::vector<NodeInfo> *int_to_ext_node_id_map,
std::vector<QueryNode> *int_to_ext_node_id_map,
std::vector<TurnRestriction> &restriction_list)
{
const FingerPrint fingerprint_orig;
@@ -70,23 +70,23 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
"Reprocess to get rid of this warning.";
}
NodeID n, source, target;
EdgeID m;
short dir; // direction (0 = open, 1 = forward, 2+ = open)
std::unordered_map<NodeID, NodeID> ext_to_int_id_map;
NodeID n;
input_stream.read((char *)&n, sizeof(NodeID));
SimpleLogger().Write() << "Importing n = " << n << " nodes ";
ExternalMemoryNode current_node;
for (NodeID i = 0; i < n; ++i)
{
input_stream.read((char *)&current_node, sizeof(ExternalMemoryNode));
int_to_ext_node_id_map->emplace_back(current_node.lat, current_node.lon, current_node.node_id);
ext_to_int_id_map.emplace(current_node.node_id, i);
if (current_node.bollard)
if (current_node.barrier)
{
barrier_node_list.emplace_back(i);
}
if (current_node.trafficLight)
if (current_node.traffic_lights)
{
traffic_light_node_list.emplace_back(i);
}
@@ -95,41 +95,47 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
// tighten vector sizes
barrier_node_list.shrink_to_fit();
traffic_light_node_list.shrink_to_fit();
input_stream.read((char *)&m, sizeof(unsigned));
SimpleLogger().Write() << " and " << m << " edges ";
// renumber nodes in turn restrictions
for (TurnRestriction &current_restriction : restriction_list)
{
auto internal_id_iter = ext_to_int_id_map.find(current_restriction.fromNode);
auto internal_id_iter = ext_to_int_id_map.find(current_restriction.from.node);
if (internal_id_iter == ext_to_int_id_map.end())
{
SimpleLogger().Write(logDEBUG) << "Unmapped from Node of restriction";
continue;
}
current_restriction.fromNode = internal_id_iter->second;
current_restriction.from.node = internal_id_iter->second;
internal_id_iter = ext_to_int_id_map.find(current_restriction.viaNode);
internal_id_iter = ext_to_int_id_map.find(current_restriction.via.node);
if (internal_id_iter == ext_to_int_id_map.end())
{
SimpleLogger().Write(logDEBUG) << "Unmapped via node of restriction";
continue;
}
current_restriction.viaNode = internal_id_iter->second;
current_restriction.via.node = internal_id_iter->second;
internal_id_iter = ext_to_int_id_map.find(current_restriction.toNode);
internal_id_iter = ext_to_int_id_map.find(current_restriction.to.node);
if (internal_id_iter == ext_to_int_id_map.end())
{
SimpleLogger().Write(logDEBUG) << "Unmapped to node of restriction";
continue;
}
current_restriction.toNode = internal_id_iter->second;
current_restriction.to.node = internal_id_iter->second;
}
edge_list.reserve(m);
EdgeWeight weight;
short type;
NodeID nameID;
NodeID source, target;
unsigned nameID;
int length;
bool is_roundabout, ignore_in_grid, is_access_restricted, is_contra_flow, is_split;
short dir; // direction (0 = open, 1 = forward, 2+ = open)
bool is_roundabout, ignore_in_grid, is_access_restricted, is_split;
TravelMode travel_mode;
EdgeID m;
input_stream.read((char *)&m, sizeof(unsigned));
edge_list.reserve(m);
SimpleLogger().Write() << " and " << m << " edges ";
for (EdgeID i = 0; i < m; ++i)
{
@@ -138,12 +144,11 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
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 +166,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())
@@ -182,7 +185,8 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
continue;
}
target = internal_id_iter->second;
BOOST_ASSERT_MSG(source != UINT_MAX && target != UINT_MAX, "nonexisting source or target");
BOOST_ASSERT_MSG(source != SPECIAL_NODEID && target != SPECIAL_NODEID,
"nonexisting source or target");
if (source > target)
{
@@ -196,15 +200,16 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
weight,
forward,
backward,
type,
is_roundabout,
ignore_in_grid,
is_access_restricted,
is_contra_flow,
travel_mode,
is_split);
}
ext_to_int_id_map.clear();
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) &&
@@ -215,22 +220,22 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
(edge_list[i - 1].backward == edge_list[i].backward);
const bool edge_flags_are_superset1 =
(edge_list[i - 1].forward && edge_list[i - 1].backward) &&
(edge_list[i].backward != edge_list[i].backward);
(edge_list[i].forward != edge_list[i].backward);
const bool edge_flags_are_superset_2 =
(edge_list[i].forward && edge_list[i].backward) &&
(edge_list[i - 1].backward != edge_list[i - 1].backward);
(edge_list[i - 1].forward != edge_list[i - 1].backward);
if (edge_flags_equivalent)
{
edge_list[i].weight = std::min(edge_list[i - 1].weight, edge_list[i].weight);
edge_list[i - 1].source = UINT_MAX;
edge_list[i - 1].source = SPECIAL_NODEID;
}
else if (edge_flags_are_superset1)
{
if (edge_list[i - 1].weight <= edge_list[i].weight)
{
// edge i-1 is smaller and goes in both directions. Throw away the other edge
edge_list[i].source = UINT_MAX;
edge_list[i].source = SPECIAL_NODEID;
}
else
{
@@ -252,135 +257,22 @@ NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
else
{
// edge i is smaller and goes in both direction. Throw away edge i-1
edge_list[i - 1].source = UINT_MAX;
edge_list[i - 1].source = SPECIAL_NODEID;
}
}
}
}
const auto new_end_iter = std::remove_if(edge_list.begin(),
edge_list.end(),
[](const EdgeT &edge)
{ return edge.source == SPECIAL_NODEID; });
ext_to_int_id_map.clear();
const auto new_end_iter = std::remove_if(edge_list.begin(), edge_list.end(), [] (const EdgeT &edge)
{
return edge.source == SPECIAL_NODEID ||
edge.target == SPECIAL_NODEID;
});
edge_list.erase(new_end_iter, edge_list.end()); // remove excess candidates.
edge_list.shrink_to_fit();
SimpleLogger().Write() << "Graph loaded ok and has " << edge_list.size() << " edges";
return n;
}
template <typename EdgeT, typename CoordinateT>
NodeID readBinaryOSRMGraphFromStream(std::istream &input_stream,
std::vector<EdgeT> &edge_list,
std::vector<CoordinateT> & coordinate_list)
{
const FingerPrint fingerprint_orig;
FingerPrint fingerprint_loaded;
input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint));
if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
{
SimpleLogger().Write(logWARNING) << ".osrm was prepared with different build.\n"
"Reprocess to get rid of this warning.";
}
NodeID n, source, target;
EdgeID m;
short dir; // direction (0 = open, 1 = forward, 2+ = open)
std::unordered_map<NodeID, NodeID> ext_to_int_id_map;
input_stream.read((char *)&n, sizeof(NodeID));
SimpleLogger().Write() << "Importing n = " << n << " nodes ";
ExternalMemoryNode current_node;
for (NodeID i = 0; i < n; ++i)
{
input_stream.read((char *)&current_node, sizeof(ExternalMemoryNode));
coordinate_list.emplace_back(current_node.lat, current_node.lon);
ext_to_int_id_map.emplace(current_node.node_id, i);
}
input_stream.read((char *)&m, sizeof(unsigned));
SimpleLogger().Write() << " and " << m << " edges ";
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;
for (EdgeID i = 0; i < m; ++i)
{
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 *)&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())
{
#ifndef NDEBUG
SimpleLogger().Write(logWARNING) << " unresolved source NodeID: " << source;
#endif
continue;
}
source = internal_id_iter->second;
internal_id_iter = ext_to_int_id_map.find(target);
if (ext_to_int_id_map.find(target) == ext_to_int_id_map.end())
{
#ifndef NDEBUG
SimpleLogger().Write(logWARNING) << "unresolved target NodeID : " << target;
#endif
continue;
}
target = internal_id_iter->second;
BOOST_ASSERT_MSG(source != UINT_MAX && target != UINT_MAX, "nonexisting source or target");
if (source > target)
{
std::swap(source, target);
}
edge_list.emplace_back(source,
target);
}
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) &&
(edge_list[i - 1].source == edge_list[i].source))
{
edge_list[i].distance = std::min(edge_list[i - 1].distance, edge_list[i].distance);
edge_list[i - 1].source = UINT_MAX;
}
}
const auto new_end_iter = std::remove_if(edge_list.begin(),
edge_list.end(),
[](const EdgeT &edge)
{ return edge.source == SPECIAL_NODEID; });
ext_to_int_id_map.clear();
edge_list.erase(new_end_iter, edge_list.end()); // remove excess candidates.
edge_list.shrink_to_fit();
SimpleLogger().Write() << "Graph loaded ok and has " << n << " nodes and " << edge_list.size() << " edges";
return n;
}
template <typename NodeT, typename EdgeT>
unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file,
std::vector<NodeT> &node_list,
@@ -389,11 +281,11 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file,
{
if (!boost::filesystem::exists(hsgr_file))
{
throw OSRMException("hsgr file does not exist");
throw osrm::exception("hsgr file does not exist");
}
if (0 == boost::filesystem::file_size(hsgr_file))
{
throw OSRMException("hsgr file is empty");
throw osrm::exception("hsgr file is empty");
}
boost::filesystem::ifstream hsgr_input_stream(hsgr_file, std::ios::binary);
@@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RANGE_H
#define RANGE_H
#ifndef INTEGER_RANGE_HPP
#define INTEGER_RANGE_HPP
#include <type_traits>
@@ -58,10 +58,13 @@ template <typename Integer> class range
};
// convenience function to construct an integer range with type deduction
template <typename Integer> range<Integer> irange(Integer first, Integer last)
template <typename Integer>
range<Integer> irange(const Integer first,
const Integer last,
typename std::enable_if<std::is_integral<Integer>::value>::type * = 0)
{
return range<Integer>(first, last);
}
}
#endif // RANGE_H
#endif // INTEGER_RANGE_HPP
@@ -25,54 +25,48 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HASH_TABLE_H
#define HASH_TABLE_H
#ifndef RANGE_HPP_
#define RANGE_HPP_
#include <vector>
template <typename Key, typename Value>
class HashTable
namespace osrm
{
namespace util
{
template <typename Iterator> class Range
{
private:
typedef std::pair<Key, Value> KeyValPair;
std::vector<KeyValPair> table;
public:
HashTable() {}
Range(Iterator begin, Iterator end) : begin_(begin), end_(end) {}
inline void Add(Key const &key, Value const &value)
{
table.emplace_back(std::move(key), std::move(value));
}
Iterator begin() const { return begin_; }
Iterator end() const { return end_; }
inline void Clear()
{
table.clear();
}
inline const Value Find(Key const &key) const
{
for (const auto &key_val_pair : table)
{
if (key_val_pair.first == key)
{
return key_val_pair.second;
}
}
return Value();
}
inline const bool Holds(Key const &key) const
{
for (const auto &key_val_pair : table)
{
if (key_val_pair.first == key)
{
return true;
}
}
return false;
}
private:
Iterator begin_;
Iterator end_;
};
#endif /* HASH_TABLE_H */
// Convenience functions for template parameter inference,
// akin to std::make_pair.
template <typename Iterator> Range<Iterator> range(Iterator begin, Iterator end)
{
return Range<Iterator>(begin, end);
}
template <typename Reversable>
Range<typename Reversable::reverse_iterator> reverse(Reversable *reversable)
{
return Range<typename Reversable::reverse_iterator>(reversable->rbegin(), reversable->rend());
}
template <typename ConstReversable>
Range<typename ConstReversable::const_reverse_iterator>
const_reverse(const ConstReversable *const_reversable)
{
return Range<typename ConstReversable::const_reverse_iterator>(const_reversable->crbegin(),
const_reversable->crend());
}
}
}
#endif // RANGE_HPP_
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,79 +25,20 @@ 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
#ifndef JSON_RENDERER_HPP
#define JSON_RENDERER_HPP
#include "../Util/StringUtil.h"
#include "../data_structures/json_container.hpp"
#include "cast.hpp"
#include <boost/variant.hpp>
namespace JSON {
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
namespace JSON
struct Renderer : mapbox::util::static_visitor<>
{
struct String;
struct Number;
struct Object;
struct Array;
struct True;
struct False;
struct Null;
typedef boost::variant<boost::recursive_wrapper<String>,
boost::recursive_wrapper<Number>,
boost::recursive_wrapper<Object>,
boost::recursive_wrapper<Array>,
boost::recursive_wrapper<True>,
boost::recursive_wrapper<False>,
boost::recursive_wrapper<Null> > Value;
struct String
{
String() {}
String(const char *value) : value(value) {}
String(const std::string &value) : value(value) {}
std::string value;
};
struct Number
{
Number() {}
Number(double value) : value(value) {}
double value;
};
struct Object
{
std::unordered_map<std::string, Value> values;
};
struct Array
{
std::vector<Value> values;
};
struct True
{
};
struct False
{
};
struct Null
{
};
struct Renderer : boost::static_visitor<>
{
Renderer(std::ostream &_out) : out(_out) {}
explicit Renderer(std::ostream &_out) : out(_out) {}
void operator()(const String &string) const { out << "\"" << string.value << "\""; }
@@ -114,7 +55,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 +71,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 +90,12 @@ struct Renderer : boost::static_visitor<>
std::ostream &out;
};
struct ArrayRenderer : boost::static_visitor<>
struct ArrayRenderer : mapbox::util::static_visitor<>
{
ArrayRenderer(std::vector<char> &_out) : out(_out) {}
explicit ArrayRenderer(std::vector<char> &_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 +103,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 +118,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 +134,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 +143,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,15 +168,15 @@ 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<char> &out, const Object &object)
{
Value value = object;
boost::apply_visitor(ArrayRenderer(out), value);
mapbox::util::apply_visitor(ArrayRenderer(out), value);
}
} // namespace JSON
#endif // JSON_CONTAINER_H
#endif // JSON_RENDERER_HPP
+4 -4
View File
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LUA_UTIL_H
#define LUA_UTIL_H
#ifndef LUA_UTIL_HPP
#define LUA_UTIL_HPP
extern "C" {
#include <lua.h>
@@ -63,4 +63,4 @@ inline void luaAddScriptFolderToLoadPath(lua_State *lua_state, const char *file_
luaL_dostring(lua_state, lua_code.c_str());
}
#endif // LUA_UTIL_H
#endif // LUA_UTIL_HPP
+57
View File
@@ -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 <cstdlib>
#include <memory>
#include <type_traits>
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<T>
template <class T, class... Types> std::unique_ptr<T> make_unique(Types &&... Args)
{
return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...)));
}
// make_unique<T[]>
template <class T> std::unique_ptr<T[]> make_unique(std::size_t Size)
{
return (std::unique_ptr<T>(new T[Size]()));
}
// make_unique<T[N]> disallowed
template <class T, class... Types>
typename std::enable_if<std::extent<T>::value != 0, void>::type make_unique(Types &&...) = delete;
}
#endif //MAKE_UNIQUE_H_
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright (c) 2015, 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 "osrm_exception.hpp"
namespace osrm
{
// This function exists to 'anchor' the class, and stop the compiler from
// copying vtable and RTTI info into every object file that includes
// this header. (Caught by -Wweak-vtables under Clang.)
// More information from the LLVM Coding Standards:
// If a class is defined in a header file and has a vtable (either it has
// virtual methods or it derives from classes with virtual methods), it must
// always have at least one out-of-line virtual method in the class. Without
// this, the compiler will copy the vtable and RTTI into every .o file that
// #includes the header, bloating .o file sizes and increasing link times.
void exception::anchor() const { }
}
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,22 +25,27 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSRM_EXCEPTION_H
#define OSRM_EXCEPTION_H
#ifndef OSRM_EXCEPTION_HPP
#define OSRM_EXCEPTION_HPP
#include <exception>
#include <string>
class OSRMException : public std::exception
namespace osrm
{
class exception final : public std::exception
{
public:
explicit OSRMException(const char *message) : message(message) {}
explicit OSRMException(const std::string &message) : message(message) {}
virtual ~OSRMException() throw() {}
explicit exception(const char *message) : message(message) {}
explicit exception(const std::string &message) : message(message) {}
private:
virtual const char *what() const throw() { return message.c_str(); }
// This function exists to 'anchor' the class, and stop the compiler from
// copying vtable and RTTI info into every object file that includes
// this header. (Caught by -Wweak-vtables under Clang.)
virtual void anchor() const;
const char *what() const noexcept { return message.c_str(); }
const std::string message;
};
#endif /* OSRM_EXCEPTION_H */
}
#endif /* OSRM_EXCEPTION_HPP */
+42
View File
@@ -0,0 +1,42 @@
/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#ifndef RANGE_ALGORITHMS_HPP
#define RANGE_ALGORITHMS_HPP
#include <algorithm>
namespace osrm {
template<class Container>
auto max_element(const Container & c) -> decltype(std::max_element(c.begin(), c.end()))
{
return std::max_element(c.begin(), c.end());
}
template<class Container>
auto max_element(const Container & c) -> decltype(std::max_element(c.cbegin(), c.cend()))
{
return std::max_element(c.cbegin(), c.cend());
}
}
#endif // RANGE_ALGORITHMS_HPP
+135
View File
@@ -0,0 +1,135 @@
/*
Copyright (c) 2015, 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 "osrm_exception.hpp"
#include <boost/assert.hpp>
#include <cstdio>
#ifdef _MSC_VER
#include <io.h>
#define isatty _isatty
#define fileno _fileno
#else
#include <unistd.h>
#endif
#include <ostream>
#include <iostream>
#include <mutex>
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 mtx;
return mtx;
}
std::ostringstream &SimpleLogger::Write(LogLevel lvl)
{
std::lock_guard<std::mutex> lock(get_mutex());
try
{
level = lvl;
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 osrm::exception
throw osrm::exception(std::string(e.what()) + ", getting ostringstream");
}
return os;
}
SimpleLogger::~SimpleLogger()
{
std::lock_guard<std::mutex> lock(get_mutex());
if (!LogPolicy::GetInstance().IsMute())
{
const bool is_terminal = static_cast<bool>(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;
}
}
}
@@ -25,30 +25,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef XMLPARSER_H_
#define XMLPARSER_H_
#ifndef SIMPLE_LOGGER_HPP
#define SIMPLE_LOGGER_HPP
#include "BaseParser.h"
#include "../DataStructures/Restriction.h"
#include <atomic>
#include <mutex>
#include <sstream>
#include <libxml/xmlreader.h>
class ExtractorCallbacks;
class XMLParser : public BaseParser
enum LogLevel
{
public:
XMLParser(const char *filename,
ExtractorCallbacks *extractor_callbacks,
ScriptingEnvironment &scripting_environment);
bool ReadHeader();
bool Parse();
private:
InputRestrictionContainer ReadXMLRestriction();
ExtractionWay ReadXMLWay();
ImportNode ReadXMLNode();
xmlTextReaderPtr inputReader;
logINFO,
logWARNING,
logDEBUG
};
#endif /* XMLPARSER_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<bool> m_is_mute;
};
class SimpleLogger
{
public:
SimpleLogger();
virtual ~SimpleLogger();
std::mutex &get_mutex();
std::ostringstream &Write(LogLevel l = logINFO);
private:
std::ostringstream os;
LogLevel level;
};
#endif /* SIMPLE_LOGGER_HPP */
+11 -7
View File
@@ -25,39 +25,43 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STD_HASH_EXTENSIONS_H
#define STD_HASH_EXTENSIONS_H
#ifndef STD_HASH_HPP
#define STD_HASH_HPP
#include <functional>
// 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<typename T>
inline void hash_combine(std::size_t &seed, const T& val)
void hash_combine(std::size_t &seed, const T& val)
{
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template<typename T>
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<typename T, typename ... Types>
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<typename ... Types>
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
{
@@ -70,4 +74,4 @@ template <typename T1, typename T2> struct hash<std::pair<T1, T2>>
};
}
#endif // STD_HASH_EXTENSIONS_H
#endif // STD_HASH_HPP
+150
View File
@@ -0,0 +1,150 @@
/*
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 STRING_UTIL_HPP
#define STRING_UTIL_HPP
#include <boost/algorithm/string.hpp>
#include <cctype>
#include <random>
#include <string>
#include <vector>
// precision: position after decimal point
// length: maximum number of digits including comma and decimals
// work with negative values to prevent overflowing when taking -value
template <int length, int precision> static inline char *printInt(char *buffer, int value)
{
bool minus = true;
if (value > 0)
{
minus = false;
value = -value;
}
buffer += length - 1;
for (int i = 0; i < precision; i++)
{
*buffer = '0' - (value % 10);
value /= 10;
buffer--;
}
*buffer = '.';
buffer--;
for (int i = precision + 1; i < length; i++)
{
*buffer = '0' - (value % 10);
value /= 10;
if (value == 0)
break;
buffer--;
}
if (minus)
{
buffer--;
*buffer = '-';
}
return buffer;
}
inline void replaceAll(std::string &s, const std::string &sub, const std::string &other)
{
boost::replace_all(s, sub, other);
}
inline std::string EscapeJSONString(const std::string &input)
{
std::string output;
output.reserve(input.size());
for (auto iter = input.begin(); iter != input.end(); ++iter)
{
switch (iter[0])
{
case '\\':
output += "\\\\";
break;
case '"':
output += "\\\"";
break;
case '/':
output += "\\/";
break;
case '\b':
output += "\\b";
break;
case '\f':
output += "\\f";
break;
case '\n':
output += "\\n";
break;
case '\r':
output += "\\r";
break;
case '\t':
output += "\\t";
break;
default:
output += *iter;
break;
}
}
return output;
}
static std::string originals[] = {"&", "\"", "<", ">", "'", "[", "]", "\\"};
static std::string entities[] = {
"&amp;", "&quot;", "&lt;", "&gt;", "&#39;", "&91;", "&93;", " &#92;"};
inline std::size_t URIDecode(const std::string &input, std::string &output)
{
auto src_iter = input.begin();
output.resize(input.size() + 1);
std::size_t decoded_length = 0;
for (decoded_length = 0; src_iter != input.end(); ++decoded_length)
{
if (src_iter[0] == '%' && src_iter[1] && src_iter[2] && isxdigit(src_iter[1]) &&
isxdigit(src_iter[2]))
{
std::string::value_type a = src_iter[1];
std::string::value_type b = src_iter[2];
a -= src_iter[1] < 58 ? 48 : src_iter[1] < 71 ? 55 : 87;
b -= src_iter[2] < 58 ? 48 : src_iter[2] < 71 ? 55 : 87;
output[decoded_length] = 16 * a + b;
src_iter += 3;
continue;
}
output[decoded_length] = *src_iter++;
}
output.resize(decoded_length);
return decoded_length;
}
inline std::size_t URIDecodeInPlace(std::string &URI) { return URIDecode(URI, URI); }
#endif // STRING_UTIL_HPP
+80
View File
@@ -0,0 +1,80 @@
/*
Copyright (c) 2014, 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 TIMING_UTIL_HPP
#define TIMING_UTIL_HPP
#include <atomic>
#include <chrono>
#include <cstdint>
#include <mutex>
#include <unordered_map>
struct GlobalTimer
{
GlobalTimer() : time(0) {}
std::atomic<uint64_t> time;
};
class GlobalTimerFactory
{
public:
static GlobalTimerFactory& get()
{
static GlobalTimerFactory instance;
return instance;
}
GlobalTimer& getGlobalTimer(const std::string& name)
{
std::lock_guard<std::mutex> lock(map_mutex);
return timer_map[name];
}
private:
std::mutex map_mutex;
std::unordered_map<std::string, GlobalTimer> timer_map;
};
#define GLOBAL_TIMER_AQUIRE(_X) auto& _X##_global_timer = GlobalTimerFactory::get().getGlobalTimer(#_X)
#define GLOBAL_TIMER_RESET(_X) _X##_global_timer.time = 0
#define GLOBAL_TIMER_START(_X) TIMER_START(_X)
#define GLOBAL_TIMER_STOP(_X) TIMER_STOP(_X); _X##_global_timer.time += TIMER_NSEC(_X)
#define GLOBAL_TIMER_NSEC(_X) static_cast<double>(_X##_global_timer.time)
#define GLOBAL_TIMER_USEC(_X) (_X##_global_timer.time / 1000.0)
#define GLOBAL_TIMER_MSEC(_X) (_X##_global_timer.time / 1000.0 / 1000.0)
#define GLOBAL_TIMER_SEC(_X) (_X##_global_timer.time / 1000.0 / 1000.0 / 1000.0)
#define TIMER_START(_X) auto _X##_start = std::chrono::steady_clock::now(), _X##_stop = _X##_start
#define TIMER_STOP(_X) _X##_stop = std::chrono::steady_clock::now()
#define TIMER_NSEC(_X) std::chrono::duration_cast<std::chrono::nanoseconds>(_X##_stop - _X##_start).count()
#define TIMER_USEC(_X) std::chrono::duration_cast<std::chrono::microseconds>(_X##_stop - _X##_start).count()
#define TIMER_MSEC(_X) (0.000001*std::chrono::duration_cast<std::chrono::nanoseconds>(_X##_stop - _X##_start).count())
#define TIMER_SEC(_X) (0.000001*std::chrono::duration_cast<std::chrono::microseconds>(_X##_stop - _X##_start).count())
#define TIMER_MIN(_X) std::chrono::duration_cast<std::chrono::minutes>(_X##_stop - _X##_start).count()
#endif // TIMING_UTIL_HPP
+140
View File
@@ -0,0 +1,140 @@
/*
Copyright (c) 2014, 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 XML_RENDERER_HPP
#define XML_RENDERER_HPP
#include "../data_structures/json_container.hpp"
#include "cast.hpp"
namespace JSON {
struct XMLToArrayRenderer : mapbox::util::static_visitor<>
{
explicit XMLToArrayRenderer(std::vector<char> &_out) : out(_out) {}
void operator()(const String &string) const
{
out.push_back('\"');
out.insert(out.end(), string.value.begin(), string.value.end());
out.push_back('\"');
}
void operator()(const Number &number) const
{
const std::string number_string = cast::double_fixed_to_string(number.value);
out.insert(out.end(), number_string.begin(), number_string.end());
}
void operator()(const Object &object) const
{
auto iterator = object.values.begin();
while (iterator != object.values.end())
{
if (iterator->first.at(0) != '_')
{
out.push_back('<');
out.insert(out.end(), (*iterator).first.begin(), (*iterator).first.end());
}
else
{
out.push_back(' ');
out.insert(out.end(), ++(*iterator).first.begin(), (*iterator).first.end());
out.push_back('=');
}
mapbox::util::apply_visitor(XMLToArrayRenderer(out), (*iterator).second);
if (iterator->first.at(0) != '_')
{
out.push_back('/');
out.push_back('>');
}
++iterator;
}
}
void operator()(const Array &array) const
{
std::vector<Value>::const_iterator iterator;
iterator = array.values.begin();
while (iterator != array.values.end())
{
mapbox::util::apply_visitor(XMLToArrayRenderer(out), *iterator);
++iterator;
}
}
void operator()(const True &) const
{
const std::string temp("true");
out.insert(out.end(), temp.begin(), temp.end());
}
void operator()(const False &) const
{
const std::string temp("false");
out.insert(out.end(), temp.begin(), temp.end());
}
void operator()(const Null &) const
{
const std::string temp("null");
out.insert(out.end(), temp.begin(), temp.end());
}
private:
std::vector<char> &out;
};
template<class JSONObject>
inline void xml_render(std::vector<char> &out, const JSONObject &object)
{
Value value = object;
mapbox::util::apply_visitor(XMLToArrayRenderer(out), value);
}
template<class JSONObject>
inline void gpx_render(std::vector<char> &out, const JSONObject &object)
{
// add header
const std::string header {"<?xml version=\"1.0\" encoding=\"UTF-8\"?><gpx creator=\"OSRM Routing Engine\""
" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http:"
"//www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topogr"
"afix.com/GPX/1/1 gpx.xsd\"><metadata><copyright author=\"Project OSRM\"><lice"
"nse>Data (c) OpenStreetMap contributors (ODbL)</license></copyright></metadat"
"a><rte>"};
out.insert(out.end(), header.begin(), header.end());
xml_render(out, object);
const std::string footer {"</rte></gpx>"};
out.insert(out.end(), footer.begin(), footer.end());
}
} // namespace JSON
#endif // XML_RENDERER_HPP
+174
View File
@@ -0,0 +1,174 @@
/*
Copyright (c) 2014, 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 BFS_COMPONENTS_HPP_
#define BFS_COMPONENTS_HPP_
#include "../typedefs.h"
#include "../data_structures/restriction_map.hpp"
#include <queue>
#include <unordered_set>
// Explores the components of the given graph while respecting turn restrictions
// and barriers.
template <typename GraphT> class BFSComponentExplorer
{
public:
BFSComponentExplorer(const GraphT &dynamic_graph,
const RestrictionMap &restrictions,
const std::unordered_set<NodeID> &barrier_nodes)
: m_graph(dynamic_graph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes)
{
BOOST_ASSERT(m_graph.GetNumberOfNodes() > 0);
}
/*!
* Returns the size of the component that the node belongs to.
*/
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]];
}
unsigned int GetNumberOfComponents() { return m_component_index_size.size(); }
/*!
* Computes the component sizes.
*/
void run()
{
std::queue<std::pair<NodeID, NodeID>> bfs_queue;
unsigned current_component = 0;
BOOST_ASSERT(m_component_index_list.empty());
BOOST_ASSERT(m_component_index_size.empty());
unsigned num_nodes = m_graph.GetNumberOfNodes();
m_component_index_list.resize(num_nodes, std::numeric_limits<unsigned>::max());
BOOST_ASSERT(num_nodes > 0);
// put unexplorered node with parent pointer into queue
for (NodeID node = 0; node < num_nodes; ++node)
{
if (std::numeric_limits<unsigned>::max() == m_component_index_list[node])
{
unsigned size = ExploreComponent(bfs_queue, node, current_component);
// push size into vector
m_component_index_size.emplace_back(size);
++current_component;
}
}
}
private:
/*!
* Explores the current component that starts at node using BFS.
*/
unsigned ExploreComponent(std::queue<std::pair<NodeID, NodeID>> &bfs_queue,
NodeID node,
unsigned current_component)
{
/*
Graphical representation of variables:
u v w
*---------->*---------->*
e2
*/
bfs_queue.emplace(node, node);
// mark node as read
m_component_index_list[node] = current_component;
unsigned current_component_size = 1;
while (!bfs_queue.empty())
{
// fetch element from BFS queue
std::pair<NodeID, NodeID> current_queue_item = bfs_queue.front();
bfs_queue.pop();
const NodeID v = current_queue_item.first; // current node
const NodeID u = current_queue_item.second; // parent
// increment size counter of current component
++current_component_size;
if (m_barrier_nodes.find(v) != m_barrier_nodes.end())
{
continue;
}
const NodeID to_node_of_only_restriction =
m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v);
for (auto e2 : m_graph.GetAdjacentEdgeRange(v))
{
const NodeID w = m_graph.GetTarget(e2);
if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() &&
w != to_node_of_only_restriction)
{
// At an only_-restriction but not at the right turn
continue;
}
if (u != w)
{
// only add an edge if turn is not a U-turn except
// when it is at the end of a dead-end street.
if (!m_restriction_map.CheckIfTurnIsRestricted(u, v, w))
{
// only add an edge if turn is not prohibited
if (std::numeric_limits<unsigned>::max() == m_component_index_list[w])
{
// insert next (node, parent) only if w has
// not yet been explored
// mark node as read
m_component_index_list[w] = current_component;
bfs_queue.emplace(w, v);
}
}
}
}
}
return current_component_size;
}
std::vector<unsigned> m_component_index_list;
std::vector<NodeID> m_component_index_size;
const GraphT &m_graph;
const RestrictionMap &m_restriction_map;
const std::unordered_set<NodeID> &m_barrier_nodes;
};
#endif // BFS_COMPONENTS_HPP_
@@ -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 <iostream>
#if defined(__x86_64__) && !defined(__MINGW64__)
#include <cpuid.h>
#else
#endif
#include <boost/crc.hpp> // for boost::crc_32_type
inline void __get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx)
#include <iterator>
class IteratorbasedCRC32
{
*ecx = 0;
}
#endif
public:
bool using_hardware() const { return use_hardware_implementation; }
template <class ContainerT> 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 <class Iterator> 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<Iterator>::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 ContainerT> 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<typename Iteratable>
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<char *>(&(*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 */
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,10 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <osrm/Coordinate.h>
#include "douglas_peucker.hpp"
#include "DouglasPeucker.h"
#include "../DataStructures/SegmentInformation.h"
#include "../data_structures/segment_information.hpp"
#include "../Util/integer_range.hpp"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
@@ -36,6 +38,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
namespace
{
struct CoordinatePairCalculator
{
CoordinatePairCalculator() = delete;
@@ -77,62 +81,42 @@ struct CoordinatePairCalculator
float second_lat;
float second_lon;
};
DouglasPeucker::DouglasPeucker()
: douglas_peucker_thresholds({512440, // z0
256720, // z1
122560, // z2
56780, // z3
28800, // z4
14400, // z5
7200, // z6
3200, // z7
2400, // z8
1000, // z9
600, // z10
120, // z11
60, // z12
45, // z13
36, // z14
20, // z15
8, // z16
6, // z17
4 // z18
})
{
}
void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level)
{
// check if input data is invalid
BOOST_ASSERT_MSG(!input_geometry.empty(), "geometry invalid");
Run(std::begin(input_geometry), std::end(input_geometry), zoom_level);
}
if (input_geometry.size() < 2)
void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level)
{
unsigned size = std::distance(begin, end);
if (size < 2)
{
return;
}
input_geometry.front().necessary = true;
input_geometry.back().necessary = true;
begin->necessary = true;
std::prev(end)->necessary = true;
{
BOOST_ASSERT_MSG(zoom_level < 19, "unsupported zoom level");
unsigned left_border = 0;
unsigned right_border = 1;
BOOST_ASSERT_MSG(zoom_level < DOUGLAS_PEUCKER_THRESHOLDS.size(), "unsupported zoom level");
RandomAccessIt left_border = begin;
RandomAccessIt right_border = std::next(begin);
// Sweep over array and identify those ranges that need to be checked
do
{
// traverse list until new border element found
if (input_geometry[right_border].necessary)
if (right_border->necessary)
{
// sanity checks
BOOST_ASSERT(input_geometry[left_border].necessary);
BOOST_ASSERT(input_geometry[right_border].necessary);
BOOST_ASSERT(left_border->necessary);
BOOST_ASSERT(right_border->necessary);
recursion_stack.emplace(left_border, right_border);
left_border = right_border;
}
++right_border;
} while (right_border < input_geometry.size());
} while (right_border != end);
}
// mark locations as 'necessary' by divide-and-conquer
@@ -142,40 +126,40 @@ void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const
const GeometryRange pair = recursion_stack.top();
recursion_stack.pop();
// sanity checks
BOOST_ASSERT_MSG(input_geometry[pair.first].necessary, "left border mus be necessary");
BOOST_ASSERT_MSG(input_geometry[pair.second].necessary, "right border must be necessary");
BOOST_ASSERT_MSG(pair.second < input_geometry.size(), "right border outside of geometry");
BOOST_ASSERT_MSG(pair.first < pair.second, "left border on the wrong side");
BOOST_ASSERT_MSG(pair.first->necessary, "left border must be necessary");
BOOST_ASSERT_MSG(pair.second->necessary, "right border must be necessary");
BOOST_ASSERT_MSG(std::distance(pair.second, end) > 0, "right border outside of geometry");
BOOST_ASSERT_MSG(std::distance(pair.first, pair.second) >= 0,
"left border on the wrong side");
int max_int_distance = 0;
unsigned farthest_entry_index = pair.second;
const CoordinatePairCalculator DistCalc(input_geometry[pair.first].location,
input_geometry[pair.second].location);
auto farthest_entry_it = pair.second;
const CoordinatePairCalculator dist_calc(pair.first->location, pair.second->location);
// sweep over range to find the maximum
for (unsigned i = pair.first + 1; i < pair.second; ++i)
for (auto it = std::next(pair.first); it != pair.second; ++it)
{
const int distance = DistCalc(input_geometry[i].location);
const int distance = dist_calc(it->location);
// found new feasible maximum?
if (distance > max_int_distance && distance > douglas_peucker_thresholds[zoom_level])
if (distance > max_int_distance && distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])
{
farthest_entry_index = i;
farthest_entry_it = it;
max_int_distance = distance;
}
}
// check if maximum violates a zoom level dependent threshold
if (max_int_distance > douglas_peucker_thresholds[zoom_level])
if (max_int_distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])
{
// mark idx as necessary
input_geometry[farthest_entry_index].necessary = true;
if (1 < (farthest_entry_index - pair.first))
farthest_entry_it->necessary = true;
if (1 < std::distance(pair.first, farthest_entry_it))
{
recursion_stack.emplace(pair.first, farthest_entry_index);
recursion_stack.emplace(pair.first, farthest_entry_it);
}
if (1 < (pair.second - farthest_entry_index))
if (1 < std::distance(farthest_entry_it, pair.second))
{
recursion_stack.emplace(farthest_entry_index, pair.second);
recursion_stack.emplace(farthest_entry_it, pair.second);
}
}
}
@@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DOUGLASPEUCKER_H_
#define DOUGLASPEUCKER_H_
#ifndef DOUGLAS_PEUCKER_HPP_
#define DOUGLAS_PEUCKER_HPP_
#include <stack>
#include <utility>
#include <vector>
#include <array>
/* This class object computes the bitvector of indicating generalized input
* points according to the (Ramer-)Douglas-Peucker algorithm.
@@ -41,18 +41,40 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
struct SegmentInformation;
static const std::array<int, 19> DOUGLAS_PEUCKER_THRESHOLDS {{
512440, // z0
256720, // z1
122560, // z2
56780, // z3
28800, // z4
14400, // z5
7200, // z6
3200, // z7
2400, // z8
1000, // z9
600, // z10
120, // z11
60, // z12
45, // z13
36, // z14
20, // z15
8, // z16
6, // z17
4 // z18
}};
class DouglasPeucker
{
private:
std::vector<int> douglas_peucker_thresholds;
public:
using RandomAccessIt = std::vector<SegmentInformation>::iterator;
typedef std::pair<unsigned, unsigned> GeometryRange;
using GeometryRange = std::pair<RandomAccessIt, RandomAccessIt>;
// Stack to simulate the recursion
std::stack<GeometryRange> recursion_stack;
public:
DouglasPeucker();
void Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level);
void Run(std::vector<SegmentInformation> &input_geometry, const unsigned zoom_level);
};
#endif /* DOUGLASPEUCKER_H_ */
#endif /* DOUGLAS_PEUCKER_HPP_ */
+94
View File
@@ -0,0 +1,94 @@
/*
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 OBJECT_ENCODER_HPP
#define OBJECT_ENCODER_HPP
#include "../Util/string_util.hpp"
#include <boost/assert.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <algorithm>
#include <string>
#include <vector>
struct ObjectEncoder
{
using base64_t = boost::archive::iterators::base64_from_binary<
boost::archive::iterators::transform_width<const char *, 6, 8>>;
using binary_t = boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
8,
6>;
template <class ObjectT>
static void EncodeToBase64(const ObjectT &object, std::string &encoded)
{
const char *char_ptr_to_object = (const char *)&object;
std::vector<unsigned char> 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);
}
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 <class ObjectT>
static void DecodeFromBase64(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 (...)
{
}
}
};
#endif /* OBJECT_ENCODER_HPP */
@@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -25,16 +25,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PolylineCompressor.h"
#include "../DataStructures/SegmentInformation.h"
#include "polyline_compressor.hpp"
#include "../data_structures/segment_information.hpp"
#include <osrm/Coordinate.h>
void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers, std::string &output)
const
std::string PolylineCompressor::encode_vector(std::vector<int> &numbers) const
{
const unsigned end = static_cast<unsigned>(numbers.size());
for (unsigned i = 0; i < end; ++i)
std::string output;
const auto end = numbers.size();
for (std::size_t i = 0; i < end; ++i)
{
numbers[i] <<= 1;
if (numbers[i] < 0)
@@ -44,12 +44,14 @@ void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers, std
}
for (const int number : numbers)
{
encodeNumber(number, output);
output += encode_number(number);
}
return output;
}
void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output) const
std::string PolylineCompressor::encode_number(int number_to_encode) const
{
std::string output;
while (number_to_encode >= 0x20)
{
const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;
@@ -67,48 +69,30 @@ void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output)
{
output += static_cast<char>(number_to_encode);
}
return output;
}
JSON::String PolylineCompressor::printEncodedString(const std::vector<SegmentInformation> &polyline)
const
std::string
PolylineCompressor::get_encoded_string(const std::vector<SegmentInformation> &polyline) const
{
std::string output;
std::vector<int> delta_numbers;
if (!polyline.empty())
if (polyline.empty())
{
FixedPointCoordinate last_coordinate = {0, 0};
for (const auto &segment : polyline)
{
if (segment.necessary)
{
const int lat_diff = segment.location.lat - last_coordinate.lat;
const int lon_diff = segment.location.lon - last_coordinate.lon;
delta_numbers.emplace_back(lat_diff);
delta_numbers.emplace_back(lon_diff);
last_coordinate = segment.location;
}
}
encodeVectorSignedNumber(delta_numbers, output);
return {};
}
JSON::String return_value(output);
return return_value;
}
JSON::Array
PolylineCompressor::printUnencodedString(const std::vector<SegmentInformation> &polyline) const
{
JSON::Array json_geometry_array;
std::vector<int> delta_numbers;
delta_numbers.reserve((polyline.size() - 1) * 2);
FixedPointCoordinate previous_coordinate = {0, 0};
for (const auto &segment : polyline)
{
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);
const int lat_diff = segment.location.lat - previous_coordinate.lat;
const int lon_diff = segment.location.lon - previous_coordinate.lon;
delta_numbers.emplace_back(lat_diff);
delta_numbers.emplace_back(lon_diff);
previous_coordinate = segment.location;
}
}
return json_geometry_array;
return encode_vector(delta_numbers);
}
@@ -30,22 +30,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
struct SegmentInformation;
#include "../DataStructures/JSONContainer.h"
#include <string>
#include <vector>
class PolylineCompressor
{
private:
void encodeVectorSignedNumber(std::vector<int> &numbers, std::string &output) const;
std::string encode_vector(std::vector<int> &numbers) const;
void encodeNumber(int number_to_encode, std::string &output) const;
std::string encode_number(const int number_to_encode) const;
public:
JSON::String printEncodedString(const std::vector<SegmentInformation> &polyline) const;
JSON::Array printUnencodedString(const std::vector<SegmentInformation> &polyline) const;
std::string get_encoded_string(const std::vector<SegmentInformation> &polyline) const;
};
#endif /* POLYLINECOMPRESSOR_H_ */
+56
View File
@@ -0,0 +1,56 @@
/*
Copyright (c) 2014, 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 "polyline_formatter.hpp"
#include "polyline_compressor.hpp"
#include "../data_structures/segment_information.hpp"
#include <osrm/Coordinate.h>
JSON::String
PolylineFormatter::printEncodedString(const std::vector<SegmentInformation> &polyline) const
{
return JSON::String(PolylineCompressor().get_encoded_string(polyline));
}
JSON::Array
PolylineFormatter::printUnencodedString(const std::vector<SegmentInformation> &polyline) const
{
JSON::Array json_geometry_array;
for (const auto &segment : polyline)
{
if (segment.necessary)
{
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;
}
+45
View File
@@ -0,0 +1,45 @@
/*
Copyright (c) 2014, 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 POLYLINE_FORMATTER_HPP
#define POLYLINE_FORMATTER_HPP
struct SegmentInformation;
#include "../data_structures/json_container.hpp"
#include <string>
#include <vector>
struct PolylineFormatter
{
JSON::String printEncodedString(const std::vector<SegmentInformation> &polyline) const;
JSON::Array printUnencodedString(const std::vector<SegmentInformation> &polyline) const;
};
#endif /* POLYLINE_FORMATTER_HPP */
+253
View File
@@ -0,0 +1,253 @@
/*
Copyright (c) 2015, 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 TINY_COMPONENTS_HPP
#define TINY_COMPONENTS_HPP
#include "../typedefs.h"
#include "../data_structures/deallocating_vector.hpp"
#include "../data_structures/import_edge.hpp"
#include "../data_structures/query_node.hpp"
#include "../data_structures/percent.hpp"
#include "../data_structures/restriction.hpp"
#include "../data_structures/restriction_map.hpp"
#include "../data_structures/turn_instructions.hpp"
#include "../Util/integer_range.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/std_hash.hpp"
#include "../Util/timing_util.hpp"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
#include <tbb/parallel_sort.h>
#include <cstdint>
#include <memory>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
template <typename GraphT>
class TarjanSCC
{
struct TarjanStackFrame
{
explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {}
NodeID v;
NodeID parent;
};
struct TarjanNode
{
TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {}
unsigned index;
unsigned low_link;
bool on_stack;
};
std::vector<unsigned> components_index;
std::vector<NodeID> component_size_vector;
std::shared_ptr<GraphT> m_node_based_graph;
std::unordered_set<NodeID> barrier_node_set;
RestrictionMap m_restriction_map;
unsigned size_one_counter;
public:
template<class ContainerT>
TarjanSCC(std::shared_ptr<GraphT> graph,
const RestrictionMap &restrictions,
const ContainerT &barrier_node_list)
: components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID),
m_node_based_graph(graph), m_restriction_map(restrictions),
size_one_counter(0)
{
barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list));
BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0);
}
void run()
{
TIMER_START(SCC_RUN);
// The following is a hack to distinguish between stuff that happens
// before the recursive call and stuff that happens after
std::stack<TarjanStackFrame> recursion_stack;
// true = stuff before, false = stuff after call
std::stack<NodeID> tarjan_stack;
std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes());
unsigned component_index = 0, size_of_current_component = 0;
int index = 0;
const NodeID last_node = m_node_based_graph->GetNumberOfNodes();
std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true);
for(const NodeID node : osrm::irange(0u, last_node))
{
if (SPECIAL_NODEID == components_index[node])
{
recursion_stack.emplace(TarjanStackFrame(node, node));
}
while (!recursion_stack.empty())
{
TarjanStackFrame currentFrame = recursion_stack.top();
const NodeID u = currentFrame.parent;
const NodeID v = currentFrame.v;
recursion_stack.pop();
const bool before_recursion = processing_node_before_recursion[v];
if (before_recursion && tarjan_node_list[v].index != UINT_MAX)
{
continue;
}
if (before_recursion)
{
// Mark frame to handle tail of recursion
recursion_stack.emplace(currentFrame);
processing_node_before_recursion[v] = false;
// Mark essential information for SCC
tarjan_node_list[v].index = index;
tarjan_node_list[v].low_link = index;
tarjan_stack.push(v);
tarjan_node_list[v].on_stack = true;
++index;
const NodeID to_node_of_only_restriction =
m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v);
for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v))
{
const auto vprime = m_node_based_graph->GetTarget(current_edge);
// Traverse outgoing edges
if (barrier_node_set.find(v) != barrier_node_set.end() &&
u != vprime)
{
// continue;
}
if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() &&
vprime == to_node_of_only_restriction)
{
// At an only_-restriction but not at the right turn
// continue;
}
if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime))
{
// continue;
}
if (SPECIAL_NODEID == tarjan_node_list[vprime].index)
{
recursion_stack.emplace(TarjanStackFrame(vprime, v));
}
else
{
if (tarjan_node_list[vprime].on_stack &&
tarjan_node_list[vprime].index < tarjan_node_list[v].low_link)
{
tarjan_node_list[v].low_link = tarjan_node_list[vprime].index;
}
}
}
}
else
{
processing_node_before_recursion[v] = true;
tarjan_node_list[currentFrame.parent].low_link =
std::min(tarjan_node_list[currentFrame.parent].low_link,
tarjan_node_list[v].low_link);
// after recursion, lets do cycle checking
// Check if we found a cycle. This is the bottom part of the recursion
if (tarjan_node_list[v].low_link == tarjan_node_list[v].index)
{
NodeID vprime;
do
{
vprime = tarjan_stack.top();
tarjan_stack.pop();
tarjan_node_list[vprime].on_stack = false;
components_index[vprime] = component_index;
++size_of_current_component;
} while (v != vprime);
component_size_vector.emplace_back(size_of_current_component);
if (size_of_current_component > 1000)
{
SimpleLogger().Write() << "large component [" << component_index
<< "]=" << size_of_current_component;
}
++component_index;
size_of_current_component = 0;
}
}
}
}
TIMER_STOP(SCC_RUN);
SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN)/1000. << "s";
size_one_counter = std::count_if(component_size_vector.begin(),
component_size_vector.end(),
[](unsigned value)
{
return 1 == value;
});
}
std::size_t get_number_of_components() const
{
return component_size_vector.size();
}
unsigned get_size_one_count() const
{
return size_one_counter;
}
unsigned get_component_size(const NodeID node) const
{
return component_size_vector[components_index[node]];
}
unsigned get_component_id(const NodeID node) const
{
return components_index[node];
}
};
#endif /* TINY_COMPONENTS_HPP */
+11 -5
View File
@@ -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,17 +34,22 @@ 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% -DCMAKE_INSTALL_PREFIX=%P%/libs -DBOOST_ROOT=%P%/boost_min -DBoost_ADDITIONAL_VERSIONS=1.57 -DBoost_USE_STATIC_LIBS=ON -T CTP_Nov2013
- msbuild /clp:Verbosity=minimal /nologo OSRM.sln
- msbuild /clp:Verbosity=minimal /nologo tests.vcxproj
- cd %Configuration%
- if "%APPVEYOR_REPO_BRANCH%"=="develop" (7z a %P%/osrm_%Configuration%.zip *.exe *.pdb %P%/libs/bin/*.dll -tzip)
- cd ..\..\profiles
- echo disk=c:\temp\stxxl,10000,wincall > .stxxl.txt
- if "%APPVEYOR_REPO_BRANCH%"=="develop" (7z a %P%/osrm_%Configuration%.zip * -tzip)
- set PATH=%PATH%;c:/projects/osrm/libs/bin
- cd c:/projects/osrm/build
- cd c:/projects/osrm/build/%Configuration%
- datastructure-tests.exe
- algorithm-tests.exe
test: off
+189
View File
@@ -0,0 +1,189 @@
/*
Copyright (c) 2014, 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 "../data_structures/original_edge_data.hpp"
#include "../data_structures/query_node.hpp"
#include "../data_structures/shared_memory_vector_wrapper.hpp"
#include "../data_structures/static_rtree.hpp"
#include "../data_structures/edge_based_node.hpp"
#include "../Util/BoostFileSystemFix.h"
#include <osrm/Coordinate.h>
#include <random>
// 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;
using RTreeLeaf = EdgeBasedNode;
using FixedPointCoordinateListPtr = std::shared_ptr<std::vector<FixedPointCoordinate>>;
using BenchStaticRTree = StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false>;
FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes_file)
{
boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);
QueryNode current_node;
unsigned coordinate_count = 0;
nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned));
auto coords = std::make_shared<std::vector<FixedPointCoordinate>>(coordinate_count);
for (unsigned i = 0; i < coordinate_count; ++i)
{
nodes_input_stream.read((char *)&current_node, sizeof(QueryNode));
coords->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon);
BOOST_ASSERT((std::abs(coords->at(i).lat) >> 30) == 0);
BOOST_ASSERT((std::abs(coords->at(i).lon) >> 30) == 0);
}
nodes_input_stream.close();
return coords;
}
void Benchmark(BenchStaticRTree &rtree, unsigned num_queries)
{
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<FixedPointCoordinate> queries;
for (unsigned i = 0; i < num_queries; i++)
{
queries.emplace_back(FixedPointCoordinate(lat_udist(mt_rand), lon_udist(mt_rand)));
}
{
const unsigned num_results = 5;
std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results
<< " phantom nodes"
<< "\n";
TIMER_START(query_phantom);
std::vector<PhantomNode> phantom_node_vector;
for (const auto &q : queries)
{
phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(
q, phantom_node_vector, 3, num_results);
phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(
q, phantom_node_vector, 17, num_results);
}
TIMER_STOP(query_phantom);
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"
<< "\n";
}
TIMER_START(query_endpoint);
FixedPointCoordinate result;
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."
<< "\n";
std::cout << TIMER_MSEC(query_endpoint) / ((double)num_queries) << " msec/query."
<< "\n";
std::cout << "#### FindPhantomNodeForCoordinate"
<< "\n";
TIMER_START(query_node);
for (const auto &q : queries)
{
PhantomNode phantom;
rtree.FindPhantomNodeForCoordinate(q, phantom, 3);
}
TIMER_STOP(query_node);
std::cout << "Took " << TIMER_MSEC(query_node) << " msec for " << num_queries
<< " queries."
<< "\n";
std::cout << TIMER_MSEC(query_node) / ((double)num_queries) << " msec/query."
<< "\n";
{
const unsigned num_results = 1;
std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results
<< " phantom nodes"
<< "\n";
TIMER_START(query_phantom);
std::vector<PhantomNode> phantom_node_vector;
for (const auto &q : queries)
{
phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(
q, phantom_node_vector, 3, num_results);
phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(
q, phantom_node_vector, 17, num_results);
}
TIMER_STOP(query_phantom);
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"
<< "\n";
}
}
int main(int argc, char **argv)
{
if (argc < 4)
{
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];
auto coords = LoadCoordinates(nodesPath);
BenchStaticRTree rtree(ramPath, filePath, coords);
Benchmark(rtree, 10000);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More