OSRM update to commit 75f9c0844550261d5e9c842d0a10b8f82eac2965. CHECK MAPS.ME OSRM DIFFS FROM HERE

This commit is contained in:
Lev Dragunov 2014-12-17 14:43:09 +03:00 committed by Alex Zolotarev
parent 3a0135ff67
commit 84db1d1338
199 changed files with 5584 additions and 3195 deletions

View file

@ -1,53 +0,0 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: true
AlwaysBreakTemplateDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BinPackParameters: false
ColumnLimit: 100
ConstructorInitializerAllOnOneLineOrOnePerLine: false
DerivePointerBinding: false
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000
PenaltyReturnTypeOnItsOwnLine: 60
PointerBindsToType: false
SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true
Standard: Cpp11
IndentWidth: 4
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Allman
IndentFunctionDeclarationAfterType: false
SpacesInParentheses: false
SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements
...

View file

@ -1,93 +0,0 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
ehthumbs.db
Icon?
Thumbs.db
# build related files #
#######################
/build/
/Util/FingerPrint.cpp
/Util/GitDescription.cpp
# Eclipse related files #
#########################
.setting*
.scb
.cproject
.project
# stxxl related files #
#######################
.stxxl
stxxl.log
stxxl.errlog
# compiled protobuffers #
#########################
/DataStructures/pbf-proto/*.pb.h
/DataStructures/pbf-proto/*.pb.cc
# External Libs #
#################
/lib/
/win/lib
# Visual Studio Temp + build Files #
####################################
/win/*.user
/win/*.ncb
/win/*.suo
/win/Debug/
/win/Release/
/win/bin/
/win/bin-debug/
/osrm-extract
/osrm-io-benchmark
/osrm-components
/osrm-routed
/osrm-datastore
/osrm-prepare
/osrm-unlock-all
/osrm-cli
/osrm-check-hsgr
/nohup.out
# Sandbox folder #
###################
/sandbox/
/test/profile.lua
# Deprecated config file #
##########################
/server.ini

View file

View file

@ -1,54 +0,0 @@
language: cpp
compiler:
- gcc
# - clang
# Make sure CMake is installed
install:
- sudo apt-add-repository -y ppa:ubuntu-toolchain-r/test
- sudo add-apt-repository -y ppa:boost-latest/ppa
- sudo apt-get update >/dev/null
- sudo apt-get -q install libprotoc-dev libprotobuf7 libprotobuf-dev libosmpbf-dev libbz2-dev libstxxl-dev libstxxl1 libxml2-dev libzip-dev lua5.1 liblua5.1-0-dev rubygems libtbb-dev
- sudo apt-get -q install g++-4.7
- sudo apt-get install libboost1.54-all-dev
#luabind
- curl https://gist.githubusercontent.com/DennisOSRM/f2eb7b948e6fe1ae319e/raw/install-luabind.sh | sudo bash
#osmosis
- curl -s https://gist.githubusercontent.com/DennisOSRM/803a64a9178ec375069f/raw/ | sudo bash
before_script:
- rvm use 1.9.3
- gem install bundler
- bundle install
- mkdir build
- cd build
- cmake .. $CMAKEOPTIONS
script:
- make -j 2
- cd ..
- cucumber -p verify
after_script:
# - cd ..
# - cucumber -p verify
branches:
only:
- master
- develop
cache:
- bundler
- apt
env:
- CMAKEOPTIONS="-DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++-4.7" OSRM_PORT=5000 OSRM_TIMEOUT=60
- CMAKEOPTIONS="-DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=g++-4.7" OSRM_PORT=5010 OSRM_TIMEOUT=60
notifications:
irc:
channels:
- irc.oftc.net#osrm
on_success: change
on_failure: always
use_notice: true
skip_join: false
recipients:
- dennis@mapbox.com
email:
on_success: change
on_failure: always

View file

@ -1,8 +1,7 @@
#ifndef __BFS_COMPONENT_EXPLORER_H__
#define __BFS_COMPONENT_EXPLORER_H__
#ifndef BFS_COMPONENT_EXPLORER_H_
#define BFS_COMPONENT_EXPLORER_H_
#include "../typedefs.h"
#include "../DataStructures/DynamicGraph.h"
#include "../DataStructures/RestrictionMap.h"
#include <queue>
@ -13,10 +12,10 @@
template <typename GraphT> class BFSComponentExplorer
{
public:
BFSComponentExplorer(const GraphT &dynamicGraph,
BFSComponentExplorer(const GraphT &dynamic_graph,
const RestrictionMap &restrictions,
const std::unordered_set<NodeID> &barrier_nodes)
: m_graph(dynamicGraph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes)
: m_graph(dynamic_graph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes)
{
BOOST_ASSERT(m_graph.GetNumberOfNodes() > 0);
}
@ -24,14 +23,14 @@ template <typename GraphT> class BFSComponentExplorer
/*!
* Returns the size of the component that the node belongs to.
*/
inline unsigned int GetComponentSize(NodeID node)
unsigned int GetComponentSize(const NodeID node) const
{
BOOST_ASSERT(node < m_component_index_list.size());
return m_component_index_size[m_component_index_list[node]];
}
inline unsigned int GetNumberOfComponents() { return m_component_index_size.size(); }
unsigned int GetNumberOfComponents() { return m_component_index_size.size(); }
/*!
* Computes the component sizes.
@ -68,7 +67,7 @@ template <typename GraphT> class BFSComponentExplorer
/*!
* Explores the current component that starts at node using BFS.
*/
inline unsigned ExploreComponent(std::queue<std::pair<NodeID, NodeID>> &bfs_queue,
unsigned ExploreComponent(std::queue<std::pair<NodeID, NodeID>> &bfs_queue,
NodeID node,
unsigned current_component)
{
@ -145,4 +144,4 @@ template <typename GraphT> class BFSComponentExplorer
const std::unordered_set<NodeID> &m_barrier_nodes;
};
#endif
#endif // BFS_COMPONENT_EXPLORER_H_

View file

@ -25,17 +25,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <osrm/Coordinate.h>
#include "DouglasPeucker.h"
#include "../DataStructures/Range.h"
#include "../DataStructures/SegmentInformation.h"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
#include <cmath>
#include <algorithm>
namespace {
struct CoordinatePairCalculator
{
CoordinatePairCalculator() = delete;
@ -77,6 +80,7 @@ struct CoordinatePairCalculator
float second_lat;
float second_lon;
};
}
DouglasPeucker::DouglasPeucker()
: douglas_peucker_thresholds({512440, // z0
@ -149,13 +153,13 @@ void DouglasPeucker::Run(std::vector<SegmentInformation> &input_geometry, const
int max_int_distance = 0;
unsigned farthest_entry_index = pair.second;
const CoordinatePairCalculator DistCalc(input_geometry[pair.first].location,
input_geometry[pair.second].location);
const CoordinatePairCalculator dist_calc(input_geometry[pair.first].location,
input_geometry[pair.second].location);
// sweep over range to find the maximum
for (unsigned i = pair.first + 1; i < pair.second; ++i)
for (const auto i : osrm::irange(pair.first + 1, pair.second))
{
const int distance = DistCalc(input_geometry[i].location);
const int distance = dist_calc(input_geometry[i].location);
// found new feasible maximum?
if (distance > max_int_distance && distance > douglas_peucker_thresholds[zoom_level])
{

View file

@ -46,7 +46,7 @@ class DouglasPeucker
private:
std::vector<int> douglas_peucker_thresholds;
typedef std::pair<unsigned, unsigned> GeometryRange;
using GeometryRange = std::pair<unsigned, unsigned>;
// Stack to simulate the recursion
std::stack<GeometryRange> recursion_stack;

View file

@ -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 */

View file

@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OBJECTTOBASE64_H_
#define OBJECTTOBASE64_H_
#ifndef OBJECT_TO_BASE64_H_
#define OBJECT_TO_BASE64_H_
#include "../Util/StringUtil.h"
@ -39,61 +39,56 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
typedef
boost::archive::iterators::base64_from_binary<
boost::archive::iterators::transform_width<const char *, 6, 8>
> base64_t;
struct ObjectEncoder
{
using base64_t = boost::archive::iterators::base64_from_binary<
boost::archive::iterators::transform_width<const char *, 6, 8>>;
typedef
boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<
std::string::const_iterator>, 8, 6
> binary_t;
using binary_t = boost::archive::iterators::transform_width<
boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
8,
6>;
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()
);
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);
unsigned char number_of_padded_chars = 0; // is in {0,1,2};
while (data.size() % 3 != 0)
{
++number_of_padded_chars;
data.push_back(0x00);
}
BOOST_ASSERT_MSG(0 == data.size() % 3, "base64 input data size is not a multiple of 3!");
encoded.resize(sizeof(ObjectT));
encoded.assign(base64_t(&data[0]),
base64_t(&data[0] + (data.size() - number_of_padded_chars)));
replaceAll(encoded, "+", "-");
replaceAll(encoded, "/", "_");
}
BOOST_ASSERT_MSG(
0 == data.size() % 3,
"base64 input data size is not a multiple of 3!"
);
encoded.resize(sizeof(ObjectT));
encoded.assign(
base64_t( &data[0] ),
base64_t( &data[0] + (data.size() - number_of_padded_chars) )
);
replaceAll(encoded, "+", "-");
replaceAll(encoded, "/", "_");
}
template <class ObjectT>
static void DecodeFromBase64(const std::string &input, ObjectT &object)
{
try
{
std::string encoded(input);
// replace "-" with "+" and "_" with "/"
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 (...)
{
}
}
};
std::copy (
binary_t( encoded.begin() ),
binary_t( encoded.begin() + encoded.length() - 1),
(char *)&object
);
} catch(...) { }
}
#endif /* OBJECTTOBASE64_H_ */
#endif /* OBJECT_TO_BASE64_H_ */

View file

@ -30,8 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <osrm/Coordinate.h>
void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers, std::string &output)
const
void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers,
std::string &output) const
{
const unsigned end = static_cast<unsigned>(numbers.size());
for (unsigned i = 0; i < end; ++i)
@ -69,8 +69,8 @@ void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output)
}
}
JSON::String PolylineCompressor::printEncodedString(const std::vector<SegmentInformation> &polyline)
const
JSON::String
PolylineCompressor::printEncodedString(const std::vector<SegmentInformation> &polyline) const
{
std::string output;
std::vector<int> delta_numbers;
@ -102,12 +102,10 @@ PolylineCompressor::printUnencodedString(const std::vector<SegmentInformation> &
{
if (segment.necessary)
{
std::string tmp, output;
FixedPointCoordinate::convertInternalLatLonToString(segment.location.lat, tmp);
output += (tmp + ",");
FixedPointCoordinate::convertInternalLatLonToString(segment.location.lon, tmp);
output += tmp;
json_geometry_array.values.push_back(output);
JSON::Array json_coordinate;
json_coordinate.values.push_back(segment.location.lat / COORDINATE_PRECISION);
json_coordinate.values.push_back(segment.location.lon / COORDINATE_PRECISION);
json_geometry_array.values.push_back(json_coordinate);
}
}
return json_geometry_array;

View file

@ -39,7 +39,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/TurnInstructions.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/StdHashExtensions.h"
#include "../Util/TimingUtil.h"
@ -92,12 +92,12 @@ class TarjanSCC
NodeID parent;
};
typedef DynamicGraph<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;
using TarjanDynamicGraph = DynamicGraph<TarjanEdgeData>;
using TarjanEdge = TarjanDynamicGraph::InputEdge;
using RestrictionSource = std::pair<NodeID, NodeID>;
using RestrictionTarget = std::pair<NodeID, bool>;
using EmanatingRestrictionsVector = std::vector<RestrictionTarget>;
using RestrictionMap = std::unordered_map<RestrictionSource, unsigned>;
std::vector<NodeInfo> m_coordinate_list;
std::vector<EmanatingRestrictionsVector> m_restriction_bucket_list;

View file

@ -11,16 +11,16 @@
// Choosen by a fair W20 dice roll (this value is completely arbitrary)
constexpr unsigned RANDOM_SEED = 13;
constexpr int32_t WORLD_MIN_LAT = -90*COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LAT = 90*COORDINATE_PRECISION;
constexpr int32_t WORLD_MIN_LON = -180*COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LON = 180*COORDINATE_PRECISION;
constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;
constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION;
typedef EdgeBasedNode RTreeLeaf;
typedef std::shared_ptr<std::vector<FixedPointCoordinate>> FixedPointCoordinateListPtr;
typedef StaticRTree<RTreeLeaf, ShM<FixedPointCoordinate, false>::vector, false> BenchStaticRTree;
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)
FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes_file)
{
boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);
@ -39,74 +39,86 @@ FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path& nodes
return coords;
}
void Benchmark(BenchStaticRTree& rtree, unsigned num_queries)
void Benchmark(BenchStaticRTree &rtree, unsigned num_queries)
{
std::mt19937 g(RANDOM_SEED);
std::mt19937 mt_rand(RANDOM_SEED);
std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);
std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);
std::vector<FixedPointCoordinate> queries;
for (unsigned i = 0; i < num_queries; i++)
{
queries.emplace_back(
FixedPointCoordinate(lat_udist(g), lon_udist(g))
);
queries.emplace_back(FixedPointCoordinate(lat_udist(mt_rand), lon_udist(mt_rand)));
}
const unsigned num_results = 5;
std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results << " phantom nodes" << std::endl;
std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results
<< " phantom nodes"
<< "\n";
TIMER_START(query_phantom);
std::vector<PhantomNode> resulting_phantom_node_vector;
for (const auto& q : queries)
for (const auto &q : queries)
{
resulting_phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(q, resulting_phantom_node_vector, 3, num_results);
rtree.IncrementalFindPhantomNodeForCoordinate(
q, resulting_phantom_node_vector, 3, num_results);
resulting_phantom_node_vector.clear();
rtree.IncrementalFindPhantomNodeForCoordinate(q, resulting_phantom_node_vector, 17, num_results);
rtree.IncrementalFindPhantomNodeForCoordinate(
q, resulting_phantom_node_vector, 17, num_results);
}
TIMER_STOP(query_phantom);
std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries." << std::endl;
std::cout << TIMER_MSEC(query_phantom)/((double) num_queries) << " msec/query." << std::endl;
std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries << " queries."
<< "\n";
std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query."
<< "\n";
std::cout << "#### LocateClosestEndPointForCoordinate" << std::endl;
std::cout << "#### LocateClosestEndPointForCoordinate"
<< "\n";
TIMER_START(query_endpoint);
FixedPointCoordinate result;
for (const auto& q : queries)
for (const auto &q : queries)
{
rtree.LocateClosestEndPointForCoordinate(q, result, 3);
}
TIMER_STOP(query_endpoint);
std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries." << std::endl;
std::cout << TIMER_MSEC(query_endpoint)/((double) num_queries) << " msec/query." << std::endl;
std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries."
<< "\n";
std::cout << TIMER_MSEC(query_endpoint) / ((double)num_queries) << " msec/query."
<< "\n";
std::cout << "#### FindPhantomNodeForCoordinate" << std::endl;
std::cout << "#### FindPhantomNodeForCoordinate"
<< "\n";
TIMER_START(query_phantomnode);
for (const auto& q : queries)
for (const auto &q : queries)
{
PhantomNode phantom;
rtree.FindPhantomNodeForCoordinate(q, phantom, 3);
}
TIMER_STOP(query_phantomnode);
std::cout << "Took " << TIMER_MSEC(query_phantomnode) << " msec for " << num_queries << " queries." << std::endl;
std::cout << TIMER_MSEC(query_phantomnode)/((double) num_queries) << " msec/query." << std::endl;
std::cout << "Took " << TIMER_MSEC(query_phantomnode) << " msec for " << num_queries
<< " queries."
<< "\n";
std::cout << TIMER_MSEC(query_phantomnode) / ((double)num_queries) << " msec/query."
<< "\n";
}
int main(int argc, char** argv)
int main(int argc, char **argv)
{
if (argc < 4)
{
std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes" << std::endl;
std::cout << "./rtree-bench file.ramIndex file.fileIndx file.nodes"
<< "\n";
return 1;
}
const char* ramPath = argv[1];
const char* filePath = argv[2];
const char* nodesPath = argv[3];
const char *ramPath = argv[1];
const char *filePath = argv[2];
const char *nodesPath = argv[3];
auto coords = LoadCoordinates(nodesPath);

View file

@ -1,11 +1,16 @@
cmake_minimum_required(VERSION 2.8)
cmake_minimum_required(VERSION 2.8.8)
if( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE )
message(FATAL_ERROR "In-source builds are not allowed.
Please create a directory and run cmake from there, passing the path to this source directory as the last argument.
This process created the file `CMakeCache.txt' and the directory `CMakeFiles'. Please delete them.")
endif()
project(OSRM)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(CheckCXXCompilerFlag)
include(FindPackageHandleStandardArgs)
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include(GetGitRevisionDescription)
git_describe(GIT_DESCRIPTION)
@ -22,7 +27,8 @@ if (WIN32 AND MSVC_VERSION LESS 1800)
message(FATAL_ERROR "Building with Microsoft compiler needs Visual Studio 2013 or later (Express version works too)")
endif()
OPTION(WITH_TOOLS "Build ORSM tools" OFF)
OPTION(WITH_TOOLS "Build OSRM tools" OFF)
OPTION(BUILD_TOOLS "Build OSRM tools" OFF)
include_directories(${CMAKE_SOURCE_DIR}/Include/)
@ -35,33 +41,36 @@ add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp FingerPrint.c
VERBATIM)
add_custom_target(FingerPrintConfigure DEPENDS ${CMAKE_SOURCE_DIR}/Util/FingerPrint.cpp)
add_custom_target(tests DEPENDS datastructure-tests)
add_custom_target(benchmarks DEPENDS rtree-bench)
set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread)
set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread unit_test_framework)
configure_file(
${CMAKE_SOURCE_DIR}/Util/GitDescription.cpp.in
${CMAKE_SOURCE_DIR}/Util/GitDescription.cpp
)
file(GLOB ExtractorGlob Extractor/*.cpp)
file(GLOB ExtractorGlobH Extractor/*.h)
file(GLOB ImporterGlob DataStructures/Import*.cpp)
add_library(IMPORT STATIC ${ImporterGlob})
set(ExtractorSources extractor.cpp ${ExtractorGlob} ${ExtractorGlobH})
add_executable(osrm-extract ${ExtractorSources})
add_library(IMPORT OBJECT ${ImporterGlob})
add_library(LOGGER OBJECT Util/simple_logger.cpp)
file(GLOB PrepareGlobH Contractor/*.h DataStructures/*.h)
file(GLOB PrepareGlob Contractor/*.cpp DataStructures/HilbertValue.cpp DataStructures/RestrictionMap.cpp)
set(PrepareSources prepare.cpp ${PrepareGlob} ${PrepareGlobH})
add_executable(osrm-prepare ${PrepareSources})
set(ExtractorSources extractor.cpp ${ExtractorGlob})
add_executable(osrm-extract ${ExtractorSources} $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:LOGGER>)
file(GLOB PrepareGlob Contractor/*.cpp DataStructures/HilbertValue.cpp DataStructures/RestrictionMap.cpp Util/compute_angle.cpp)
set(PrepareSources prepare.cpp ${PrepareGlob})
add_executable(osrm-prepare ${PrepareSources} $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:LOGGER>)
file(GLOB ServerGlob Server/*.cpp)
file(GLOB RoutingAlgs RoutingAlgorithms/*.h)
file(GLOB DescriptorGlob Descriptors/*.cpp)
file(GLOB DatastructureGlob DataStructures/SearchEngineData.cpp DataStructures/RouteParameters.cpp)
list(REMOVE_ITEM DatastructureGlob DataStructures/Coordinate.cpp)
file(GLOB CoordinateGlob DataStructures/Coordinate.cpp)
file(GLOB AlgorithmGlob Algorithms/*.cpp)
file(GLOB HttpGlob Server/Http/*.cpp)
file(GLOB LibOSRMGlob Library/*.cpp)
file(GLOB DataStructureTestsGlob UnitTests/DataStructures/*.cpp DataStructures/HilbertValue.cpp)
set(
OSRMSources
@ -72,14 +81,20 @@ set(
${AlgorithmGlob}
${HttpGlob}
)
add_library(COORDLIB STATIC ${CoordinateGlob})
add_library(FINGERPRINT STATIC Util/FingerPrint.cpp)
add_library(OSRM ${OSRMSources} Util/GitDescription.cpp Util/FingerPrint.cpp)
add_library(GITDESCRIPTION STATIC Util/GitDescription.cpp)
add_library(COORDINATE OBJECT ${CoordinateGlob})
add_library(FINGERPRINT OBJECT Util/FingerPrint.cpp)
add_library(GITDESCRIPTION OBJECT Util/GitDescription.cpp)
add_library(OSRM ${OSRMSources} $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER>)
add_dependencies(FINGERPRINT FingerPrintConfigure)
add_executable(osrm-routed routed.cpp ${ServerGlob} ${RoutingAlgs})
add_executable(osrm-datastore datastore.cpp)
add_executable(osrm-routed routed.cpp ${ServerGlob})
add_executable(osrm-datastore datastore.cpp $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:GITDESCRIPTION> $<TARGET_OBJECTS:LOGGER>)
# Unit tests
add_executable(datastructure-tests EXCLUDE_FROM_ALL UnitTests/datastructure_tests.cpp ${DataStructureTestsGlob} $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER>)
# Benchmarks
add_executable(rtree-bench EXCLUDE_FROM_ALL Benchmarks/StaticRTreeBench.cpp $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER>)
# Check the release mode
if(NOT CMAKE_BUILD_TYPE MATCHES Debug)
@ -103,7 +118,7 @@ if(CMAKE_BUILD_TYPE MATCHES Release)
# Since gcc 4.9 the LTO format is non-standart ('slim'), so we need to use the build-in tools
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND
NOT "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9.0")
NOT "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9.0" AND NOT MINGW)
message(STATUS "Using gcc specific binutils for LTO.")
set(CMAKE_AR "/usr/bin/gcc-ar")
set(CMAKE_RANLIB "/usr/bin/gcc-ranlib")
@ -111,6 +126,10 @@ if(CMAKE_BUILD_TYPE MATCHES Release)
endif (HAS_LTO_FLAG)
endif()
if (NOT WIN32)
add_definitions(-DBOOST_TEST_DYN_LINK)
endif()
# Configuring compilers
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
# using Clang
@ -119,10 +138,9 @@ elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
# using GCC
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -fPIC")
if (WIN32) # using mingw
add_definitions(-DM_PI=3.141592653589793238462643383) # define M_PI
add_definitions(-D_USE_MATH_DEFINES) # define M_PI, M_1_PI etc.
add_definitions(-DWIN32)
SET(OPTIONAL_SOCKET_LIBS ws2_32 wsock32)
SET(OPTIONAL_OMP_LIB gomp)
endif()
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel")
# using Intel C++
@ -136,18 +154,6 @@ elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
add_definitions(-D_WIN32_WINNT=0x0501)
endif()
# disable partitioning of LTO process when possible (fixes Debian issues)
set(LTO_PARTITION_FLAGS "")
CHECK_CXX_COMPILER_FLAG("-flto-partition=none" HAS_LTO_PARTITION_FLAG)
if (HAS_LTO_PARTITION_FLAG)
set(LTO_PARTITION_FLAGS "${LTO_PARTITION_FLAGS} -flto-partition=none")
endif (HAS_LTO_PARTITION_FLAG)
# Add Link-Time-Optimization flags, if supported (GCC >= 4.7) and enabled
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LTO_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${LTO_FLAGS} ${LTO_PARTITION_FLAGS}")
set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LTO_FLAGS} ${LTO_PARTITION_FLAGS}")
# Activate C++11
if(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
ADD_DEFINITIONS(-std=c++11)
@ -182,16 +188,21 @@ if(NOT Boost_FOUND)
endif()
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(OSRM ${Boost_LIBRARIES} COORDLIB)
target_link_libraries(osrm-extract ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB IMPORT)
target_link_libraries(osrm-prepare ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB IMPORT)
target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM FINGERPRINT GITDESCRIPTION)
target_link_libraries(osrm-datastore ${Boost_LIBRARIES} FINGERPRINT GITDESCRIPTION COORDLIB)
target_link_libraries(OSRM ${Boost_LIBRARIES})
target_link_libraries(osrm-extract ${Boost_LIBRARIES})
target_link_libraries(osrm-prepare ${Boost_LIBRARIES})
target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM)
target_link_libraries(osrm-datastore ${Boost_LIBRARIES})
target_link_libraries(datastructure-tests ${Boost_LIBRARIES})
target_link_libraries(rtree-bench ${Boost_LIBRARIES})
find_package(Threads REQUIRED)
target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT} ${OPTIONAL_OMP_LIB})
target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(osrm-datastore ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(osrm-prepare ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(OSRM ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(datastructure-tests ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(rtree-bench ${CMAKE_THREAD_LIBS_INIT})
find_package(TBB REQUIRED)
if(WIN32 AND CMAKE_BUILD_TYPE MATCHES Debug)
@ -201,21 +212,13 @@ target_link_libraries(osrm-datastore ${TBB_LIBRARIES})
target_link_libraries(osrm-extract ${TBB_LIBRARIES})
target_link_libraries(osrm-prepare ${TBB_LIBRARIES})
target_link_libraries(osrm-routed ${TBB_LIBRARIES})
target_link_libraries(datastructure-tests ${TBB_LIBRARIES})
target_link_libraries(rtree-bench ${TBB_LIBRARIES})
include_directories(${TBB_INCLUDE_DIR})
find_package(Lua52)
if(NOT LUA52_FOUND)
find_package(Lua51 REQUIRED)
if(NOT APPLE)
find_package(LuaJIT 5.1)
endif()
else()
if(NOT APPLE)
find_package(LuaJIT 5.2)
endif()
endif()
find_package( Luabind REQUIRED )
include(check_luabind)
include_directories(${LUABIND_INCLUDE_DIR})
target_link_libraries(osrm-extract ${LUABIND_LIBRARY})
target_link_libraries(osrm-prepare ${LUABIND_LIBRARY})
@ -258,29 +261,40 @@ include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries(osrm-extract ${ZLIB_LIBRARY})
target_link_libraries(osrm-routed ${ZLIB_LIBRARY})
if(WITH_TOOLS)
if(WITH_TOOLS OR BUILD_TOOLS)
message(STATUS "Activating OSRM internal tools")
find_package(GDAL)
if(GDAL_FOUND)
add_executable(osrm-components Tools/components.cpp)
target_link_libraries(osrm-components ${TBB_LIBRARIES} IMPORT)
add_executable(osrm-components Tools/components.cpp $<TARGET_OBJECTS:FINGERPRINT> $<TARGET_OBJECTS:IMPORT> $<TARGET_OBJECTS:COORDINATE> $<TARGET_OBJECTS:LOGGER>)
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: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: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_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_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_link_libraries(osrm-springclean ${Boost_LIBRARIES})
install(TARGETS osrm-cli DESTINATION bin)
install(TARGETS osrm-io-benchmark DESTINATION bin)
install(TARGETS osrm-unlock-all DESTINATION bin)
install(TARGETS osrm-check-hsgr DESTINATION bin)
install(TARGETS osrm-springclean DESTINATION bin)
endif()
file(GLOB InstallGlob Include/osrm/*.h Library/OSRM.h)
@ -311,4 +325,7 @@ endforeach ()
configure_file(${CMAKE_SOURCE_DIR}/cmake/pkgconfig.in libosrm.pc @ONLY)
install(FILES ${PROJECT_BINARY_DIR}/libosrm.pc DESTINATION lib/pkgconfig)
add_subdirectory(mapsme)
if(BUILD_DEBIAN_PACKAGE)
include(CPackDebianConfig)
include(CPack)
endif()

View file

@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/Range.h"
#include "../DataStructures/XORFastHash.h"
#include "../DataStructures/XORFastHashStorage.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/StringUtil.h"
#include "../Util/TimingUtil.h"
#include "../typedefs.h"
@ -92,19 +92,18 @@ class Contractor
ContractorHeapData(short h, bool t) : hop(h), target(t) {}
};
typedef DynamicGraph<ContractorEdgeData> ContractorGraph;
// typedef BinaryHeap< NodeID, NodeID, int, ContractorHeapData, ArrayStorage<NodeID, NodeID>
// > ContractorHeap;
typedef BinaryHeap<NodeID, NodeID, int, ContractorHeapData, XORFastHashStorage<NodeID, NodeID>>
ContractorHeap;
typedef ContractorGraph::InputEdge ContractorEdge;
using ContractorGraph = DynamicGraph<ContractorEdgeData>;
// using ContractorHeap = BinaryHeap<NodeID, NodeID, int, ContractorHeapData, ArrayStorage<NodeID, NodeID>
// >;
using ContractorHeap = BinaryHeap<NodeID, NodeID, int, ContractorHeapData, XORFastHashStorage<NodeID, NodeID>>;
using ContractorEdge = ContractorGraph::InputEdge;
struct ContractorThreadData
{
ContractorHeap heap;
std::vector<ContractorEdge> inserted_edges;
std::vector<NodeID> neighbours;
ContractorThreadData(NodeID nodes) : heap(nodes) {}
explicit ContractorThreadData(NodeID nodes) : heap(nodes) {}
};
struct NodePriorityData
@ -136,7 +135,7 @@ class Contractor
struct ThreadDataContainer
{
ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {}
explicit ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {}
inline ContractorThreadData* getThreadData()
{
@ -151,7 +150,7 @@ class Contractor
}
int number_of_nodes;
typedef tbb::enumerable_thread_specific<std::shared_ptr<ContractorThreadData>> EnumerableThreadData;
using EnumerableThreadData = tbb::enumerable_thread_specific<std::shared_ptr<ContractorThreadData>>;
EnumerableThreadData data;
};

View file

@ -29,28 +29,27 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../Algorithms/BFSComponentExplorer.h"
#include "../DataStructures/Percent.h"
#include "../DataStructures/Range.h"
#include "../Util/ComputeAngle.h"
#include "../Util/compute_angle.hpp"
#include "../Util/LuaUtil.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include <boost/assert.hpp>
#include <fstream>
#include <iomanip>
#include <limits>
EdgeBasedGraphFactory::EdgeBasedGraphFactory(
const std::shared_ptr<NodeBasedDynamicGraph> &node_based_graph,
const std::shared_ptr<NodeBasedDynamicGraph> &node_based_graph_origin,
std::unique_ptr<RestrictionMap> restriction_map,
std::vector<NodeID> &barrier_node_list,
std::vector<NodeID> &traffic_light_node_list,
std::vector<NodeInfo> &m_node_info_list,
std::vector<NodeInfo> &node_info_list,
SpeedProfileProperties &speed_profile)
: speed_profile(speed_profile),
m_number_of_edge_based_nodes(std::numeric_limits<unsigned>::max()),
m_node_info_list(m_node_info_list), m_node_based_graph(node_based_graph),
m_node_based_graph_origin(node_based_graph_origin),
m_node_info_list(node_info_list), m_node_based_graph(node_based_graph),
m_restriction_map(std::move(restriction_map)), max_id(0)
{
@ -79,35 +78,30 @@ void EdgeBasedGraphFactory::GetEdgeBasedNodes(std::vector<EdgeBasedNode> &nodes)
nodes.swap(m_edge_based_node_list);
}
void EdgeBasedGraphFactory::GetEdgeBasedNodeData(osrm::NodeDataVectorT &data)
{
data.swap(m_edge_based_node_data);
}
void
EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const bool belongs_to_tiny_cc)
EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeID node_v, const bool belongs_to_tiny_cc)
{
// merge edges together into one EdgeBasedNode
BOOST_ASSERT(u != SPECIAL_NODEID);
BOOST_ASSERT(v != SPECIAL_NODEID);
BOOST_ASSERT(node_u != SPECIAL_NODEID);
BOOST_ASSERT(node_v != SPECIAL_NODEID);
// find forward edge id and
const EdgeID e1 = m_node_based_graph->FindEdge(u, v);
const EdgeID e1 = m_node_based_graph->FindEdge(node_u, node_v);
BOOST_ASSERT(e1 != SPECIAL_EDGEID);
const EdgeData &forward_data = m_node_based_graph->GetEdgeData(e1);
// find reverse edge id and
const EdgeID e2 = m_node_based_graph->FindEdge(v, u);
const EdgeID e2 = m_node_based_graph->FindEdge(node_v, node_u);
#ifndef NDEBUG
if (e2 == m_node_based_graph->EndEdges(v))
if (e2 == m_node_based_graph->EndEdges(node_v))
{
SimpleLogger().Write(logWARNING) << "Did not find edge (" << v << "," << u << ")";
SimpleLogger().Write(logWARNING) << "Did not find edge (" << node_v << "," << node_u << ")";
}
#endif
BOOST_ASSERT(e2 != SPECIAL_EDGEID);
BOOST_ASSERT(e2 < m_node_based_graph->EndEdges(v));
BOOST_ASSERT(e2 < m_node_based_graph->EndEdges(node_v));
const EdgeData &reverse_data = m_node_based_graph->GetEdgeData(e2);
if (forward_data.edgeBasedNodeID == SPECIAL_NODEID &&
@ -157,7 +151,7 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const
// BOOST_ASSERT(reverse_data.distance >= temp_sum);
}
NodeID current_edge_source_coordinate_id = u;
NodeID current_edge_source_coordinate_id = node_u;
if (SPECIAL_NODEID != forward_data.edgeBasedNodeID)
{
@ -177,32 +171,32 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const
BOOST_ASSERT(current_edge_target_coordinate_id != current_edge_source_coordinate_id);
// build edges
m_edge_based_node_list.emplace_back(forward_data.way_id,
reverse_data.way_id,
forward_data.edgeBasedNodeID,
m_edge_based_node_list.emplace_back(forward_data.edgeBasedNodeID,
reverse_data.edgeBasedNodeID,
current_edge_source_coordinate_id,
current_edge_target_coordinate_id,
forward_data.nameID,
forward_geometry[i].second,
reverse_geometry[i].second,
reverse_geometry[geometry_size - 1 - i].second,
forward_dist_prefix_sum[i],
reverse_dist_prefix_sum[i],
m_geometry_compressor.GetPositionForID(e1),
i,
belongs_to_tiny_cc);
belongs_to_tiny_cc,
forward_data.travel_mode,
reverse_data.travel_mode);
current_edge_source_coordinate_id = current_edge_target_coordinate_id;
BOOST_ASSERT(m_edge_based_node_list.back().IsCompressed());
BOOST_ASSERT(u != m_edge_based_node_list.back().u ||
v != m_edge_based_node_list.back().v);
BOOST_ASSERT(node_u != m_edge_based_node_list.back().u ||
node_v != m_edge_based_node_list.back().v);
BOOST_ASSERT(u != m_edge_based_node_list.back().v ||
v != m_edge_based_node_list.back().u);
BOOST_ASSERT(node_u != m_edge_based_node_list.back().v ||
node_v != m_edge_based_node_list.back().u);
}
BOOST_ASSERT(current_edge_source_coordinate_id == v);
BOOST_ASSERT(current_edge_source_coordinate_id == node_v);
BOOST_ASSERT(m_edge_based_node_list.back().IsCompressed());
}
else
@ -229,12 +223,10 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const
BOOST_ASSERT(forward_data.edgeBasedNodeID != SPECIAL_NODEID ||
reverse_data.edgeBasedNodeID != SPECIAL_NODEID);
m_edge_based_node_list.emplace_back(forward_data.way_id,
reverse_data.way_id,
forward_data.edgeBasedNodeID,
m_edge_based_node_list.emplace_back(forward_data.edgeBasedNodeID,
reverse_data.edgeBasedNodeID,
u,
v,
node_u,
node_v,
forward_data.nameID,
forward_data.distance,
reverse_data.distance,
@ -242,7 +234,9 @@ EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID u, const NodeID v, const
0,
SPECIAL_EDGEID,
0,
belongs_to_tiny_cc);
belongs_to_tiny_cc,
forward_data.travel_mode,
reverse_data.travel_mode);
BOOST_ASSERT(!m_edge_based_node_list.back().IsCompressed());
}
}
@ -279,11 +273,6 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename,
GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state);
TIMER_STOP(generate_edges);
TIMER_START(generate_node_data);
GenerateEdgeBasedNodeData();
TIMER_STOP(generate_node_data);
m_geometry_compressor.SerializeInternalVector(geometry_filename);
SimpleLogger().Write() << "Timing statistics for edge-expanded graph:";
@ -291,7 +280,6 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename,
SimpleLogger().Write() << "Renumbering edges: " << TIMER_SEC(renumber) << "s";
SimpleLogger().Write() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s";
SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s";
SimpleLogger().Write() << "Generating node data: " << TIMER_SEC(generate_node_data) << "s";
}
void EdgeBasedGraphFactory::CompressGeometry()
@ -301,61 +289,61 @@ void EdgeBasedGraphFactory::CompressGeometry()
const unsigned original_number_of_nodes = m_node_based_graph->GetNumberOfNodes();
const unsigned original_number_of_edges = m_node_based_graph->GetNumberOfEdges();
Percent p(original_number_of_nodes);
Percent progress(original_number_of_nodes);
unsigned removed_node_count = 0;
for (const NodeID v : osrm::irange(0u, original_number_of_nodes))
for (const NodeID node_v : osrm::irange(0u, original_number_of_nodes))
{
p.printStatus(v);
progress.printStatus(node_v);
// only contract degree 2 vertices
if (2 != m_node_based_graph->GetOutDegree(v))
if (2 != m_node_based_graph->GetOutDegree(node_v))
{
continue;
}
// don't contract barrier node
if (m_barrier_nodes.end() != m_barrier_nodes.find(v))
if (m_barrier_nodes.end() != m_barrier_nodes.find(node_v))
{
continue;
}
// check if v is a via node for a turn restriction, i.e. a 'directed' barrier node
if (m_restriction_map->IsViaNode(v))
if (m_restriction_map->IsViaNode(node_v))
{
continue;
}
const bool reverse_edge_order =
!(m_node_based_graph->GetEdgeData(m_node_based_graph->BeginEdges(v)).forward);
const EdgeID forward_e2 = m_node_based_graph->BeginEdges(v) + reverse_edge_order;
!(m_node_based_graph->GetEdgeData(m_node_based_graph->BeginEdges(node_v)).forward);
const EdgeID forward_e2 = m_node_based_graph->BeginEdges(node_v) + reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != forward_e2);
const EdgeID reverse_e2 = m_node_based_graph->BeginEdges(v) + 1 - reverse_edge_order;
const EdgeID reverse_e2 = m_node_based_graph->BeginEdges(node_v) + 1 - reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2);
const EdgeData &fwd_edge_data2 = m_node_based_graph->GetEdgeData(forward_e2);
const EdgeData &rev_edge_data2 = m_node_based_graph->GetEdgeData(reverse_e2);
const NodeID w = m_node_based_graph->GetTarget(forward_e2);
BOOST_ASSERT(SPECIAL_NODEID != w);
BOOST_ASSERT(v != w);
const NodeID u = m_node_based_graph->GetTarget(reverse_e2);
BOOST_ASSERT(SPECIAL_NODEID != u);
BOOST_ASSERT(u != v);
const NodeID node_w = m_node_based_graph->GetTarget(forward_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_w);
BOOST_ASSERT(node_v != node_w);
const NodeID node_u = m_node_based_graph->GetTarget(reverse_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_u);
BOOST_ASSERT(node_u != node_v);
const EdgeID forward_e1 = m_node_based_graph->FindEdge(u, v);
BOOST_ASSERT(m_node_based_graph->EndEdges(u) != forward_e1);
const EdgeID forward_e1 = m_node_based_graph->FindEdge(node_u, node_v);
BOOST_ASSERT(m_node_based_graph->EndEdges(node_u) != forward_e1);
BOOST_ASSERT(SPECIAL_EDGEID != forward_e1);
BOOST_ASSERT(v == m_node_based_graph->GetTarget(forward_e1));
const EdgeID reverse_e1 = m_node_based_graph->FindEdge(w, v);
BOOST_ASSERT(node_v == m_node_based_graph->GetTarget(forward_e1));
const EdgeID reverse_e1 = m_node_based_graph->FindEdge(node_w, node_v);
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1);
BOOST_ASSERT(v == m_node_based_graph->GetTarget(reverse_e1));
BOOST_ASSERT(node_v == m_node_based_graph->GetTarget(reverse_e1));
const EdgeData &fwd_edge_data1 = m_node_based_graph->GetEdgeData(forward_e1);
const EdgeData &rev_edge_data1 = m_node_based_graph->GetEdgeData(reverse_e1);
if ((m_node_based_graph->FindEdge(u, w) != m_node_based_graph->EndEdges(u)) ||
(m_node_based_graph->FindEdge(w, u) != m_node_based_graph->EndEdges(w)))
if ((m_node_based_graph->FindEdge(node_u, node_w) != m_node_based_graph->EndEdges(node_u)) ||
(m_node_based_graph->FindEdge(node_w, node_u) != m_node_based_graph->EndEdges(node_w)))
{
continue;
}
@ -378,7 +366,7 @@ void EdgeBasedGraphFactory::CompressGeometry()
BOOST_ASSERT(0 != forward_weight2);
const bool add_traffic_signal_penalty =
(m_traffic_lights.find(v) != m_traffic_lights.end());
(m_traffic_lights.find(node_v) != m_traffic_lights.end());
// add weight of e2's to e1
m_node_based_graph->GetEdgeData(forward_e1).distance += fwd_edge_data2.distance;
@ -386,43 +374,43 @@ void EdgeBasedGraphFactory::CompressGeometry()
if (add_traffic_signal_penalty)
{
m_node_based_graph->GetEdgeData(forward_e1).distance +=
speed_profile.trafficSignalPenalty;
speed_profile.traffic_signal_penalty;
m_node_based_graph->GetEdgeData(reverse_e1).distance +=
speed_profile.trafficSignalPenalty;
speed_profile.traffic_signal_penalty;
}
// extend e1's to targets of e2's
m_node_based_graph->SetTarget(forward_e1, w);
m_node_based_graph->SetTarget(reverse_e1, u);
m_node_based_graph->SetTarget(forward_e1, node_w);
m_node_based_graph->SetTarget(reverse_e1, node_u);
// remove e2's (if bidir, otherwise only one)
m_node_based_graph->DeleteEdge(v, forward_e2);
m_node_based_graph->DeleteEdge(v, reverse_e2);
m_node_based_graph->DeleteEdge(node_v, forward_e2);
m_node_based_graph->DeleteEdge(node_v, reverse_e2);
// update any involved turn restrictions
m_restriction_map->FixupStartingTurnRestriction(u, v, w);
m_restriction_map->FixupArrivingTurnRestriction(u, v, w);
m_restriction_map->FixupStartingTurnRestriction(node_u, node_v, node_w);
m_restriction_map->FixupArrivingTurnRestriction(node_u, node_v, node_w);
m_restriction_map->FixupStartingTurnRestriction(w, v, u);
m_restriction_map->FixupArrivingTurnRestriction(w, v, u);
m_restriction_map->FixupStartingTurnRestriction(node_w, node_v, node_u);
m_restriction_map->FixupArrivingTurnRestriction(node_w, node_v, node_u);
// store compressed geometry in container
m_geometry_compressor.CompressEdge(
forward_e1,
forward_e2,
v,
w,
node_v,
node_w,
forward_weight1 +
(add_traffic_signal_penalty ? speed_profile.trafficSignalPenalty : 0),
(add_traffic_signal_penalty ? speed_profile.traffic_signal_penalty : 0),
forward_weight2);
m_geometry_compressor.CompressEdge(
reverse_e1,
reverse_e2,
v,
u,
node_v,
node_u,
reverse_weight1,
reverse_weight2 +
(add_traffic_signal_penalty ? speed_profile.trafficSignalPenalty : 0));
(add_traffic_signal_penalty ? speed_profile.traffic_signal_penalty : 0));
++removed_node_count;
BOOST_ASSERT(m_node_based_graph->GetEdgeData(forward_e1).nameID ==
@ -451,7 +439,7 @@ void EdgeBasedGraphFactory::CompressGeometry()
}
/**
* Writes the id of the edge in the edge expanded graph (into the egde in the node based graph)
* Writes the id of the edge in the edge expanded graph (into the edge in the node based graph)
*/
void EdgeBasedGraphFactory::RenumberEdges()
{
@ -478,104 +466,6 @@ void EdgeBasedGraphFactory::RenumberEdges()
m_number_of_edge_based_nodes = numbered_edges_count;
}
void EdgeBasedGraphFactory::GenerateEdgeBasedNodeData()
{
BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() == m_node_based_graph_origin->GetNumberOfNodes());
m_edge_based_node_data.resize(m_number_of_edge_based_nodes);
std::vector<bool> found;
found.resize(m_number_of_edge_based_nodes, false);
for (NodeID current_node = 0; current_node < m_node_based_graph->GetNumberOfNodes();
++current_node)
{
for (EdgeID current_edge : m_node_based_graph->GetAdjacentEdgeRange(current_node))
{
EdgeData & edge_data = m_node_based_graph->GetEdgeData(current_edge);
if (!edge_data.forward)
{
continue;
}
NodeID target = m_node_based_graph->GetTarget(current_edge);
osrm::NodeData data;
if (m_geometry_compressor.HasEntryForID(current_edge))
{
const std::vector<GeometryCompressor::CompressedNode> & via_nodes = m_geometry_compressor.GetBucketReference(current_edge);
assert(via_nodes.size() > 0);
std::vector< std::pair< NodeID, FixedPointCoordinate > > nodes;
if (via_nodes.front().first != current_node)
nodes.emplace_back(current_node, FixedPointCoordinate(m_node_info_list[current_node].lat, m_node_info_list[current_node].lon));
for (auto n : via_nodes)
nodes.emplace_back(n.first, FixedPointCoordinate(m_node_info_list[n.first].lat, m_node_info_list[n.first].lon));
if (via_nodes.back().first != target)
nodes.emplace_back(target, FixedPointCoordinate(m_node_info_list[target].lat, m_node_info_list[target].lon));
for (uint32_t i = 1; i < nodes.size(); ++i)
{
auto n1 = nodes[i - 1];
auto n2 = nodes[i];
if (n1.first == n2.first)
{
SimpleLogger().Write() << "Error: Equal values " << n1.first << " and " << n2.first;
SimpleLogger().Write() << "i: "<< i << " nodes: " << nodes.size();
throw std::exception();
}
EdgeID e = m_node_based_graph_origin->FindEdge(n1.first, n2.first);
if (e == SPECIAL_EDGEID)
{
SimpleLogger().Write() << "Error: Can't find edge between nodes " << n1.first << " and " << n2.first;
continue;
}
EdgeData &ed = m_node_based_graph_origin->GetEdgeData(e);
data.AddSegment(ed.way_id,
m_node_info_list[n1.first].lat / COORDINATE_PRECISION,
m_node_info_list[n1.first].lon / COORDINATE_PRECISION,
m_node_info_list[n2.first].lat / COORDINATE_PRECISION,
m_node_info_list[n2.first].lon / COORDINATE_PRECISION);
}
} else
{
data.AddSegment(edge_data.way_id,
m_node_info_list[current_node].lat / COORDINATE_PRECISION,
m_node_info_list[current_node].lon / COORDINATE_PRECISION,
m_node_info_list[target].lat / COORDINATE_PRECISION,
m_node_info_list[target].lon / COORDINATE_PRECISION);
}
if (found[edge_data.edgeBasedNodeID])
{
if (m_edge_based_node_data[edge_data.edgeBasedNodeID] != data)
{
std::cout << "Error!" << std::endl;
throw std::exception();
}
} else
{
found[edge_data.edgeBasedNodeID] = true;
m_edge_based_node_data[edge_data.edgeBasedNodeID] = data;
}
}
}
for (auto v : found)
{
if (!v)
{
std::cout << "Error2" << std::endl;
throw std::exception();
}
}
SimpleLogger().Write() << "Edge based node data count: " << m_edge_based_node_data.size();
}
/**
* Creates the nodes in the edge expanded graph from edges in the node-based graph.
*/
@ -593,21 +483,17 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes()
<< " many components";
SimpleLogger().Write() << "generating edge-expanded nodes";
Percent p(m_node_based_graph->GetNumberOfNodes());
Percent progress(m_node_based_graph->GetNumberOfNodes());
// loop over all edges and generate new set of nodes
for (NodeID u = 0, end = m_node_based_graph->GetNumberOfNodes(); u < end; ++u)
{
BOOST_ASSERT(u != SPECIAL_NODEID);
BOOST_ASSERT(u < m_node_based_graph->GetNumberOfNodes());
p.printIncrement();
progress.printStatus(u);
for (EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u))
{
const EdgeData &edge_data = m_node_based_graph->GetEdgeData(e1);
// if (edge_data.edgeBasedNodeID == SPECIAL_NODEID)
// {
// continue;
// }
BOOST_ASSERT(e1 != SPECIAL_EDGEID);
const NodeID v = m_node_based_graph->GetTarget(e1);
@ -619,7 +505,6 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes()
}
BOOST_ASSERT(u < v);
BOOST_ASSERT(edge_data.type != SHRT_MAX);
// Note: edges that end on barrier nodes or on a turn restriction
// may actually be in two distinct components. We choose the smallest
@ -670,11 +555,12 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg
unsigned skipped_barrier_turns_counter = 0;
unsigned compressed = 0;
Percent p(m_node_based_graph->GetNumberOfNodes());
Percent progress(m_node_based_graph->GetNumberOfNodes());
for (NodeID u = 0, end = m_node_based_graph->GetNumberOfNodes(); u < end; ++u)
{
for (EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u))
progress.printStatus(u);
for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(u))
{
if (!m_node_based_graph->GetEdgeData(e1).forward)
{
@ -739,29 +625,31 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg
BOOST_ASSERT(edge_data1.forward);
BOOST_ASSERT(edge_data2.forward);
if (edge_data1.way_id == 244396524)
{
SimpleLogger().Write() << " - Id: " << edge_data1.way_id << " n1: " << u << " n2: " << v;
}
if (edge_data2.way_id == 244396524)
{
SimpleLogger().Write() << " - Id: " << edge_data2.way_id << " n1: " << v << " n2: " << w;
}
// the following is the core of the loop.
unsigned distance = edge_data1.distance;
if (m_traffic_lights.find(v) != m_traffic_lights.end())
{
distance += speed_profile.trafficSignalPenalty;
distance += speed_profile.traffic_signal_penalty;
}
const double angle = GetAngleBetweenThreeFixedPointCoordinates(
m_node_info_list[u], m_node_info_list[v], m_node_info_list[w]);
const int turn_penalty = GetTurnPenalty(angle, lua_state);
TurnInstruction turn_instruction = AnalyzeTurn(u, v, w, angle);
// unpack last node of first segment if packed
const auto first_coordinate = m_node_info_list[(m_geometry_compressor.HasEntryForID(e1) ?
m_geometry_compressor.GetLastNodeIDOfBucket(e1) :
u)];
// unpack first node of second segment if packed
const auto third_coordinate = m_node_info_list[(m_geometry_compressor.HasEntryForID(e2) ?
m_geometry_compressor.GetFirstNodeIDOfBucket(e2) :
w)];
const double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
first_coordinate, m_node_info_list[v], third_coordinate);
const int turn_penalty = GetTurnPenalty(turn_angle, lua_state);
TurnInstruction turn_instruction = AnalyzeTurn(u, v, w, turn_angle);
if (turn_instruction == TurnInstruction::UTurn)
{
distance += speed_profile.uTurnPenalty;
distance += speed_profile.u_turn_penalty;
}
distance += turn_penalty;
@ -776,7 +664,8 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg
(edge_is_compressed ? m_geometry_compressor.GetPositionForID(e1) : v),
edge_data1.nameID,
turn_instruction,
edge_is_compressed);
edge_is_compressed,
edge_data2.travel_mode);
++original_edges_counter;
@ -796,7 +685,6 @@ EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(const std::string &original_edg
false));
}
}
p.printIncrement();
}
FlushVectorToStream(edge_data_file, original_edge_data_vector);
@ -830,37 +718,28 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co
return 0;
}
TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u,
const NodeID v,
const NodeID w,
double angle)
TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u,
const NodeID node_v,
const NodeID node_w,
const double angle)
const
{
if (u == w)
if (node_u == node_w)
{
return TurnInstruction::UTurn;
}
const EdgeID edge1 = m_node_based_graph->FindEdge(u, v);
const EdgeID edge2 = m_node_based_graph->FindEdge(v, w);
const EdgeID edge1 = m_node_based_graph->FindEdge(node_u, node_v);
const EdgeID edge2 = m_node_based_graph->FindEdge(node_v, node_w);
const EdgeData &data1 = m_node_based_graph->GetEdgeData(edge1);
const EdgeData &data2 = m_node_based_graph->GetEdgeData(edge2);
if (!data1.contraFlow && data2.contraFlow)
{
return TurnInstruction::EnterAgainstAllowedDirection;
}
if (data1.contraFlow && !data2.contraFlow)
{
return TurnInstruction::LeaveAgainstAllowedDirection;
}
// roundabouts need to be handled explicitely
if (data1.roundabout && data2.roundabout)
{
// Is a turn possible? If yes, we stay on the roundabout!
if (1 == m_node_based_graph->GetDirectedOutDegree(v))
if (1 == m_node_based_graph->GetDirectedOutDegree(node_v))
{
// No turn possible.
return TurnInstruction::NoTurn;
@ -888,11 +767,7 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID u,
{
// TODO: Here we should also do a small graph exploration to check for
// more complex situations
if (0 != data1.nameID)
{
return TurnInstruction::NoTurn;
}
else if (m_node_based_graph->GetOutDegree(v) <= 2)
if (0 != data1.nameID || m_node_based_graph->GetOutDegree(node_v) <= 2)
{
return TurnInstruction::NoTurn;
}

View file

@ -38,7 +38,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/TurnInstructions.h"
#include "../DataStructures/NodeBasedGraph.h"
#include "../DataStructures/RestrictionMap.h"
#include "../DataStructures/EdgeBasedNodeData.h"
#include "GeometryCompressor.h"
#include <algorithm>
@ -50,7 +49,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <unordered_set>
#include <vector>
struct lua_State;
class EdgeBasedGraphFactory
@ -62,7 +60,6 @@ class EdgeBasedGraphFactory
struct SpeedProfileProperties;
explicit EdgeBasedGraphFactory(const std::shared_ptr<NodeBasedDynamicGraph> &node_based_graph,
const std::shared_ptr<NodeBasedDynamicGraph> &node_based_graph_origin,
std::unique_ptr<RestrictionMap> restricion_map,
std::vector<NodeID> &barrier_node_list,
std::vector<NodeID> &traffic_light_node_list,
@ -77,9 +74,7 @@ class EdgeBasedGraphFactory
void GetEdgeBasedNodes(std::vector<EdgeBasedNode> &nodes);
void GetEdgeBasedNodeData(osrm::NodeDataVectorT &data);
TurnInstruction AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, double angle) const;
TurnInstruction AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, const double angle) const;
int GetTurnPenalty(double angle, lua_State *lua_state) const;
@ -88,17 +83,17 @@ class EdgeBasedGraphFactory
struct SpeedProfileProperties
{
SpeedProfileProperties()
: trafficSignalPenalty(0), uTurnPenalty(0), has_turn_penalty_function(false)
: traffic_signal_penalty(0), u_turn_penalty(0), has_turn_penalty_function(false)
{
}
int trafficSignalPenalty;
int uTurnPenalty;
int traffic_signal_penalty;
int u_turn_penalty;
bool has_turn_penalty_function;
} speed_profile;
private:
typedef NodeBasedDynamicGraph::EdgeData EdgeData;
using EdgeData = NodeBasedDynamicGraph::EdgeData;
unsigned m_number_of_edge_based_nodes;
@ -107,18 +102,15 @@ class EdgeBasedGraphFactory
DeallocatingVector<EdgeBasedEdge> m_edge_based_edge_list;
std::shared_ptr<NodeBasedDynamicGraph> m_node_based_graph;
std::shared_ptr<NodeBasedDynamicGraph> m_node_based_graph_origin;
std::unordered_set<NodeID> m_barrier_nodes;
std::unordered_set<NodeID> m_traffic_lights;
std::unique_ptr<RestrictionMap> m_restriction_map;
std::vector<osrm::NodeData> m_edge_based_node_data;
GeometryCompressor m_geometry_compressor;
void CompressGeometry();
void RenumberEdges();
void GenerateEdgeBasedNodeData();
void GenerateEdgeExpandedNodes();
void GenerateEdgeExpandedEdges(const std::string &original_edge_data_filename,
lua_State *lua_state);
@ -128,7 +120,7 @@ class EdgeBasedGraphFactory
void FlushVectorToStream(std::ofstream &edge_data_file,
std::vector<OriginalEdgeData> &original_edge_data_vector) const;
unsigned max_id;
NodeID max_id;
};
#endif /* EDGEBASEDGRAPHFACTORY_H_ */

View file

@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "GeometryCompressor.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
@ -225,3 +225,16 @@ GeometryCompressor::GetBucketReference(const EdgeID edge_id) const
const unsigned index = m_edge_id_to_list_index_map.at(edge_id);
return m_compressed_geometries.at(index);
}
NodeID GeometryCompressor::GetFirstNodeIDOfBucket(const EdgeID edge_id) const
{
const auto &bucket = GetBucketReference(edge_id);
BOOST_ASSERT(bucket.size() >= 2);
return bucket[1].first;
}
NodeID GeometryCompressor::GetLastNodeIDOfBucket(const EdgeID edge_id) const
{
const auto &bucket = GetBucketReference(edge_id);
BOOST_ASSERT(bucket.size() >= 2);
return bucket[bucket.size()-2].first;
}

View file

@ -25,6 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GEOMETRY_COMPRESSOR_H
#define GEOMETRY_COMPRESSOR_H
#include "../typedefs.h"
#include <unordered_map>
@ -32,13 +35,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
#ifndef GEOMETRY_COMPRESSOR_H
#define GEOMETRY_COMPRESSOR_H
class GeometryCompressor
{
public:
typedef std::pair<NodeID, EdgeWeight> CompressedNode;
using CompressedNode = std::pair<NodeID, EdgeWeight>;
GeometryCompressor();
void CompressEdge(const EdgeID surviving_edge_id,
@ -54,6 +54,8 @@ class GeometryCompressor
unsigned GetPositionForID(const EdgeID edge_id) const;
const std::vector<GeometryCompressor::CompressedNode> &
GetBucketReference(const EdgeID edge_id) const;
NodeID GetFirstNodeIDOfBucket(const EdgeID edge_id) const;
NodeID GetLastNodeIDOfBucket(const EdgeID edge_id) const;
private:
void IncreaseFreeList();

View file

@ -38,8 +38,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../Util/GitDescription.h"
#include "../Util/LuaUtil.h"
#include "../Util/make_unique.hpp"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/StringUtil.h"
#include "../Util/TimingUtil.h"
#include "../typedefs.h"
@ -108,7 +109,7 @@ int Prepare::Process(int argc, char *argv[])
FingerPrint fingerprint_orig;
CheckRestrictionsFile(fingerprint_orig);
boost::filesystem::ifstream in(input_path, std::ios::in | std::ios::binary);
boost::filesystem::ifstream input_stream(input_path, std::ios::in | std::ios::binary);
node_filename = input_path.string() + ".nodes";
edge_out = input_path.string() + ".edges";
@ -116,7 +117,6 @@ int Prepare::Process(int argc, char *argv[])
graph_out = input_path.string() + ".hsgr";
rtree_nodes_path = input_path.string() + ".ramIndex";
rtree_leafs_path = input_path.string() + ".fileIndex";
node_data_filename = input_path.string() + ".nodeData";
/*** Setup Scripting Environment ***/
// Create a new lua state
@ -135,17 +135,17 @@ int Prepare::Process(int argc, char *argv[])
#ifdef WIN32
#pragma message("Memory consumption on Windows can be higher due to different bit packing")
#else
static_assert(sizeof(ImportEdge) == 24,
static_assert(sizeof(ImportEdge) == 20,
"changing ImportEdge type has influence on memory consumption!");
#endif
NodeID number_of_node_based_nodes =
readBinaryOSRMGraphFromStream(in,
readBinaryOSRMGraphFromStream(input_stream,
edge_list,
barrier_node_list,
traffic_light_list,
&internal_to_external_node_map,
restriction_list);
in.close();
input_stream.close();
if (edge_list.empty())
{
@ -162,24 +162,31 @@ int Prepare::Process(int argc, char *argv[])
DeallocatingVector<EdgeBasedEdge> edge_based_edge_list;
// init node_based_edge_list, edge_based_edge_list by edgeList
BuildEdgeExpandedGraph(lua_state,
number_of_node_based_nodes,
number_of_edge_based_nodes,
node_based_edge_list,
edge_based_edge_list,
speed_profile);
number_of_edge_based_nodes = BuildEdgeExpandedGraph(lua_state,
number_of_node_based_nodes,
node_based_edge_list,
edge_based_edge_list,
speed_profile);
lua_close(lua_state);
TIMER_STOP(expansion);
BuildRTree(node_based_edge_list);
IteratorbasedCRC32<std::vector<EdgeBasedNode>> crc32;
const unsigned node_based_edge_list_CRC32 =
crc32(node_based_edge_list.begin(), node_based_edge_list.end());
RangebasedCRC32 crc32;
if (crc32.using_hardware())
{
SimpleLogger().Write() << "using hardware based CRC32 computation";
}
else
{
SimpleLogger().Write() << "using software based CRC32 computation";
}
const unsigned crc32_value = crc32(node_based_edge_list);
node_based_edge_list.clear();
node_based_edge_list.shrink_to_fit();
SimpleLogger().Write() << "CRC32: " << node_based_edge_list_CRC32;
SimpleLogger().Write() << "CRC32: " << crc32_value;
WriteNodeMapping();
@ -188,7 +195,8 @@ int Prepare::Process(int argc, char *argv[])
*/
SimpleLogger().Write() << "initializing contractor";
Contractor *contractor = new Contractor(number_of_edge_based_nodes, edge_based_edge_list);
auto contractor =
osrm::make_unique<Contractor>(number_of_edge_based_nodes, edge_based_edge_list);
TIMER_START(contraction);
contractor->Run();
@ -198,31 +206,34 @@ int Prepare::Process(int argc, char *argv[])
DeallocatingVector<QueryEdge> contracted_edge_list;
contractor->GetEdges(contracted_edge_list);
delete contractor;
contractor.reset();
/***
* Sorting contracted edges in a way that the static query graph can read some in in-place.
*/
tbb::parallel_sort(contracted_edge_list.begin(), contracted_edge_list.end());
unsigned max_used_node_id = 0;
unsigned contracted_edge_count = contracted_edge_list.size();
const unsigned contracted_edge_count = contracted_edge_list.size();
SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count
<< " edges";
boost::filesystem::ofstream hsgr_output_stream(graph_out, std::ios::binary);
hsgr_output_stream.write((char *)&fingerprint_orig, sizeof(FingerPrint));
for (const QueryEdge &edge : contracted_edge_list)
const unsigned max_used_node_id = 1 + [&contracted_edge_list]
{
BOOST_ASSERT(UINT_MAX != edge.source);
BOOST_ASSERT(UINT_MAX != edge.target);
unsigned tmp_max = 0;
for (const QueryEdge &edge : contracted_edge_list)
{
BOOST_ASSERT(SPECIAL_NODEID != edge.source);
BOOST_ASSERT(SPECIAL_NODEID != edge.target);
tmp_max = std::max(tmp_max, edge.source);
tmp_max = std::max(tmp_max, edge.target);
}
return tmp_max;
}();
max_used_node_id = std::max(max_used_node_id, edge.source);
max_used_node_id = std::max(max_used_node_id, edge.target);
}
SimpleLogger().Write(logDEBUG) << "input graph has " << number_of_edge_based_nodes << " nodes";
SimpleLogger().Write(logDEBUG) << "contracted graph has " << max_used_node_id << " nodes";
max_used_node_id += 1;
std::vector<StaticGraph<EdgeData>::NodeArrayEntry> node_array;
node_array.resize(number_of_edge_based_nodes + 1);
@ -254,7 +265,7 @@ int Prepare::Process(int argc, char *argv[])
const unsigned node_array_size = node_array.size();
// serialize crc32, aka checksum
hsgr_output_stream.write((char *)&node_based_edge_list_CRC32, sizeof(unsigned));
hsgr_output_stream.write((char *)&crc32_value, sizeof(unsigned));
// serialize number of nodes
hsgr_output_stream.write((char *)&node_array_size, sizeof(unsigned));
// serialize number of edges
@ -462,9 +473,9 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state,
std::cerr << lua_tostring(lua_state, -1) << " occured in scripting block" << std::endl;
return false;
}
speed_profile.trafficSignalPenalty = 10 * lua_tointeger(lua_state, -1);
speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1);
SimpleLogger().Write(logDEBUG)
<< "traffic_signal_penalty: " << speed_profile.trafficSignalPenalty;
<< "traffic_signal_penalty: " << speed_profile.traffic_signal_penalty;
if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n"))
{
@ -472,7 +483,7 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state,
return false;
}
speed_profile.uTurnPenalty = 10 * lua_tointeger(lua_state, -1);
speed_profile.u_turn_penalty = 10 * lua_tointeger(lua_state, -1);
speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function");
return true;
@ -481,30 +492,25 @@ Prepare::SetupScriptingEnvironment(lua_State *lua_state,
/**
\brief Building an edge-expanded graph from node-based input and turn restrictions
*/
void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state,
NodeID number_of_node_based_nodes,
unsigned &number_of_edge_based_nodes,
std::vector<EdgeBasedNode> &node_based_edge_list,
DeallocatingVector<EdgeBasedEdge> &edge_based_edge_list,
EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile)
std::size_t
Prepare::BuildEdgeExpandedGraph(lua_State *lua_state,
NodeID number_of_node_based_nodes,
std::vector<EdgeBasedNode> &node_based_edge_list,
DeallocatingVector<EdgeBasedEdge> &edge_based_edge_list,
EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile)
{
SimpleLogger().Write() << "Generating edge-expanded graph representation";
std::shared_ptr<NodeBasedDynamicGraph> node_based_graph =
NodeBasedDynamicGraphFromImportEdges(number_of_node_based_nodes, edge_list);
std::unique_ptr<RestrictionMap> restriction_map =
std::unique_ptr<RestrictionMap>(new RestrictionMap(node_based_graph, restriction_list));
std::shared_ptr<NodeBasedDynamicGraph> node_based_graph_origin =
NodeBasedDynamicGraphFromImportEdges(number_of_node_based_nodes, edge_list);
EdgeBasedGraphFactory *edge_based_graph_factory =
new EdgeBasedGraphFactory(node_based_graph,
node_based_graph_origin,
std::move(restriction_map),
barrier_node_list,
traffic_light_list,
internal_to_external_node_map,
speed_profile);
std::shared_ptr<EdgeBasedGraphFactory> edge_based_graph_factory =
std::make_shared<EdgeBasedGraphFactory>(node_based_graph,
std::move(restriction_map),
barrier_node_list,
traffic_light_list,
internal_to_external_node_map,
speed_profile);
edge_list.clear();
edge_list.shrink_to_fit();
@ -517,7 +523,8 @@ void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state,
traffic_light_list.clear();
traffic_light_list.shrink_to_fit();
number_of_edge_based_nodes = edge_based_graph_factory->GetNumberOfEdgeBasedNodes();
const std::size_t number_of_edge_based_nodes =
edge_based_graph_factory->GetNumberOfEdgeBasedNodes();
BOOST_ASSERT(number_of_edge_based_nodes != std::numeric_limits<unsigned>::max());
#ifndef WIN32
@ -528,17 +535,10 @@ void Prepare::BuildEdgeExpandedGraph(lua_State *lua_state,
edge_based_graph_factory->GetEdgeBasedEdges(edge_based_edge_list);
edge_based_graph_factory->GetEdgeBasedNodes(node_based_edge_list);
// serialize node data
osrm::NodeDataVectorT data;
edge_based_graph_factory->GetEdgeBasedNodeData(data);
SimpleLogger().Write() << "Serialize node data";
osrm::SaveNodeDataToFile(node_data_filename, data);
delete edge_based_graph_factory;
edge_based_graph_factory.reset();
node_based_graph.reset();
return number_of_edge_based_nodes;
}
/**
@ -565,10 +565,10 @@ void Prepare::WriteNodeMapping()
Saves info to files: '.ramIndex' and '.fileIndex'.
*/
void Prepare::BuildRTree(std::vector<EdgeBasedNode> &edge_based_node_list)
void Prepare::BuildRTree(std::vector<EdgeBasedNode> &node_based_edge_list)
{
SimpleLogger().Write() << "building r-tree ...";
StaticRTree<EdgeBasedNode>(edge_based_node_list,
StaticRTree<EdgeBasedNode>(node_based_edge_list,
rtree_nodes_path.c_str(),
rtree_leafs_path.c_str(),
internal_to_external_node_map);

View file

@ -18,9 +18,9 @@
class Prepare
{
public:
typedef QueryEdge::EdgeData EdgeData;
typedef DynamicGraph<EdgeData>::InputEdge InputEdge;
typedef StaticGraph<EdgeData>::InputEdge StaticEdge;
using EdgeData = QueryEdge::EdgeData;
using InputEdge = DynamicGraph<EdgeData>::InputEdge;
using StaticEdge = StaticGraph<EdgeData>::InputEdge;
explicit Prepare();
Prepare(const Prepare &) = delete;
@ -33,12 +33,11 @@ class Prepare
void CheckRestrictionsFile(FingerPrint &fingerprint_orig);
bool SetupScriptingEnvironment(lua_State *myLuaState,
EdgeBasedGraphFactory::SpeedProfileProperties &speed_profile);
void BuildEdgeExpandedGraph(lua_State *myLuaState,
NodeID nodeBasedNodeNumber,
unsigned &nodeBasedEdgesNumber,
std::vector<EdgeBasedNode> &nodeBasedEdgeList,
DeallocatingVector<EdgeBasedEdge> &edgeBasedEdgeList,
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);
@ -63,7 +62,6 @@ class Prepare
std::string graph_out;
std::string rtree_nodes_path;
std::string rtree_leafs_path;
std::string node_data_filename;
};
#endif // PREPARE_H

View file

@ -100,8 +100,8 @@ class BinaryHeap
void operator=(const BinaryHeap &right);
public:
typedef Weight WeightType;
typedef Data DataType;
using WeightType = Weight;
using DataType = Data;
explicit BinaryHeap(size_t maxID) : node_index(maxID) { Clear(); }

View file

@ -28,8 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H
#include "../typedefs.h"
#include <boost/circular_buffer.hpp>
#include <condition_variable>
#include <mutex>

View file

@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <osrm/Coordinate.h>
#include "../Util/MercatorUtil.h"
#ifndef NDEBUG
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#endif
#include "../Util/StringUtil.h"
@ -159,11 +159,11 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s
const FixedPointCoordinate &point)
{
// initialize values
const float x_value = lat2y(point.lat / COORDINATE_PRECISION);
const float x_value = static_cast<float>(lat2y(point.lat / COORDINATE_PRECISION));
const float y_value = point.lon / COORDINATE_PRECISION;
float a = lat2y(source_coordinate.lat / COORDINATE_PRECISION);
float a = static_cast<float>(lat2y(source_coordinate.lat / COORDINATE_PRECISION));
float b = source_coordinate.lon / COORDINATE_PRECISION;
float c = lat2y(target_coordinate.lat / COORDINATE_PRECISION);
float c = static_cast<float>(lat2y(target_coordinate.lat / COORDINATE_PRECISION));
float d = target_coordinate.lon / COORDINATE_PRECISION;
float p, q;
if (std::abs(a - c) > std::numeric_limits<float>::epsilon())
@ -184,7 +184,8 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s
bool inverse_ratio = false;
// straight line segment on equator
if (std::abs(c) < std::numeric_limits<float>::epsilon() && std::abs(a) < std::numeric_limits<float>::epsilon())
if (std::abs(c) < std::numeric_limits<float>::epsilon() &&
std::abs(a) < std::numeric_limits<float>::epsilon())
{
ratio = (q - b) / (d - b);
}
@ -228,7 +229,7 @@ FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &s
ratio = 1.0f - ratio;
}
//compute the nearest location
// compute the nearest location
FixedPointCoordinate nearest_location;
BOOST_ASSERT(!std::isnan(ratio));
if (ratio <= 0.f)
@ -258,16 +259,16 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin
BOOST_ASSERT(query_location.isValid());
// initialize values
const float x = lat2y(query_location.lat / COORDINATE_PRECISION);
const float y = query_location.lon / COORDINATE_PRECISION;
const float a = lat2y(segment_source.lat / COORDINATE_PRECISION);
const float b = segment_source.lon / COORDINATE_PRECISION;
const float c = lat2y(segment_target.lat / COORDINATE_PRECISION);
const float d = segment_target.lon / COORDINATE_PRECISION;
float p, q /*,mX*/, nY;
if (std::abs(a - c) > std::numeric_limits<float>::epsilon())
const double x = lat2y(query_location.lat / COORDINATE_PRECISION);
const double y = query_location.lon / COORDINATE_PRECISION;
const double a = lat2y(segment_source.lat / COORDINATE_PRECISION);
const double b = segment_source.lon / COORDINATE_PRECISION;
const double c = lat2y(segment_target.lat / COORDINATE_PRECISION);
const double d = segment_target.lon / COORDINATE_PRECISION;
double p, q /*,mX*/, nY;
if (std::abs(a - c) > std::numeric_limits<double>::epsilon())
{
const float m = (d - b) / (c - a); // slope
const double m = (d - b) / (c - a); // slope
// Projection of (x,y) on line joining (a,b) and (c,d)
p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m);
q = b + m * (p - a);
@ -293,11 +294,11 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin
{
ratio = (segment_target == query_location ? 1.f : 0.f);
}
else if (std::abs(ratio) <= std::numeric_limits<float>::epsilon())
else if (std::abs(ratio) <= std::numeric_limits<double>::epsilon())
{
ratio = 0.;
ratio = 0.f;
}
else if (std::abs(ratio - 1.f) <= std::numeric_limits<float>::epsilon())
else if (std::abs(ratio - 1.f) <= std::numeric_limits<double>::epsilon())
{
ratio = 1.f;
}
@ -308,7 +309,7 @@ float FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordin
{
nearest_location = segment_source;
}
else if (ratio >= 1.)
else if (ratio >= 1.f)
{
nearest_location = segment_target;
}
@ -366,7 +367,8 @@ void FixedPointCoordinate::Output(std::ostream &out) const
float FixedPointCoordinate::GetBearing(const FixedPointCoordinate &first_coordinate,
const FixedPointCoordinate &second_coordinate)
{
const float lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;
const float lon_diff =
second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;
const float lon_delta = DegreeToRadian(lon_diff);
const float lat1 = DegreeToRadian(first_coordinate.lat / COORDINATE_PRECISION);
const float lat2 = DegreeToRadian(second_coordinate.lat / COORDINATE_PRECISION);
@ -408,9 +410,15 @@ float FixedPointCoordinate::GetBearing(const FixedPointCoordinate &other) const
return result;
}
float FixedPointCoordinate::DegreeToRadian(const float degree) { return degree * (static_cast<float>(M_PI) / 180.f); }
float FixedPointCoordinate::DegreeToRadian(const float degree)
{
return degree * (static_cast<float>(M_PI) / 180.f);
}
float FixedPointCoordinate::RadianToDegree(const float radian) { return radian * (180.f * static_cast<float>(M_1_PI)); }
float FixedPointCoordinate::RadianToDegree(const float radian)
{
return radian * (180.f * static_cast<float>(M_1_PI));
}
// This distance computation does integer arithmetic only and is a lot faster than
// the other distance function which are numerically correct('ish).
@ -421,11 +429,11 @@ int FixedPointCoordinate::OrderedPerpendicularDistanceApproximation(
const FixedPointCoordinate &segment_target)
{
// initialize values
const float x = lat2y(input_point.lat / COORDINATE_PRECISION);
const float x = static_cast<float>(lat2y(input_point.lat / COORDINATE_PRECISION));
const float y = input_point.lon / COORDINATE_PRECISION;
const float a = lat2y(segment_source.lat / COORDINATE_PRECISION);
const float a = static_cast<float>(lat2y(segment_source.lat / COORDINATE_PRECISION));
const float b = segment_source.lon / COORDINATE_PRECISION;
const float c = lat2y(segment_target.lat / COORDINATE_PRECISION);
const float c = static_cast<float>(lat2y(segment_target.lat / COORDINATE_PRECISION));
const float d = segment_target.lon / COORDINATE_PRECISION;
float p, q;

View file

@ -165,11 +165,11 @@ class DeallocatingVector
std::vector<ElementT *> bucket_list;
public:
typedef DeallocatingVectorIterator<ElementT, ELEMENTS_PER_BLOCK> iterator;
typedef DeallocatingVectorIterator<ElementT, ELEMENTS_PER_BLOCK> const_iterator;
using iterator = DeallocatingVectorIterator<ElementT, ELEMENTS_PER_BLOCK>;
using const_iterator = DeallocatingVectorIterator<ElementT, ELEMENTS_PER_BLOCK>;
// this forward-only iterator deallocates all buckets that have been visited
typedef DeallocatingVectorRemoveIterator<ElementT, ELEMENTS_PER_BLOCK> deallocation_iterator;
using deallocation_iterator = DeallocatingVectorRemoveIterator<ElementT, ELEMENTS_PER_BLOCK>;
DeallocatingVector() : current_size(0) { bucket_list.emplace_back(new ElementT[ELEMENTS_PER_BLOCK]); }

View file

@ -43,10 +43,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
template <typename EdgeDataT> class DynamicGraph
{
public:
typedef EdgeDataT EdgeData;
typedef unsigned NodeIterator;
typedef unsigned EdgeIterator;
typedef osrm::range<EdgeIterator> EdgeRange;
using EdgeData = EdgeDataT;
using NodeIterator = unsigned;
using EdgeIterator = unsigned;
using EdgeRange = osrm::range<EdgeIterator>;
class InputEdge
{
@ -71,7 +71,7 @@ template <typename EdgeDataT> class DynamicGraph
};
// Constructs an empty graph with a given number of nodes.
explicit DynamicGraph(int32_t nodes) : number_of_nodes(nodes), number_of_edges(0)
explicit DynamicGraph(NodeIterator nodes) : number_of_nodes(nodes), number_of_edges(0)
{
node_list.reserve(number_of_nodes);
node_list.resize(number_of_nodes);
@ -80,7 +80,7 @@ template <typename EdgeDataT> class DynamicGraph
edge_list.resize(number_of_nodes);
}
template <class ContainerT> DynamicGraph(const int32_t nodes, const ContainerT &graph)
template <class ContainerT> DynamicGraph(const NodeIterator nodes, const ContainerT &graph)
{
number_of_nodes = nodes;
number_of_edges = (EdgeIterator)graph.size();

View file

@ -1,10 +1,10 @@
#ifndef EDGE_BASED_NODE_H
#define EDGE_BASED_NODE_H
#include "../Util/SimpleLogger.h"
#include "../DataStructures/TravelMode.h"
#include "../typedefs.h"
#include "../Include/osrm/Coordinate.h"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
@ -14,8 +14,6 @@ struct EdgeBasedNode
{
EdgeBasedNode() :
forward_way_id(-1),
reverse_way_id(-1),
forward_edge_based_node_id(SPECIAL_NODEID),
reverse_edge_based_node_id(SPECIAL_NODEID),
u(SPECIAL_NODEID),
@ -27,12 +25,12 @@ struct EdgeBasedNode
reverse_offset(0),
packed_geometry_id(SPECIAL_EDGEID),
fwd_segment_position( std::numeric_limits<unsigned short>::max() ),
is_in_tiny_cc(false)
is_in_tiny_cc(false),
forward_travel_mode(TRAVEL_MODE_INACCESSIBLE),
backward_travel_mode(TRAVEL_MODE_INACCESSIBLE)
{ }
explicit EdgeBasedNode(
unsigned forward_way_id,
unsigned reverse_way_id,
NodeID forward_edge_based_node_id,
NodeID reverse_edge_based_node_id,
NodeID u,
@ -44,10 +42,10 @@ struct EdgeBasedNode
int reverse_offset,
unsigned packed_geometry_id,
unsigned short fwd_segment_position,
bool belongs_to_tiny_component
bool belongs_to_tiny_component,
TravelMode forward_travel_mode,
TravelMode backward_travel_mode
) :
forward_way_id(forward_way_id),
reverse_way_id(reverse_way_id),
forward_edge_based_node_id(forward_edge_based_node_id),
reverse_edge_based_node_id(reverse_edge_based_node_id),
u(u),
@ -59,7 +57,9 @@ struct EdgeBasedNode
reverse_offset(reverse_offset),
packed_geometry_id(packed_geometry_id),
fwd_segment_position(fwd_segment_position),
is_in_tiny_cc(belongs_to_tiny_component)
is_in_tiny_cc(belongs_to_tiny_component),
forward_travel_mode(forward_travel_mode),
backward_travel_mode(backward_travel_mode)
{
BOOST_ASSERT((forward_edge_based_node_id != SPECIAL_NODEID) ||
(reverse_edge_based_node_id != SPECIAL_NODEID));
@ -79,8 +79,6 @@ struct EdgeBasedNode
return packed_geometry_id != SPECIAL_EDGEID;
}
unsigned forward_way_id;
unsigned reverse_way_id;
NodeID forward_edge_based_node_id; // needed for edge-expanded graph
NodeID reverse_edge_based_node_id; // needed for edge-expanded graph
NodeID u; // indices into the coordinates array
@ -93,6 +91,8 @@ struct EdgeBasedNode
unsigned packed_geometry_id; // if set, then the edge represents a packed geometry
unsigned short fwd_segment_position; // segment id in a compressed geometry
bool is_in_tiny_cc;
TravelMode forward_travel_mode : 4;
TravelMode backward_travel_mode : 4;
};
#endif //EDGE_BASED_NODE_H

View file

@ -1,123 +0,0 @@
#pragma once
#include <stdint.h>
#include <vector>
#include <fstream>
namespace osrm
{
struct NodeData
{
#pragma pack (push, 1)
struct SegmentInfo
{
uint64_t wayId;
double lat1, lon1, lat2, lon2;
SegmentInfo()
: wayId(-1), lat1(-10000), lon1(-10000), lat2(-10000), lon2(-10000)
{
}
SegmentInfo(uint64_t wayId, double lat1, double lon1, double lat2, double lon2)
: wayId(wayId), lat1(lat1), lon1(lon1), lat2(lat2), lon2(lon2)
{
}
bool operator != (SegmentInfo const & other) const
{
return wayId != other.wayId || lat1 != other.lat1 || lon1 != other.lon1 ||
lat2 != other.lat2 || lon2 != other.lon2;
}
};
#pragma pack (pop)
typedef std::vector<SegmentInfo> SegmentInfoVectorT;
SegmentInfoVectorT m_segments;
NodeData()
{
}
NodeData(SegmentInfoVectorT & vec)
{
m_segments.swap(vec);
}
bool operator == (NodeData const & other) const
{
if (m_segments.size() != other.m_segments.size())
return false;
for (uint32_t i = 0; i < m_segments.size(); ++i)
if (m_segments[i] != other.m_segments[i])
return false;
return true;
}
bool operator != (NodeData const & other) const
{
return !(*this == other);
}
void AddSegment(uint64_t wayId, double lat1, double lon1, double lat2, double lon2)
{
m_segments.emplace_back(wayId, lat1, lon1, lat2, lon2);
}
void SetSegments(SegmentInfoVectorT & segments)
{
m_segments.swap(segments);
}
};
typedef std::vector<NodeData> NodeDataVectorT;
inline bool SaveNodeDataToFile(std::string const & filename, NodeDataVectorT const & data)
{
std::ofstream stream;
stream.open(filename);
if (!stream.is_open())
return false;
uint32_t count = data.size();
stream.write((char*)&count, sizeof(count));
for (auto d : data)
{
uint32_t pc = d.m_segments.size();
stream.write((char*)&pc, sizeof(pc));
stream.write((char*)d.m_segments.data(), sizeof(NodeData::SegmentInfo) * pc);
}
stream.close();
return true;
}
inline bool LoadNodeDataFromFile(std::string const & filename, NodeDataVectorT & data)
{
std::ifstream stream;
stream.open(filename);
if (!stream.is_open())
return false;
uint32_t count = 0;
stream.read((char*)&count, sizeof(count));
for (uint32_t i = 0; i < count; ++i)
{
uint32_t pc;
stream.read((char*)&pc, sizeof(pc));
NodeData::SegmentInfoVectorT segments;
segments.resize(pc);
stream.read((char*)segments.data(), sizeof(NodeData::SegmentInfo) * pc);
data.emplace_back(segments);
}
stream.close();
return true;
}
}

View file

@ -0,0 +1,216 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSRM_FIXED_POINT_NUMBER_H
#define OSRM_FIXED_POINT_NUMBER_H
#include <cmath>
#include <cstdint>
#include <iostream>
#include <limits>
#include <type_traits>
#include <utility>
namespace osrm
{
// implements an binary based fixed point number type
template <unsigned FractionalBitSize,
bool use_64_bits = false,
bool is_unsigned = false,
bool truncate_results = false>
class FixedPointNumber
{
static_assert(FractionalBitSize > 0, "FractionalBitSize must be greater than 0");
static_assert(FractionalBitSize <= 32, "FractionalBitSize must at most 32");
typename std::conditional<use_64_bits, int64_t, int32_t>::type m_fixed_point_state;
constexpr static const decltype(m_fixed_point_state) PRECISION = 1 << FractionalBitSize;
// state signage encapsulates whether the state should either represent a
// signed or an unsigned floating point number
using state_signage =
typename std::conditional<is_unsigned,
typename std::make_unsigned<decltype(m_fixed_point_state)>::type,
decltype(m_fixed_point_state)>::type;
public:
FixedPointNumber() : m_fixed_point_state(0) {}
// the type is either initialized with a floating point value or an
// integral state. Anything else will throw at compile-time.
template <class T>
constexpr FixedPointNumber(const T &&input) noexcept
: m_fixed_point_state(static_cast<decltype(m_fixed_point_state)>(
std::round(std::forward<const T>(input) * PRECISION)))
{
static_assert(
std::is_floating_point<T>::value || std::is_integral<T>::value,
"FixedPointNumber needs to be initialized with floating point or integral value");
}
// get max value
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
constexpr static auto max() noexcept -> T
{
return static_cast<T>(std::numeric_limits<state_signage>::max()) / PRECISION;
}
// get min value
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
constexpr static auto min() noexcept -> T
{
return static_cast<T>(1) / PRECISION;
}
// get lowest value
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
constexpr static auto lowest() noexcept -> T
{
return static_cast<T>(std::numeric_limits<state_signage>::min()) / PRECISION;
}
// cast to floating point type T, return value
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
explicit operator const T() const noexcept
{
// casts to external type (signed or unsigned) and then to float
return static_cast<T>(static_cast<state_signage>(m_fixed_point_state)) / PRECISION;
}
// warn about cast to integral type T, its disabled for good reason
template <typename T, typename std::enable_if<std::is_integral<T>::value>::type * = nullptr>
explicit operator T() const
{
static_assert(std::is_integral<T>::value,
"casts to integral types have been disabled on purpose");
}
// compare, ie. sort fixed-point numbers
bool operator<(const FixedPointNumber &other) const noexcept
{
return m_fixed_point_state < other.m_fixed_point_state;
}
// equality, ie. sort fixed-point numbers
bool operator==(const FixedPointNumber &other) const noexcept
{
return m_fixed_point_state == other.m_fixed_point_state;
}
bool operator!=(const FixedPointNumber &other) const { return !(*this == other); }
bool operator>(const FixedPointNumber &other) const { return other < *this; }
bool operator<=(const FixedPointNumber &other) const { return !(other < *this); }
bool operator>=(const FixedPointNumber &other) const { return !(*this < other); }
// arithmetic operators
FixedPointNumber operator+(const FixedPointNumber &other) const noexcept
{
FixedPointNumber tmp = *this;
tmp.m_fixed_point_state += other.m_fixed_point_state;
return tmp;
}
FixedPointNumber &operator+=(const FixedPointNumber &other) noexcept
{
this->m_fixed_point_state += other.m_fixed_point_state;
return *this;
}
FixedPointNumber operator-(const FixedPointNumber &other) const noexcept
{
FixedPointNumber tmp = *this;
tmp.m_fixed_point_state -= other.m_fixed_point_state;
return tmp;
}
FixedPointNumber &operator-=(const FixedPointNumber &other) noexcept
{
this->m_fixed_point_state -= other.m_fixed_point_state;
return *this;
}
FixedPointNumber operator*(const FixedPointNumber &other) const noexcept
{
int64_t temp = this->m_fixed_point_state;
temp *= other.m_fixed_point_state;
// rounding!
if (!truncate_results)
{
temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1);
}
temp >>= FractionalBitSize;
FixedPointNumber tmp;
tmp.m_fixed_point_state = static_cast<decltype(m_fixed_point_state)>(temp);
return tmp;
}
FixedPointNumber &operator*=(const FixedPointNumber &other) noexcept
{
int64_t temp = this->m_fixed_point_state;
temp *= other.m_fixed_point_state;
// rounding!
if (!truncate_results)
{
temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1);
}
temp >>= FractionalBitSize;
this->m_fixed_point_state = static_cast<decltype(m_fixed_point_state)>(temp);
return *this;
}
FixedPointNumber operator/(const FixedPointNumber &other) const noexcept
{
int64_t temp = this->m_fixed_point_state;
temp <<= FractionalBitSize;
temp /= static_cast<int64_t>(other.m_fixed_point_state);
FixedPointNumber tmp;
tmp.m_fixed_point_state = static_cast<decltype(m_fixed_point_state)>(temp);
return tmp;
}
FixedPointNumber &operator/=(const FixedPointNumber &other) noexcept
{
int64_t temp = this->m_fixed_point_state;
temp <<= FractionalBitSize;
temp /= static_cast<int64_t>(other.m_fixed_point_state);
FixedPointNumber tmp;
this->m_fixed_point_state = static_cast<decltype(m_fixed_point_state)>(temp);
return *this;
}
};
static_assert(4 == sizeof(FixedPointNumber<1>), "FP19 has wrong size != 4");
}
#endif // OSRM_FIXED_POINT_NUMBER_H

View file

@ -34,7 +34,7 @@ template <typename Key, typename Value>
class HashTable
{
private:
typedef std::pair<Key, Value> KeyValPair;
using KeyValPair = std::pair<Key, Value>;
std::vector<KeyValPair> table;
public:

View file

@ -46,24 +46,21 @@ bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const
return source < other.source;
}
NodeBasedEdge::NodeBasedEdge(unsigned way_id,
NodeID source,
NodeBasedEdge::NodeBasedEdge(NodeID source,
NodeID target,
NodeID name_id,
EdgeWeight weight,
bool forward,
bool backward,
short type,
bool roundabout,
bool in_tiny_cc,
bool access_restricted,
bool contra_flow,
TravelMode travel_mode,
bool is_split)
: way_id(way_id), source(source), target(target), name_id(name_id), weight(weight), type(type),
: source(source), target(target), name_id(name_id), weight(weight),
forward(forward), backward(backward), roundabout(roundabout), in_tiny_cc(in_tiny_cc),
access_restricted(access_restricted), contra_flow(contra_flow), is_split(is_split)
access_restricted(access_restricted), is_split(is_split), travel_mode(travel_mode)
{
BOOST_ASSERT_MSG(type > 0, "negative edge type");
}
bool EdgeBasedEdge::operator<(const EdgeBasedEdge &other) const

View file

@ -28,39 +28,36 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef IMPORT_EDGE_H
#define IMPORT_EDGE_H
#include "../DataStructures/TravelMode.h"
#include "../typedefs.h"
struct NodeBasedEdge
{
bool operator<(const NodeBasedEdge &e) const;
explicit NodeBasedEdge(unsigned way_id,
NodeID source,
explicit NodeBasedEdge(NodeID source,
NodeID target,
NodeID name_id,
EdgeWeight weight,
bool forward,
bool backward,
short type,
bool roundabout,
bool in_tiny_cc,
bool access_restricted,
bool contra_flow,
TravelMode travel_mode,
bool is_split);
unsigned way_id;
NodeID source;
NodeID target;
NodeID name_id;
EdgeWeight weight;
short type;
bool forward : 1;
bool backward : 1;
bool roundabout : 1;
bool in_tiny_cc : 1;
bool access_restricted : 1;
bool contra_flow : 1;
bool is_split : 1;
TravelMode travel_mode : 4;
NodeBasedEdge() = delete;
};
@ -89,6 +86,6 @@ struct EdgeBasedEdge
bool backward : 1;
};
typedef NodeBasedEdge ImportEdge;
using ImportEdge = NodeBasedEdge;
#endif /* IMPORT_EDGE_H */

View file

@ -25,14 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// based on https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp
// based on
// https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp
#ifndef JSON_CONTAINER_H
#define JSON_CONTAINER_H
#include "../Util/StringUtil.h"
#include <boost/variant.hpp>
#include "../ThirdParty/variant/variant.hpp"
#include "../Util/cast.hpp"
#include <iostream>
#include <vector>
@ -42,21 +42,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace JSON
{
struct String;
struct Number;
struct Object;
struct Array;
struct True;
struct False;
struct Null;
typedef boost::variant<boost::recursive_wrapper<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
{
@ -73,16 +60,6 @@ struct Number
double value;
};
struct Object
{
std::unordered_map<std::string, Value> values;
};
struct Array
{
std::vector<Value> values;
};
struct True
{
};
@ -95,9 +72,27 @@ struct Null
{
};
struct Renderer : boost::static_visitor<>
using Value = mapbox::util::variant<String,
Number,
mapbox::util::recursive_wrapper<Object>,
mapbox::util::recursive_wrapper<Array>,
True,
False,
Null>;
struct Object
{
Renderer(std::ostream &_out) : out(_out) {}
std::unordered_map<std::string, Value> values;
};
struct Array
{
std::vector<Value> values;
};
struct Renderer : mapbox::util::static_visitor<>
{
explicit Renderer(std::ostream &_out) : out(_out) {}
void operator()(const String &string) const { out << "\"" << string.value << "\""; }
@ -114,7 +109,7 @@ struct Renderer : boost::static_visitor<>
while (iterator != object.values.end())
{
out << "\"" << (*iterator).first << "\":";
boost::apply_visitor(Renderer(out), (*iterator).second);
mapbox::util::apply_visitor(Renderer(out), (*iterator).second);
if (++iterator != object.values.end())
{
out << ",";
@ -130,7 +125,7 @@ struct Renderer : boost::static_visitor<>
iterator = array.values.begin();
while (iterator != array.values.end())
{
boost::apply_visitor(Renderer(out), *iterator);
mapbox::util::apply_visitor(Renderer(out), *iterator);
if (++iterator != array.values.end())
{
out << ",";
@ -149,11 +144,12 @@ struct Renderer : boost::static_visitor<>
std::ostream &out;
};
struct ArrayRenderer : boost::static_visitor<>
struct ArrayRenderer : mapbox::util::static_visitor<>
{
ArrayRenderer(std::vector<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 +157,7 @@ struct ArrayRenderer : boost::static_visitor<>
void operator()(const Number &number) const
{
const std::string number_string = FixedDoubleToString(number.value);
const std::string number_string = cast::double_fixed_to_string(number.value);
out.insert(out.end(), number_string.begin(), number_string.end());
}
@ -176,7 +172,7 @@ struct ArrayRenderer : boost::static_visitor<>
out.push_back('\"');
out.push_back(':');
boost::apply_visitor(ArrayRenderer(out), (*iterator).second);
mapbox::util::apply_visitor(ArrayRenderer(out), (*iterator).second);
if (++iterator != object.values.end())
{
out.push_back(',');
@ -192,7 +188,7 @@ struct ArrayRenderer : boost::static_visitor<>
iterator = array.values.begin();
while (iterator != array.values.end())
{
boost::apply_visitor(ArrayRenderer(out), *iterator);
mapbox::util::apply_visitor(ArrayRenderer(out), *iterator);
if (++iterator != array.values.end())
{
out.push_back(',');
@ -201,17 +197,20 @@ struct ArrayRenderer : boost::static_visitor<>
out.push_back(']');
}
void operator()(const True &) const {
void operator()(const True &) const
{
const std::string temp("true");
out.insert(out.end(), temp.begin(), temp.end());
}
void operator()(const False &) const {
void operator()(const False &) const
{
const std::string temp("false");
out.insert(out.end(), temp.begin(), temp.end());
}
void operator()(const Null &) const {
void operator()(const Null &) const
{
const std::string temp("null");
out.insert(out.end(), temp.begin(), temp.end());
}
@ -223,13 +222,13 @@ struct ArrayRenderer : boost::static_visitor<>
inline void render(std::ostream &out, const Object &object)
{
Value value = object;
boost::apply_visitor(Renderer(out), value);
mapbox::util::apply_visitor(Renderer(out), value);
}
inline void render(std::vector<char> &out, const Object &object)
{
Value value = object;
boost::apply_visitor(ArrayRenderer(out), value);
mapbox::util::apply_visitor(ArrayRenderer(out), value);
}
} // namespace JSON

View file

@ -1,9 +1,9 @@
#ifndef __NODE_BASED_GRAPH_H__
#define __NODE_BASED_GRAPH_H__
#ifndef NODE_BASED_GRAPH_H_
#define NODE_BASED_GRAPH_H_
#include "DynamicGraph.h"
#include "ImportEdge.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include <tbb/parallel_sort.h>
@ -12,25 +12,23 @@
struct NodeBasedEdgeData
{
NodeBasedEdgeData()
: way_id(-1), distance(INVALID_EDGE_WEIGHT), edgeBasedNodeID(SPECIAL_NODEID),
nameID(std::numeric_limits<unsigned>::max()), type(std::numeric_limits<short>::max()),
: distance(INVALID_EDGE_WEIGHT), edgeBasedNodeID(SPECIAL_NODEID),
nameID(std::numeric_limits<unsigned>::max()),
isAccessRestricted(false), shortcut(false), forward(false), backward(false),
roundabout(false), ignore_in_grid(false), contraFlow(false)
roundabout(false), ignore_in_grid(false), travel_mode(TRAVEL_MODE_INACCESSIBLE)
{
}
unsigned way_id;
int distance;
unsigned edgeBasedNodeID;
unsigned nameID;
short type;
bool isAccessRestricted : 1;
bool shortcut : 1;
bool forward : 1;
bool backward : 1;
bool roundabout : 1;
bool ignore_in_grid : 1;
bool contraFlow : 1;
TravelMode travel_mode : 4;
void SwapDirectionFlags()
{
@ -43,7 +41,7 @@ struct NodeBasedEdgeData
{
return (forward == other.forward) && (backward == other.backward) &&
(nameID == other.nameID) && (ignore_in_grid == other.ignore_in_grid) &&
(contraFlow == other.contraFlow);
(travel_mode == other.travel_mode);
}
};
@ -53,14 +51,14 @@ struct SimpleEdgeData
EdgeWeight capacity;
};
typedef DynamicGraph<NodeBasedEdgeData> NodeBasedDynamicGraph;
typedef DynamicGraph<SimpleEdgeData> SimpleNodeBasedDynamicGraph;
using NodeBasedDynamicGraph = DynamicGraph<NodeBasedEdgeData>;
using SimpleNodeBasedDynamicGraph = DynamicGraph<SimpleEdgeData>;
// Factory method to create NodeBasedDynamicGraph from ImportEdges
inline std::shared_ptr<NodeBasedDynamicGraph>
NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector<ImportEdge> &input_edge_list)
{
static_assert(sizeof(NodeBasedEdgeData) == 20, "changing node based edge data size changes memory consumption");
static_assert(sizeof(NodeBasedEdgeData) == 16, "changing node based edge data size changes memory consumption");
DeallocatingVector<NodeBasedDynamicGraph::InputEdge> edges_list;
NodeBasedDynamicGraph::InputEdge edge;
@ -81,8 +79,6 @@ NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector<ImportEdge
edge.data.forward = import_edge.backward;
}
edge.data.way_id = import_edge.way_id;
if (edge.source == edge.target)
{
continue;
@ -94,9 +90,9 @@ NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector<ImportEdge
edge.data.roundabout = import_edge.roundabout;
edge.data.ignore_in_grid = import_edge.in_tiny_cc;
edge.data.nameID = import_edge.name_id;
edge.data.type = import_edge.type;
edge.data.isAccessRestricted = import_edge.access_restricted;
edge.data.contraFlow = import_edge.contra_flow;
edge.data.travel_mode = import_edge.travel_mode;
edges_list.push_back(edge);
if (!import_edge.is_split)
@ -168,7 +164,7 @@ NodeBasedDynamicGraphFromImportEdges(int number_of_nodes, std::vector<ImportEdge
edges_list.resize(edge_count);
SimpleLogger().Write() << "merged " << edges_list.size() - edge_count << " edges out of " << edges_list.size();
auto graph = std::make_shared<NodeBasedDynamicGraph>(number_of_nodes, edges_list);
auto graph = std::make_shared<NodeBasedDynamicGraph>(static_cast<NodeBasedDynamicGraph::NodeIterator>(number_of_nodes), edges_list);
return graph;
}
@ -176,7 +172,7 @@ template<class SimpleEdgeT>
inline std::shared_ptr<SimpleNodeBasedDynamicGraph>
SimpleNodeBasedDynamicGraphFromEdges(int number_of_nodes, std::vector<SimpleEdgeT> &input_edge_list)
{
static_assert(sizeof(NodeBasedEdgeData) == 20, "changing node based edge data size changes memory consumption");
static_assert(sizeof(NodeBasedEdgeData) == 16, "changing node based edge data size changes memory consumption");
tbb::parallel_sort(input_edge_list.begin(), input_edge_list.end());
DeallocatingVector<SimpleNodeBasedDynamicGraph::InputEdge> edges_list;
@ -245,4 +241,4 @@ SimpleNodeBasedDynamicGraphFromEdges(int number_of_nodes, std::vector<SimpleEdge
return graph;
}
#endif // __NODE_BASED_GRAPH_H__
#endif // NODE_BASED_GRAPH_H_

View file

@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define ORIGINAL_EDGE_DATA_H
#include "TurnInstructions.h"
#include "../DataStructures/TravelMode.h"
#include "../typedefs.h"
#include <limits>
@ -38,16 +39,18 @@ struct OriginalEdgeData
explicit OriginalEdgeData(NodeID via_node,
unsigned name_id,
TurnInstruction turn_instruction,
bool compressed_geometry)
bool compressed_geometry,
TravelMode travel_mode)
: via_node(via_node), name_id(name_id), turn_instruction(turn_instruction),
compressed_geometry(compressed_geometry)
compressed_geometry(compressed_geometry), travel_mode(travel_mode)
{
}
OriginalEdgeData()
: via_node(std::numeric_limits<unsigned>::max()),
name_id(std::numeric_limits<unsigned>::max()),
turn_instruction(TurnInstruction::NoTurn), compressed_geometry(false)
turn_instruction(TurnInstruction::NoTurn), compressed_geometry(false),
travel_mode(TRAVEL_MODE_INACCESSIBLE)
{
}
@ -55,6 +58,7 @@ struct OriginalEdgeData
unsigned name_id;
TurnInstruction turn_instruction;
bool compressed_geometry;
TravelMode travel_mode;
};
#endif // ORIGINAL_EDGE_DATA_H

View file

@ -28,8 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef PHANTOM_NODES_H
#define PHANTOM_NODES_H
#include "../Include/osrm/Coordinate.h"
#include "../Util/SimpleLogger.h"
#include <osrm/Coordinate.h>
#include "../DataStructures/TravelMode.h"
#include "../Util/simple_logger.hpp"
#include "../typedefs.h"
#include <vector>
@ -39,7 +40,8 @@ struct PhantomNode
PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id,
int forward_weight, int reverse_weight, int forward_offset, int reverse_offset,
unsigned packed_geometry_id, FixedPointCoordinate &location,
unsigned short fwd_segment_position) :
unsigned short fwd_segment_position,
TravelMode forward_travel_mode, TravelMode backward_travel_mode) :
forward_node_id(forward_node_id),
reverse_node_id(reverse_node_id),
name_id(name_id),
@ -49,7 +51,9 @@ struct PhantomNode
reverse_offset(reverse_offset),
packed_geometry_id(packed_geometry_id),
location(location),
fwd_segment_position(fwd_segment_position)
fwd_segment_position(fwd_segment_position),
forward_travel_mode(forward_travel_mode),
backward_travel_mode(backward_travel_mode)
{ }
PhantomNode() :
@ -61,7 +65,9 @@ struct PhantomNode
forward_offset(0),
reverse_offset(0),
packed_geometry_id(SPECIAL_EDGEID),
fwd_segment_position(0)
fwd_segment_position(0),
forward_travel_mode(TRAVEL_MODE_INACCESSIBLE),
backward_travel_mode(TRAVEL_MODE_INACCESSIBLE)
{ }
NodeID forward_node_id;
@ -74,6 +80,8 @@ struct PhantomNode
unsigned packed_geometry_id;
FixedPointCoordinate location;
unsigned short fwd_segment_position;
TravelMode forward_travel_mode : 4;
TravelMode backward_travel_mode : 4;
int GetForwardWeightPlusOffset() const
{
@ -134,7 +142,7 @@ struct PhantomNode
}
};
typedef std::vector<std::vector<PhantomNode>> PhantomNodeArray;
using PhantomNodeArray = std::vector<std::vector<PhantomNode>>;
struct PhantomNodeLists
{

View file

@ -30,7 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../typedefs.h"
#include "../Include/osrm/Coordinate.h"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
@ -38,8 +38,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
struct NodeInfo
{
typedef NodeID key_type; // type of NodeID
typedef int value_type; // type of lat,lons
using key_type = NodeID; // type of NodeID
using value_type = int; // type of lat,lons
explicit NodeInfo(int lat, int lon, NodeID node_id) : lat(lat), lon(lon), node_id(node_id) {}
NodeInfo()

View file

@ -1,6 +1,6 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
Copyright (c) 2013,2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@ -49,7 +49,7 @@ template <typename Integer> class range
const range &begin() const { return *this; }
const range &end() const { return *this; }
Integer front() const { return iter; }
Integer back() const { return last-1; }
Integer back() const { return last - 1; }
// Iterator functions
bool operator!=(const range &) const { return iter < last; }
@ -57,6 +57,7 @@ template <typename Integer> class range
Integer operator*() const { return iter; }
};
// convenience function to construct an integer range with type deduction
template <typename Integer> range<Integer> irange(Integer first, Integer last)
{
return range<Integer>(first, last);

View file

@ -1,5 +1,5 @@
#ifndef __RANGE_TABLE_H__
#define __RANGE_TABLE_H__
#ifndef RANGE_TABLE_H_
#define RANGE_TABLE_H_
#include "Range.h"
#include "SharedMemoryFactory.h"
@ -36,10 +36,10 @@ class RangeTable
{
public:
typedef std::array<unsigned char, BLOCK_SIZE> BlockT;
typedef typename ShM<BlockT, USE_SHARED_MEMORY>::vector BlockContainerT;
typedef typename ShM<unsigned, USE_SHARED_MEMORY>::vector OffsetContainerT;
typedef osrm::range<unsigned> RangeT;
using BlockT = std::array<unsigned char, BLOCK_SIZE>;
using BlockContainerT = typename ShM<BlockT, USE_SHARED_MEMORY>::vector;
using OffsetContainerT = typename ShM<unsigned, USE_SHARED_MEMORY>::vector;
using RangeT = osrm::range<unsigned>;
friend std::ostream& operator<< <>(std::ostream &out, const RangeTable &table);
friend std::istream& operator>> <>(std::istream &in, RangeTable &table);
@ -228,4 +228,4 @@ std::istream& operator>>(std::istream &in, RangeTable<BLOCK_SIZE, USE_SHARED_MEM
return in;
}
#endif
#endif //RANGE_TABLE_H_

View file

@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define RAW_ROUTE_DATA_H
#include "../DataStructures/PhantomNodes.h"
#include "../DataStructures/TravelMode.h"
#include "../DataStructures/TurnInstructions.h"
#include "../typedefs.h"
@ -41,18 +42,25 @@ struct PathData
PathData()
: node(SPECIAL_NODEID), name_id(INVALID_EDGE_WEIGHT),
segment_duration(INVALID_EDGE_WEIGHT),
turn_instruction(TurnInstruction::NoTurn)
turn_instruction(TurnInstruction::NoTurn),
travel_mode(TRAVEL_MODE_INACCESSIBLE)
{
}
PathData(NodeID node, unsigned name_id, TurnInstruction turn_instruction, EdgeWeight segment_duration)
: node(node), name_id(name_id), segment_duration(segment_duration), turn_instruction(turn_instruction)
PathData(NodeID node,
unsigned name_id,
TurnInstruction turn_instruction,
EdgeWeight segment_duration,
TravelMode travel_mode)
: node(node), name_id(name_id), segment_duration(segment_duration), turn_instruction(turn_instruction),
travel_mode(travel_mode)
{
}
NodeID node;
unsigned name_id;
EdgeWeight segment_duration;
TurnInstruction turn_instruction;
TravelMode travel_mode : 4;
};
struct RawRouteData
@ -69,6 +77,11 @@ struct RawRouteData
int shortest_path_length;
int alternative_path_length;
bool is_via_leg(const std::size_t leg) const
{
return (leg != unpacked_path_segments.size() - 1);
}
RawRouteData()
: check_sum(SPECIAL_NODEID),
shortest_path_length(INVALID_EDGE_WEIGHT),

View file

@ -101,7 +101,7 @@ struct InputRestrictionContainer
struct CmpRestrictionContainerByFrom
{
typedef InputRestrictionContainer value_type;
using value_type = InputRestrictionContainer;
inline bool operator()(const InputRestrictionContainer &a, const InputRestrictionContainer &b)
const
{
@ -113,7 +113,7 @@ struct CmpRestrictionContainerByFrom
struct CmpRestrictionContainerByTo
{
typedef InputRestrictionContainer value_type;
using value_type = InputRestrictionContainer;
inline bool operator()(const InputRestrictionContainer &a, const InputRestrictionContainer &b)
const
{

View file

@ -28,8 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "RestrictionMap.h"
#include "NodeBasedGraph.h"
#include "../Util/SimpleLogger.h"
bool RestrictionMap::IsViaNode(const NodeID node) const
{
return m_no_turn_via_node_set.find(node) != m_no_turn_via_node_set.end();
@ -96,9 +94,8 @@ void RestrictionMap::FixupArrivingTurnRestriction(const NodeID node_u,
std::vector<NodeID> predecessors;
for (const EdgeID current_edge_id : m_graph->GetAdjacentEdgeRange(node_u))
{
const EdgeData &edge_data = m_graph->GetEdgeData(current_edge_id);
const NodeID target = m_graph->GetTarget(current_edge_id);
if (edge_data.backward && (node_v != target))
if (node_v != target)
{
predecessors.push_back(target);
}
@ -163,11 +160,11 @@ NodeID RestrictionMap::CheckForEmanatingIsOnlyTurn(const NodeID node_u, const No
return SPECIAL_NODEID;
}
auto restriction_iter = m_restriction_map.find({node_u, node_v});
const auto restriction_iter = m_restriction_map.find({node_u, node_v});
if (restriction_iter != m_restriction_map.end())
{
const unsigned index = restriction_iter->second;
auto &bucket = m_restriction_bucket_list.at(index);
const auto &bucket = m_restriction_bucket_list.at(index);
for (const RestrictionTarget &restriction_target : bucket)
{
if (restriction_target.is_only)
@ -184,8 +181,6 @@ bool RestrictionMap::CheckIfTurnIsRestricted(const NodeID node_u,
const NodeID node_v,
const NodeID node_w) const
{
// return false;
BOOST_ASSERT(node_u != SPECIAL_NODEID);
BOOST_ASSERT(node_v != SPECIAL_NODEID);
BOOST_ASSERT(node_w != SPECIAL_NODEID);
@ -195,7 +190,7 @@ bool RestrictionMap::CheckIfTurnIsRestricted(const NodeID node_u,
return false;
}
auto restriction_iter = m_restriction_map.find({node_u, node_v});
const auto restriction_iter = m_restriction_map.find({node_u, node_v});
if (restriction_iter != m_restriction_map.end())
{
const unsigned index = restriction_iter->second;

View file

@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __RESTRICTION_MAP_H__
#define __RESTRICTION_MAP_H__
#ifndef RESTRICTION_MAP_H_
#define RESTRICTION_MAP_H_
#include <memory>
@ -110,8 +110,8 @@ class RestrictionMap
private:
bool IsSourceNode(const NodeID node) const;
typedef std::vector<RestrictionTarget> EmanatingRestrictionsVector;
typedef NodeBasedDynamicGraph::EdgeData EdgeData;
using EmanatingRestrictionsVector = std::vector<RestrictionTarget>;
using EdgeData = NodeBasedDynamicGraph::EdgeData;
std::size_t m_count;
std::shared_ptr<NodeBasedDynamicGraph> m_graph;
@ -123,4 +123,4 @@ class RestrictionMap
std::unordered_set<NodeID> m_no_turn_via_node_set;
};
#endif
#endif //RESTRICTION_MAP_H_

View file

@ -33,7 +33,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
RouteParameters::RouteParameters()
: zoom_level(18), print_instructions(false), alternate_route(true), geometry(true),
compression(true), deprecatedAPI(false), uturn_default(false), check_sum(-1)
compression(true), deprecatedAPI(false), uturn_default(false), check_sum(-1), num_results(1)
{
}
@ -45,6 +45,14 @@ void RouteParameters::setZoomLevel(const short level)
}
}
void RouteParameters::setNumberOfResults(const short number)
{
if (number > 0 && number <= 100)
{
num_results = number;
}
}
void RouteParameters::setAlternateRouteFlag(const bool flag) { alternate_route = flag; }
void RouteParameters::setUTurn(const bool flag)

View file

@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef SEARCH_ENGINE_DATA_H
#define SEARCH_ENGINE_DATA_H
#include <boost/scoped_ptr.hpp>
#include <boost/thread/tss.hpp>
#include "../typedefs.h"
#include "BinaryHeap.h"
@ -41,8 +41,8 @@ struct HeapData
struct SearchEngineData
{
typedef BinaryHeap<NodeID, NodeID, int, HeapData, UnorderedMapStorage<NodeID, int>> QueryHeap;
typedef boost::scoped_ptr<QueryHeap> SearchEngineHeapPtr;
using QueryHeap = BinaryHeap<NodeID, NodeID, int, HeapData, UnorderedMapStorage<NodeID, int>>;
using SearchEngineHeapPtr = boost::thread_specific_ptr<QueryHeap>;
static SearchEngineHeapPtr forwardHeap;
static SearchEngineHeapPtr backwardHeap;

View file

@ -30,6 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "TurnInstructions.h"
#include "../DataStructures/TravelMode.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
@ -43,8 +44,9 @@ struct SegmentInformation
float length;
short bearing; // more than enough [0..3600] fits into 12 bits
TurnInstruction turn_instruction;
bool necessary:1;
bool is_via_location:1;
TravelMode travel_mode;
bool necessary;
bool is_via_location;
explicit SegmentInformation(const FixedPointCoordinate &location,
const NodeID name_id,
@ -52,9 +54,11 @@ struct SegmentInformation
const float length,
const TurnInstruction turn_instruction,
const bool necessary,
const bool is_via_location)
const bool is_via_location,
const TravelMode travel_mode)
: location(location), name_id(name_id), duration(duration), length(length), bearing(0),
turn_instruction(turn_instruction), necessary(necessary), is_via_location(is_via_location)
turn_instruction(turn_instruction), travel_mode(travel_mode), necessary(necessary),
is_via_location(is_via_location)
{
}
@ -62,9 +66,11 @@ struct SegmentInformation
const NodeID name_id,
const EdgeWeight duration,
const float length,
const TurnInstruction turn_instruction)
const TurnInstruction turn_instruction,
const TravelMode travel_mode)
: location(location), name_id(name_id), duration(duration), length(length), bearing(0),
turn_instruction(turn_instruction), necessary(turn_instruction != TurnInstruction::NoTurn), is_via_location(false)
turn_instruction(turn_instruction), travel_mode(travel_mode),
necessary(turn_instruction != TurnInstruction::NoTurn), is_via_location(false)
{
}
};

View file

@ -29,21 +29,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define SHARED_MEMORY_FACTORY_H
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/interprocess/mapped_region.hpp>
#if !defined(WIN32) && !defined(__ANDROID__)
#ifndef WIN32
#include <boost/interprocess/xsi_shared_memory.hpp>
#else
#include <boost/interprocess/shared_memory_object.hpp>
#endif
//#ifdef __linux__
//#include <sys/ipc.h>
//#include <sys/shm.h>
//#endif
#ifdef __linux__
#include <sys/ipc.h>
#include <sys/shm.h>
#endif
// #include <cstring>
#include <cstdint>
@ -61,7 +61,7 @@ struct OSRMLockFile
}
};
#if !defined(WIN32) && !defined(__ANDROID__)
#ifndef WIN32
class SharedMemory
{
@ -196,12 +196,14 @@ class SharedMemory
};
#else
// Windows - specific code
class SharedMemory : boost::noncopyable
class SharedMemory
{
SharedMemory(const SharedMemory&) = delete;
// Remove shared memory on destruction
class shm_remove : boost::noncopyable
class shm_remove
{
private:
shm_remove(const shm_remove&) = delete;
char *m_shmid;
bool m_initialized;
@ -286,7 +288,6 @@ class SharedMemory : boost::noncopyable
private:
static void build_key(int id, char *key)
{
OSRMLockFile lock_file;
sprintf(key, "%s.%d", "osrm.lock", id);
}
@ -365,6 +366,6 @@ template <class LockFileT = OSRMLockFile> class SharedMemoryFactory_tmpl
SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete;
};
typedef SharedMemoryFactory_tmpl<> SharedMemoryFactory;
using SharedMemoryFactory = SharedMemoryFactory_tmpl<>;
#endif /* SHARED_MEMORY_POINTER_FACTORY_H */

View file

@ -28,8 +28,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef SHARED_MEMORY_VECTOR_WRAPPER_H
#define SHARED_MEMORY_VECTOR_WRAPPER_H
#include "../Util/SimpleLogger.h"
#include <boost/assert.hpp>
#include <algorithm>
@ -78,7 +76,7 @@ template <typename DataT> class SharedMemoryWrapper
void swap(SharedMemoryWrapper<DataT> &other)
{
BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid");
// BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid");
std::swap(m_size, other.m_size);
std::swap(m_ptr, other.m_ptr);
}
@ -121,7 +119,7 @@ template <> class SharedMemoryWrapper<bool>
void swap(SharedMemoryWrapper<bool> &other)
{
BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid");
// BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid");
std::swap(m_size, other.m_size);
std::swap(m_ptr, other.m_ptr);
}
@ -148,9 +146,9 @@ template <> class SharedMemoryWrapper<bool>
template <typename DataT, bool UseSharedMemory> struct ShM
{
typedef typename std::conditional<UseSharedMemory,
using vector = typename std::conditional<UseSharedMemory,
SharedMemoryWrapper<DataT>,
std::vector<DataT>>::type vector;
std::vector<DataT>>::type;
};
#endif // SHARED_MEMORY_VECTOR_WRAPPER_H

View file

@ -31,11 +31,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Percent.h"
#include "Range.h"
#include "SharedMemoryVectorWrapper.h"
#include "../Util/SimpleLogger.h"
#include "../typedefs.h"
#include <boost/assert.hpp>
#include <tbb/parallel_sort.h>
#include <algorithm>
#include <limits>
#include <utility>
@ -44,10 +45,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
template <typename EdgeDataT, bool UseSharedMemory = false> class StaticGraph
{
public:
typedef NodeID NodeIterator;
typedef NodeID EdgeIterator;
typedef EdgeDataT EdgeData;
typedef osrm::range<EdgeIterator> EdgeRange;
using NodeIterator = NodeID;
using EdgeIterator = NodeID;
using EdgeData = EdgeDataT;
using EdgeRange = osrm::range<EdgeIterator>;
class InputEdge
{
@ -87,7 +88,7 @@ template <typename EdgeDataT, bool UseSharedMemory = false> class StaticGraph
StaticGraph(const int nodes, std::vector<InputEdge> &graph)
{
std::sort(graph.begin(), graph.end());
tbb::parallel_sort(graph.begin(), graph.end());
number_of_nodes = nodes;
number_of_edges = (EdgeIterator)graph.size();
node_array.resize(number_of_nodes + 1);
@ -121,8 +122,8 @@ template <typename EdgeDataT, bool UseSharedMemory = false> class StaticGraph
StaticGraph(typename ShM<NodeArrayEntry, UseSharedMemory>::vector &nodes,
typename ShM<EdgeArrayEntry, UseSharedMemory>::vector &edges)
{
number_of_nodes = nodes.size() - 1;
number_of_edges = edges.size();
number_of_nodes = static_cast<decltype(number_of_nodes)>(nodes.size() - 1);
number_of_edges = static_cast<decltype(number_of_edges)>(edges.size());
node_array.swap(nodes);
edge_array.swap(edges);

View file

@ -211,7 +211,7 @@ class StaticKDTree
}
private:
typedef unsigned Iterator;
using Iterator = unsigned;
struct Tree
{
Iterator left;

View file

@ -35,10 +35,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SharedMemoryFactory.h"
#include "SharedMemoryVectorWrapper.h"
#include "../ThirdParty/variant/variant.hpp"
#include "../Util/floating_point.hpp"
#include "../Util/MercatorUtil.h"
#include "../Util/NumericUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../typedefs.h"
@ -48,7 +49,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/thread.hpp>
#include <boost/variant.hpp>
#include <tbb/parallel_for.h>
#include <tbb/parallel_sort.h>
#include <algorithm>
#include <array>
@ -67,7 +70,6 @@ template <class EdgeDataT,
class StaticRTree
{
public:
struct RectangleInt2D
{
RectangleInt2D() : min_lon(INT_MAX), max_lon(INT_MIN), min_lat(INT_MAX), max_lat(INT_MIN) {}
@ -252,7 +254,7 @@ class StaticRTree
}
};
typedef RectangleInt2D RectangleT;
using RectangleT = RectangleInt2D;
struct TreeNode
{
@ -305,7 +307,7 @@ class StaticRTree
}
};
typedef boost::variant<TreeNode, EdgeDataT> IncrementalQueryNodeType;
using IncrementalQueryNodeType = mapbox::util::variant<TreeNode, EdgeDataT>;
struct IncrementalQueryCandidate
{
explicit IncrementalQueryCandidate(const float dist, const IncrementalQueryNodeType &node)
@ -321,23 +323,8 @@ class StaticRTree
return other.min_dist < min_dist;
}
inline bool RepresentsTreeNode() const
{
return boost::apply_visitor(decide_type_visitor(), node);
}
float min_dist;
IncrementalQueryNodeType node;
private:
class decide_type_visitor : public boost::static_visitor<bool>
{
public:
bool operator()(const TreeNode &) const { return true; }
template<typename AnotherType>
bool operator()(const AnotherType &) const { return false; }
};
};
typename ShM<TreeNode, UseSharedMemory>::vector m_search_tree;
@ -366,33 +353,39 @@ class StaticRTree
HilbertCode get_hilbert_number;
// generate auxiliary vector of hilbert-valuesß∫
for (uint64_t element_counter = 0; element_counter != m_element_count; ++element_counter)
{
WrappedInputElement &current_wrapper = input_wrapper_vector[element_counter];
current_wrapper.m_array_index = element_counter;
// generate auxiliary vector of hilbert-values
tbb::parallel_for(
tbb::blocked_range<uint64_t>(0, m_element_count),
[&input_data_vector, &input_wrapper_vector, &get_hilbert_number, &coordinate_list](
const tbb::blocked_range<uint64_t> &range)
{
for (uint64_t element_counter = range.begin(); element_counter != range.end();
++element_counter)
{
WrappedInputElement &current_wrapper = input_wrapper_vector[element_counter];
current_wrapper.m_array_index = element_counter;
EdgeDataT const &current_element = input_data_vector[element_counter];
EdgeDataT const &current_element = input_data_vector[element_counter];
// Get Hilbert-Value for centroid in mercartor projection
FixedPointCoordinate current_centroid = EdgeDataT::Centroid(
FixedPointCoordinate(coordinate_list.at(current_element.u).lat,
coordinate_list.at(current_element.u).lon),
FixedPointCoordinate(coordinate_list.at(current_element.v).lat,
coordinate_list.at(current_element.v).lon));
current_centroid.lat =
COORDINATE_PRECISION * lat2y(current_centroid.lat / COORDINATE_PRECISION);
current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid);
}
// Get Hilbert-Value for centroid in mercartor projection
FixedPointCoordinate current_centroid = EdgeDataT::Centroid(
FixedPointCoordinate(coordinate_list.at(current_element.u).lat,
coordinate_list.at(current_element.u).lon),
FixedPointCoordinate(coordinate_list.at(current_element.v).lat,
coordinate_list.at(current_element.v).lon));
current_centroid.lat =
COORDINATE_PRECISION * lat2y(current_centroid.lat / COORDINATE_PRECISION);
current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid);
}
});
// open leaf file
boost::filesystem::ofstream leaf_node_file(leaf_node_filename, std::ios::binary);
leaf_node_file.write((char *)&m_element_count, sizeof(uint64_t));
// sort the hilbert-value representatives
sort(input_wrapper_vector.begin(), input_wrapper_vector.end());
tbb::parallel_sort(input_wrapper_vector.begin(), input_wrapper_vector.end());
std::vector<TreeNode> tree_nodes_in_level;
// pack M elements into leaf node and write to leaf file
@ -472,18 +465,22 @@ class StaticRTree
// reverse and renumber tree to have root at index 0
std::reverse(m_search_tree.begin(), m_search_tree.end());
uint32_t search_tree_size = m_search_tree.size();
for (uint32_t i = 0; i != search_tree_size; ++i)
{
TreeNode &current_tree_node = this->m_search_tree[i];
for (uint32_t j = 0; j < current_tree_node.child_count; ++j)
{
const uint32_t old_id = current_tree_node.children[j];
const uint32_t new_id = search_tree_size - old_id - 1;
current_tree_node.children[j] = new_id;
}
}
uint32_t search_tree_size = m_search_tree.size();
tbb::parallel_for(tbb::blocked_range<uint32_t>(0, search_tree_size),
[this, &search_tree_size](const tbb::blocked_range<uint32_t> &range)
{
for (uint32_t i = range.begin(); i != range.end(); ++i)
{
TreeNode &current_tree_node = this->m_search_tree[i];
for (uint32_t j = 0; j < current_tree_node.child_count; ++j)
{
const uint32_t old_id = current_tree_node.children[j];
const uint32_t new_id = search_tree_size - old_id - 1;
current_tree_node.children[j] = new_id;
}
}
});
// open tree file
boost::filesystem::ofstream tree_node_file(tree_node_filename, std::ios::binary);
@ -688,9 +685,9 @@ class StaticRTree
continue;
}
if (current_query_node.RepresentsTreeNode())
if (current_query_node.node.template is<TreeNode>())
{
const TreeNode & current_tree_node = boost::get<TreeNode>(current_query_node.node);
const TreeNode & current_tree_node = current_query_node.node.template get<TreeNode>();
if (current_tree_node.child_is_on_disk)
{
++loaded_leafs;
@ -763,7 +760,7 @@ class StaticRTree
{
++inspected_segments;
// inspecting an actual road segment
const EdgeDataT & current_segment = boost::get<EdgeDataT>(current_query_node.node);
const EdgeDataT & current_segment = current_query_node.node.template get<EdgeDataT>();
// don't collect too many results from small components
if (number_of_results_found_in_big_cc == number_of_results && !current_segment.is_in_tiny_cc)
@ -791,7 +788,7 @@ class StaticRTree
BOOST_ASSERT(0. <= current_perpendicular_distance);
if ((current_perpendicular_distance < current_min_dist) &&
!EpsilonCompare(current_perpendicular_distance, current_min_dist))
!osrm::epsilon_compare(current_perpendicular_distance, current_min_dist))
{
// store phantom node in result vector
result_phantom_node_vector.emplace_back(
@ -804,7 +801,9 @@ class StaticRTree
current_segment.reverse_offset,
current_segment.packed_geometry_id,
foot_point_coordinate_on_segment,
current_segment.fwd_segment_position);
current_segment.fwd_segment_position,
current_segment.forward_travel_mode,
current_segment.backward_travel_mode);
// Hack to fix rounding errors and wandering via nodes.
FixUpRoundingIssue(input_coordinate, result_phantom_node_vector.back());
@ -891,7 +890,7 @@ class StaticRTree
if (current_query_node.RepresentsTreeNode())
{
const TreeNode & current_tree_node = boost::get<TreeNode>(current_query_node.node);
const TreeNode & current_tree_node = current_query_node.node.template get<TreeNode>();
if (current_tree_node.child_is_on_disk)
{
LeafNode current_leaf_node;
@ -940,7 +939,7 @@ class StaticRTree
{
++inspected_segments;
// inspecting an actual road segment
const EdgeDataT & current_segment = boost::get<EdgeDataT>(current_query_node.node);
const EdgeDataT & current_segment = current_query_node.node.template get<EdgeDataT>();
// don't collect too many results from small components
if (number_of_results_found_in_big_cc == number_of_results && !current_segment.is_in_tiny_cc)
@ -968,7 +967,7 @@ class StaticRTree
BOOST_ASSERT(0. <= current_perpendicular_distance);
if ((current_perpendicular_distance < current_min_dist) &&
!EpsilonCompare(current_perpendicular_distance, current_min_dist))
!osrm::epsilon_compare(current_perpendicular_distance, current_min_dist))
{
// store phantom node in result vector
result_phantom_node_vector.emplace_back(
@ -1068,7 +1067,7 @@ class StaticRTree
BOOST_ASSERT(0. <= current_perpendicular_distance);
if ((current_perpendicular_distance < min_dist) &&
!EpsilonCompare(current_perpendicular_distance, min_dist))
!osrm::epsilon_compare(current_perpendicular_distance, min_dist))
{ // found a new minimum
min_dist = current_perpendicular_distance;
result_phantom_node = {current_edge.forward_edge_based_node_id,
@ -1080,7 +1079,9 @@ class StaticRTree
current_edge.reverse_offset,
current_edge.packed_geometry_id,
nearest,
current_edge.fwd_segment_position};
current_edge.fwd_segment_position,
current_edge.forward_travel_mode,
current_edge.backward_travel_mode};
nearest_edge = current_edge;
}
}

View file

@ -1,4 +1,5 @@
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.
@ -24,16 +25,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __NUMERIC_UTIL_H__
#define __NUMERIC_UTIL_H__
#ifndef TRAVEL_MODE_H
#define TRAVEL_MODE_H
#include <cstdlib>
using TravelMode = unsigned char;
static const TravelMode TRAVEL_MODE_INACCESSIBLE = 0;
static const TravelMode TRAVEL_MODE_DEFAULT = 1;
#include <limits>
template <typename FloatT> inline bool EpsilonCompare(const FloatT d1, const FloatT d2)
{
return (std::abs(d1 - d2) < std::numeric_limits<FloatT>::epsilon());
}
#endif
#endif /* TRAVEL_MODE_H */

View file

@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
enum class TurnInstruction : unsigned char
{
NoTurn = 0, GoStraight, TurnSlightRight, TurnRight, TurnSharpRight, UTurn,
TurnSharpLeft, TurnLeft, TurnSlightLeft, ReachViaPoint, HeadOn, EnterRoundAbout,
TurnSharpLeft, TurnLeft, TurnSlightLeft, ReachViaLocation, HeadOn, EnterRoundAbout,
LeaveRoundAbout, StayOnRoundAbout, StartAtEndOfStreet, ReachedYourDestination,
EnterAgainstAllowedDirection, LeaveAgainstAllowedDirection,
InverseAccessRestrictionFlag = 127,

View file

@ -49,14 +49,14 @@ template <typename NodeID, typename Key> class XORFastHashStorage
HashCell(const HashCell &other) : key(other.key), id(other.id), time(other.time) {}
inline operator Key() const { return key; }
operator Key() const { return key; }
inline void operator=(const Key &key_to_insert) { key = key_to_insert; }
void operator=(const Key &key_to_insert) { key = key_to_insert; }
};
explicit XORFastHashStorage(size_t) : positions(2 << 16), current_timestamp(0) {}
inline HashCell &operator[](const NodeID node)
HashCell &operator[](const NodeID node)
{
unsigned short position = fast_hasher(node);
while ((positions[position].time == current_timestamp) && (positions[position].id != node))
@ -69,7 +69,7 @@ template <typename NodeID, typename Key> class XORFastHashStorage
return positions[position];
}
inline void Clear()
void Clear()
{
++current_timestamp;
if (std::numeric_limits<unsigned>::max() == current_timestamp)

View file

@ -45,38 +45,71 @@ void DescriptionFactory::SetStartSegment(const PhantomNode &source, const bool t
start_phantom = source;
const EdgeWeight segment_duration =
(traversed_in_reverse ? source.reverse_weight : source.forward_weight);
AppendSegment(source.location,
PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration));
const TravelMode travel_mode =
(traversed_in_reverse ? source.backward_travel_mode : source.forward_travel_mode);
AppendSegment(
source.location,
PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration, travel_mode));
BOOST_ASSERT(path_description.back().duration == segment_duration);
}
void DescriptionFactory::SetEndSegment(const PhantomNode &target, const bool traversed_in_reverse)
void DescriptionFactory::SetEndSegment(const PhantomNode &target,
const bool traversed_in_reverse,
const bool is_via_location)
{
target_phantom = target;
const EdgeWeight segment_duration =
(traversed_in_reverse ? target.reverse_weight : target.forward_weight);
path_description.emplace_back(
target.location, target.name_id, segment_duration, 0.f, TurnInstruction::NoTurn, true, true);
const TravelMode travel_mode =
(traversed_in_reverse ? target.backward_travel_mode : target.forward_travel_mode);
path_description.emplace_back(target.location,
target.name_id,
segment_duration,
0.f,
is_via_location ? TurnInstruction::ReachViaLocation
: TurnInstruction::NoTurn,
true,
true,
travel_mode);
BOOST_ASSERT(path_description.back().duration == segment_duration);
}
void DescriptionFactory::AppendSegment(const FixedPointCoordinate &coordinate,
const PathData &path_point)
{
if ((1 == path_description.size()) && (path_description.back().location == coordinate))
// if the start location is on top of a node, the first movement might be zero-length,
// in which case we dont' add a new description, but instead update the existing one
if ((1 == path_description.size()) && (path_description.front().location == coordinate))
{
path_description.back().name_id = path_point.name_id;
if (path_point.segment_duration > 0)
{
path_description.front().name_id = path_point.name_id;
path_description.front().travel_mode = path_point.travel_mode;
}
return;
}
// make sure mode changes are announced, even when there otherwise is no turn
const TurnInstruction turn = [&]() -> TurnInstruction
{
if (TurnInstruction::NoTurn == path_point.turn_instruction &&
path_description.front().travel_mode != path_point.travel_mode &&
path_point.segment_duration > 0)
{
return TurnInstruction::GoStraight;
}
return path_point.turn_instruction;
}();
path_description.emplace_back(coordinate,
path_point.name_id,
path_point.segment_duration,
0.f,
path_point.turn_instruction);
turn,
path_point.travel_mode);
}
JSON::Value DescriptionFactory::AppendEncodedPolylineString(const bool return_encoded)
JSON::Value DescriptionFactory::AppendGeometryString(const bool return_encoded)
{
if (return_encoded)
{

View file

@ -80,9 +80,11 @@ class DescriptionFactory
void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &data);
void BuildRouteSummary(const double distance, const unsigned time);
void SetStartSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse);
void SetEndSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse);
JSON::Value AppendEncodedPolylineString(const bool return_encoded);
std::vector<unsigned> const & GetViaIndices() const;
void SetEndSegment(const PhantomNode &start_phantom,
const bool traversed_in_reverse,
const bool is_via_location = false);
JSON::Value AppendGeometryString(const bool return_encoded);
std::vector<unsigned> const &GetViaIndices() const;
template <class DataFacadeT> void Run(const DataFacadeT *facade, const unsigned zoomLevel)
{
@ -198,14 +200,15 @@ class DescriptionFactory
{
++necessary_pieces;
if (path_description[i].is_via_location)
{ //mark the end of a leg
{ // mark the end of a leg
via_indices.push_back(necessary_pieces);
}
const double angle = path_description[i+1].location.GetBearing(path_description[i].location);
const double angle =
path_description[i + 1].location.GetBearing(path_description[i].location);
path_description[i].bearing = static_cast<unsigned>(angle * 10);
}
}
via_indices.push_back(necessary_pieces+1);
via_indices.push_back(necessary_pieces + 1);
BOOST_ASSERT(via_indices.size() >= 2);
// BOOST_ASSERT(0 != necessary_pieces || path_description.empty());
return;

View file

@ -30,14 +30,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseDescriptor.h"
template <class DataFacadeT> class GPXDescriptor : public BaseDescriptor<DataFacadeT>
template <class DataFacadeT> class GPXDescriptor final : public BaseDescriptor<DataFacadeT>
{
private:
DescriptorConfig config;
FixedPointCoordinate current;
DataFacadeT * facade;
DataFacadeT *facade;
void AddRoutePoint(const FixedPointCoordinate & coordinate, std::vector<char> & output)
void AddRoutePoint(const FixedPointCoordinate &coordinate, std::vector<char> &output)
{
const std::string route_point_head = "<rtept lat=\"";
const std::string route_point_middle = " lon=\"";
@ -57,12 +57,12 @@ template <class DataFacadeT> class GPXDescriptor : public BaseDescriptor<DataFac
}
public:
GPXDescriptor(DataFacadeT *facade) : facade(facade) {}
explicit GPXDescriptor(DataFacadeT *facade) : facade(facade) {}
void SetConfig(const DescriptorConfig &c) { config = c; }
void SetConfig(const DescriptorConfig &c) final { config = c; }
// TODO: reorder parameters
void Run(const RawRouteData &raw_route, http::Reply &reply)
void Run(const RawRouteData &raw_route, http::Reply &reply) final
{
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<gpx creator=\"OSRM Routing Engine\" version=\"1.1\" "
@ -79,7 +79,8 @@ template <class DataFacadeT> class GPXDescriptor : public BaseDescriptor<DataFac
(!raw_route.unpacked_path_segments.front().empty());
if (found_route)
{
AddRoutePoint(raw_route.segment_end_coordinates.front().source_phantom.location, reply.content);
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)
{
@ -90,8 +91,8 @@ template <class DataFacadeT> class GPXDescriptor : public BaseDescriptor<DataFac
AddRoutePoint(current_coordinate, reply.content);
}
}
AddRoutePoint(raw_route.segment_end_coordinates.back().target_phantom.location, 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());

View file

@ -42,7 +42,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFacadeT>
template <class DataFacadeT> class JSONDescriptor final : public BaseDescriptor<DataFacadeT>
{
private:
DataFacadeT *facade;
@ -70,13 +70,14 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
ExtractRouteNames<DataFacadeT, Segment> GenerateRouteNames;
public:
JSONDescriptor(DataFacadeT *facade) : facade(facade), entered_restricted_area_count(0) {}
explicit JSONDescriptor(DataFacadeT *facade) : facade(facade), entered_restricted_area_count(0) {}
void SetConfig(const DescriptorConfig &c) { config = c; }
void SetConfig(const DescriptorConfig &c) final { config = c; }
unsigned DescribeLeg(const std::vector<PathData> route_leg,
const PhantomNodes &leg_phantoms,
const bool target_traversed_in_reverse)
const bool target_traversed_in_reverse,
const bool is_via_leg)
{
unsigned added_element_count = 0;
// Get all the coordinates for the computed route
@ -87,13 +88,14 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
description_factory.AppendSegment(current_coordinate, path_data);
++added_element_count;
}
description_factory.SetEndSegment(leg_phantoms.target_phantom, target_traversed_in_reverse);
description_factory.SetEndSegment(
leg_phantoms.target_phantom, target_traversed_in_reverse, is_via_leg);
++added_element_count;
BOOST_ASSERT((route_leg.size() + 1) == added_element_count);
return added_element_count;
}
void Run(const RawRouteData &raw_route, http::Reply &reply)
void Run(const RawRouteData &raw_route, http::Reply &reply) final
{
JSON::Object json_result;
if (INVALID_EDGE_WEIGHT == raw_route.shortest_path_length)
@ -124,9 +126,10 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
#ifndef NDEBUG
const int added_segments =
#endif
DescribeLeg(raw_route.unpacked_path_segments[i],
raw_route.segment_end_coordinates[i],
raw_route.target_traversed_in_reverse[i]);
DescribeLeg(raw_route.unpacked_path_segments[i],
raw_route.segment_end_coordinates[i],
raw_route.target_traversed_in_reverse[i],
raw_route.is_via_leg(i));
BOOST_ASSERT(0 < added_segments);
}
description_factory.Run(facade, config.zoom_level);
@ -134,7 +137,7 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
if (config.geometry)
{
JSON::Value route_geometry =
description_factory.AppendEncodedPolylineString(config.encode_geometry);
description_factory.AppendGeometryString(config.encode_geometry);
json_result.values["route_geometry"] = route_geometry;
}
if (config.instructions)
@ -202,14 +205,15 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
current = facade->GetCoordinateOfNode(path_data.node);
alternate_description_factory.AppendSegment(current, path_data);
}
alternate_description_factory.SetEndSegment(raw_route.segment_end_coordinates.back().target_phantom, raw_route.alt_source_traversed_in_reverse.back());
alternate_description_factory.SetEndSegment(
raw_route.segment_end_coordinates.back().target_phantom,
raw_route.alt_source_traversed_in_reverse.back());
alternate_description_factory.Run(facade, config.zoom_level);
if (config.geometry)
{
JSON::Value alternate_geometry_string =
alternate_description_factory.AppendEncodedPolylineString(
config.encode_geometry);
alternate_description_factory.AppendGeometryString(config.encode_geometry);
JSON::Array json_alternate_geometries_array;
json_alternate_geometries_array.values.push_back(alternate_geometry_string);
json_result.values["alternative_geometries"] = json_alternate_geometries_array;
@ -279,10 +283,10 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
std::string hint;
for (const auto i : osrm::irange<std::size_t>(0, raw_route.segment_end_coordinates.size()))
{
EncodeObjectToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint);
ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint);
json_location_hint_array.values.push_back(hint);
}
EncodeObjectToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint);
ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint);
json_location_hint_array.values.push_back(hint);
json_hint_object.values["locations"] = json_location_hint_array;
json_result.values["hint_data"] = json_hint_object;
@ -326,16 +330,16 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
if (TurnInstruction::LeaveRoundAbout == current_instruction)
{
temp_instruction =
IntToString(as_integer(TurnInstruction::EnterRoundAbout));
cast::integral_to_string(cast::enum_to_underlying(TurnInstruction::EnterRoundAbout));
current_turn_instruction += temp_instruction;
current_turn_instruction += "-";
temp_instruction = IntToString(round_about.leave_at_exit + 1);
temp_instruction = cast::integral_to_string(round_about.leave_at_exit + 1);
current_turn_instruction += temp_instruction;
round_about.leave_at_exit = 0;
}
else
{
temp_instruction = IntToString(as_integer(current_instruction));
temp_instruction = cast::integral_to_string(cast::enum_to_underlying(current_instruction));
current_turn_instruction += temp_instruction;
}
json_instruction_row.values.push_back(current_turn_instruction);
@ -346,13 +350,17 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
json_instruction_row.values.push_back(necessary_segments_running_index);
json_instruction_row.values.push_back(round(segment.duration / 10));
json_instruction_row.values.push_back(
UintToString(static_cast<int>(segment.length)) + "m");
const double bearing_value = (segment.bearing / 10.) ;
cast::integral_to_string(static_cast<unsigned>(segment.length)) + "m");
const double bearing_value = (segment.bearing / 10.);
json_instruction_row.values.push_back(Azimuth::Get(bearing_value));
json_instruction_row.values.push_back(static_cast<unsigned>(round(bearing_value)));
json_instruction_row.values.push_back(
static_cast<unsigned>(round(bearing_value)));
json_instruction_row.values.push_back(segment.travel_mode);
route_segments_list.emplace_back(
segment.name_id, static_cast<int>(segment.length), static_cast<unsigned>(route_segments_list.size()));
segment.name_id,
static_cast<int>(segment.length),
static_cast<unsigned>(route_segments_list.size()));
json_instruction_array.values.push_back(json_instruction_row);
}
}
@ -367,7 +375,7 @@ template <class DataFacadeT> class JSONDescriptor : public BaseDescriptor<DataFa
}
JSON::Array json_last_instruction_row;
temp_instruction = IntToString(as_integer(TurnInstruction::ReachedYourDestination));
temp_instruction = cast::integral_to_string(cast::enum_to_underlying(TurnInstruction::ReachedYourDestination));
json_last_instruction_row.values.push_back(temp_instruction);
json_last_instruction_row.values.push_back("");
json_last_instruction_row.values.push_back(0);

View file

@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/ImportNode.h"
#include "../Util/LuaUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>

View file

@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ExtractionContainers.h"
#include "ExtractionWay.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../DataStructures/RangeTable.h"
@ -330,7 +330,6 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name,
edge_iterator->source_coordinate.lon != std::numeric_limits<int>::min())
{
BOOST_ASSERT(edge_iterator->speed != -1);
BOOST_ASSERT(edge_iterator->type >= 0);
edge_iterator->target_coordinate.lat = node_iterator->lat;
edge_iterator->target_coordinate.lon = node_iterator->lon;
@ -349,7 +348,6 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name,
short zero = 0;
short one = 1;
file_out_stream.write((char *)&edge_iterator->way_id, sizeof(unsigned));
file_out_stream.write((char *)&edge_iterator->start, sizeof(unsigned));
file_out_stream.write((char *)&edge_iterator->target, sizeof(unsigned));
file_out_stream.write((char *)&integer_distance, sizeof(int));
@ -372,14 +370,16 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name,
}
file_out_stream.write((char *)&integer_weight, sizeof(int));
file_out_stream.write((char *)&edge_iterator->type, sizeof(short));
file_out_stream.write((char *)&edge_iterator->name_id, sizeof(unsigned));
file_out_stream.write((char *)&edge_iterator->is_roundabout, sizeof(bool));
file_out_stream.write((char *)&edge_iterator->is_in_tiny_cc, sizeof(bool));
file_out_stream.write((char *)&edge_iterator->is_access_restricted, sizeof(bool));
file_out_stream.write((char *)&edge_iterator->is_contra_flow, sizeof(bool));
file_out_stream.write((char *)&edge_iterator->is_split, sizeof(bool));
// cannot take adress of bit field, so use local
const TravelMode travel_mode = edge_iterator->travel_mode;
file_out_stream.write((char *)&travel_mode, sizeof(TravelMode));
file_out_stream.write((char *)&edge_iterator->is_split, sizeof(bool));
++number_of_used_edges;
}
++edge_iterator;

View file

@ -43,12 +43,12 @@ class ExtractionContainers
const static unsigned stxxl_memory = ((sizeof(std::size_t) == 4) ? INT_MAX : UINT_MAX);
#endif
public:
typedef stxxl::vector<NodeID> STXXLNodeIDVector;
typedef stxxl::vector<ExternalMemoryNode> STXXLNodeVector;
typedef stxxl::vector<InternalExtractorEdge> STXXLEdgeVector;
typedef stxxl::vector<std::string> STXXLStringVector;
typedef stxxl::vector<InputRestrictionContainer> STXXLRestrictionsVector;
typedef stxxl::vector<WayIDStartAndEndEdge> STXXLWayIDStartEndVector;
using STXXLNodeIDVector = stxxl::vector<NodeID>;
using STXXLNodeVector = stxxl::vector<ExternalMemoryNode>;
using STXXLEdgeVector = stxxl::vector<InternalExtractorEdge>;
using STXXLStringVector = stxxl::vector<std::string>;
using STXXLRestrictionsVector = stxxl::vector<InputRestrictionContainer>;
using STXXLWayIDStartEndVector = stxxl::vector<WayIDStartAndEndEdge>;
STXXLNodeIDVector used_node_id_list;
STXXLNodeVector all_nodes_list;
@ -60,7 +60,7 @@ class ExtractionContainers
ExtractionContainers();
virtual ~ExtractionContainers();
~ExtractionContainers();
void PrepareData(const std::string &output_file_name,
const std::string &restrictions_file_name);

View file

@ -28,10 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef EXTRACTION_HELPER_FUNCTIONS_H
#define EXTRACTION_HELPER_FUNCTIONS_H
#include "../Util/StringUtil.h"
#include "../Util/cast.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/regex.hpp>
#include <limits>
@ -68,18 +69,18 @@ inline unsigned parseDuration(const std::string &s)
{
if (1 == result.size())
{
minutes = StringToUint(result[0]);
minutes = cast::string_to_int(result[0]);
}
if (2 == result.size())
{
minutes = StringToUint(result[1]);
hours = StringToUint(result[0]);
minutes = cast::string_to_int(result[1]);
hours = cast::string_to_int(result[0]);
}
if (3 == result.size())
{
seconds = StringToUint(result[2]);
minutes = StringToUint(result[1]);
hours = StringToUint(result[0]);
seconds = cast::string_to_int(result[2]);
minutes = cast::string_to_int(result[1]);
hours = cast::string_to_int(result[0]);
}
return 10 * (3600 * hours + 60 * minutes + seconds);
}

View file

@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define EXTRACTION_WAY_H
#include "../DataStructures/HashTable.h"
#include "../DataStructures/TravelMode.h"
#include "../typedefs.h"
#include <string>
@ -44,15 +45,15 @@ struct ExtractionWay
nameID = INVALID_NAMEID;
path.clear();
keyVals.Clear();
direction = ExtractionWay::notSure;
speed = -1;
forward_speed = -1;
backward_speed = -1;
duration = -1;
type = -1;
access = true;
roundabout = false;
isAccessRestricted = false;
ignoreInGrid = false;
forward_travel_mode = TRAVEL_MODE_DEFAULT;
backward_travel_mode = TRAVEL_MODE_DEFAULT;
}
enum Directions
@ -60,20 +61,70 @@ struct ExtractionWay
oneway,
bidirectional,
opposite };
// These accessor methods exists to support the depreciated "way.direction" access
// in LUA. Since the direction attribute was removed from ExtractionWay, the
// accessors translate to/from the mode attributes.
inline void set_direction(const Directions m)
{
if (Directions::oneway == m)
{
forward_travel_mode = TRAVEL_MODE_DEFAULT;
backward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
}
else if (Directions::opposite == m)
{
forward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
backward_travel_mode = TRAVEL_MODE_DEFAULT;
}
else if (Directions::bidirectional == m)
{
forward_travel_mode = TRAVEL_MODE_DEFAULT;
backward_travel_mode = TRAVEL_MODE_DEFAULT;
}
}
inline const Directions get_direction() const
{
if (TRAVEL_MODE_INACCESSIBLE != forward_travel_mode && TRAVEL_MODE_INACCESSIBLE != backward_travel_mode)
{
return Directions::bidirectional;
}
else if (TRAVEL_MODE_INACCESSIBLE != forward_travel_mode)
{
return Directions::oneway;
}
else if (TRAVEL_MODE_INACCESSIBLE != backward_travel_mode)
{
return Directions::opposite;
}
else
{
return Directions::notSure;
}
}
// These accessors exists because it's not possible to take the address of a bitfield,
// and LUA therefore cannot read/write the mode attributes directly.
inline void set_forward_mode(const TravelMode m) { forward_travel_mode = m; }
inline const TravelMode get_forward_mode() const { return forward_travel_mode; }
inline void set_backward_mode(const TravelMode m) { backward_travel_mode = m; }
inline const TravelMode get_backward_mode() const { return backward_travel_mode; }
unsigned id;
unsigned nameID;
double speed;
double forward_speed;
double backward_speed;
double duration;
Directions direction;
std::string name;
short type;
bool access;
bool roundabout;
bool isAccessRestricted;
bool ignoreInGrid;
std::vector<NodeID> path;
HashTable<std::string, std::string> keyVals;
TravelMode forward_travel_mode : 4;
TravelMode backward_travel_mode : 4;
};
#endif // EXTRACTION_WAY_H

View file

@ -34,9 +34,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "XMLParser.h"
#include "../Util/GitDescription.h"
#include "../Util/IniFileUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/ProgramOptions.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../typedefs.h"

View file

@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/Restriction.h"
#include "../DataStructures/ImportNode.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include <osrm/Coordinate.h>
@ -63,7 +63,11 @@ bool ExtractorCallbacks::ProcessRestriction(const InputRestrictionContainer &res
/** warning: caller needs to take care of synchronization! */
void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
{
if ((0 >= parsed_way.speed) && (0 >= parsed_way.duration))
if (((0 >= parsed_way.forward_speed) ||
(TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode)) &&
((0 >= parsed_way.backward_speed) ||
(TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode)) &&
(0 >= parsed_way.duration))
{ // Only true if the way is specified by the speed profile
return;
}
@ -84,10 +88,11 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
{
// TODO: iterate all way segments and set duration corresponding to the length of each
// segment
parsed_way.speed = parsed_way.duration / (parsed_way.path.size() - 1);
parsed_way.forward_speed = parsed_way.duration / (parsed_way.path.size() - 1);
parsed_way.backward_speed = parsed_way.duration / (parsed_way.path.size() - 1);
}
if (std::numeric_limits<double>::epsilon() >= std::abs(-1. - parsed_way.speed))
if (std::numeric_limits<double>::epsilon() >= std::abs(-1. - parsed_way.forward_speed))
{
SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << parsed_way.id;
return;
@ -106,30 +111,34 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
parsed_way.nameID = string_map_iterator->second;
}
if (ExtractionWay::opposite == parsed_way.direction)
if (TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode)
{
std::reverse(parsed_way.path.begin(), parsed_way.path.end());
parsed_way.direction = ExtractionWay::oneway;
parsed_way.forward_travel_mode = parsed_way.backward_travel_mode;
parsed_way.backward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
}
const bool split_edge =
(parsed_way.backward_speed > 0) && (parsed_way.speed != parsed_way.backward_speed);
(parsed_way.forward_speed>0) && (TRAVEL_MODE_INACCESSIBLE != parsed_way.forward_travel_mode) &&
(parsed_way.backward_speed>0) && (TRAVEL_MODE_INACCESSIBLE != parsed_way.backward_travel_mode) &&
((parsed_way.forward_speed != parsed_way.backward_speed) ||
(parsed_way.forward_travel_mode != parsed_way.backward_travel_mode));
BOOST_ASSERT(parsed_way.forward_travel_mode>0);
for (unsigned n = 0; n < (parsed_way.path.size() - 1); ++n)
{
external_memory.all_edges_list.push_back(InternalExtractorEdge(
parsed_way.id,
parsed_way.path[n],
parsed_way.path[n + 1],
parsed_way.type,
(split_edge ? ExtractionWay::oneway : parsed_way.direction),
parsed_way.speed,
((split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode) ? ExtractionWay::oneway
: ExtractionWay::bidirectional),
parsed_way.forward_speed,
parsed_way.nameID,
parsed_way.roundabout,
parsed_way.ignoreInGrid,
(0 < parsed_way.duration),
parsed_way.isAccessRestricted,
false,
parsed_way.forward_travel_mode,
split_edge));
external_memory.used_node_id_list.push_back(parsed_way.path[n]);
}
@ -145,14 +154,14 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
if (split_edge)
{ // Only true if the way should be split
BOOST_ASSERT(parsed_way.backward_travel_mode>0);
std::reverse(parsed_way.path.begin(), parsed_way.path.end());
for (std::vector<NodeID>::size_type n = 0; n < parsed_way.path.size() - 1; ++n)
{
external_memory.all_edges_list.push_back(
InternalExtractorEdge(parsed_way.id,
parsed_way.path[n],
InternalExtractorEdge(parsed_way.path[n],
parsed_way.path[n + 1],
parsed_way.type,
ExtractionWay::oneway,
parsed_way.backward_speed,
parsed_way.nameID,
@ -160,7 +169,7 @@ void ExtractorCallbacks::ProcessWay(ExtractionWay &parsed_way)
parsed_way.ignoreInGrid,
(0 < parsed_way.duration),
parsed_way.isAccessRestricted,
(ExtractionWay::oneway == parsed_way.direction),
parsed_way.backward_travel_mode,
split_edge));
}
external_memory.way_start_end_id_list.push_back(

View file

@ -83,7 +83,7 @@ struct WayIDStartAndEndEdge
struct CmpWayByID
{
typedef WayIDStartAndEndEdge value_type;
using value_type = WayIDStartAndEndEdge;
bool operator()(const WayIDStartAndEndEdge &a, const WayIDStartAndEndEdge &b) const
{
return a.wayID < b.wayID;
@ -94,7 +94,7 @@ struct CmpWayByID
struct Cmp
{
typedef NodeID value_type;
using value_type = NodeID;
bool operator()(const NodeID left, const NodeID right) const { return left < right; }
value_type max_value() { return 0xffffffff; }
value_type min_value() { return 0x0; }
@ -102,7 +102,7 @@ struct Cmp
struct CmpNodeByID
{
typedef ExternalMemoryNode value_type;
using value_type = ExternalMemoryNode;
bool operator()(const ExternalMemoryNode &left, const ExternalMemoryNode &right) const
{
return left.node_id < right.node_id;

View file

@ -29,6 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define INTERNAL_EXTRACTOR_EDGE_H
#include "../typedefs.h"
#include "../DataStructures/TravelMode.h"
#include <osrm/Coordinate.h>
#include <boost/assert.hpp>
@ -36,16 +37,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
struct InternalExtractorEdge
{
InternalExtractorEdge()
: way_id(0), start(0), target(0), type(0), direction(0), speed(0), name_id(0), is_roundabout(false),
: start(0), target(0), direction(0), speed(0), name_id(0), is_roundabout(false),
is_in_tiny_cc(false), is_duration_set(false), is_access_restricted(false),
is_contra_flow(false), is_split(false)
travel_mode(TRAVEL_MODE_INACCESSIBLE), is_split(false)
{
}
explicit InternalExtractorEdge(unsigned id,
NodeID start,
explicit InternalExtractorEdge(NodeID start,
NodeID target,
short type,
short direction,
double speed,
unsigned name_id,
@ -53,31 +52,28 @@ struct InternalExtractorEdge
bool is_in_tiny_cc,
bool is_duration_set,
bool is_access_restricted,
bool is_contra_flow,
TravelMode travel_mode,
bool is_split)
: way_id(id), start(start), target(target), type(type), direction(direction), speed(speed),
: start(start), target(target), direction(direction), speed(speed),
name_id(name_id), is_roundabout(is_roundabout), is_in_tiny_cc(is_in_tiny_cc),
is_duration_set(is_duration_set), is_access_restricted(is_access_restricted),
is_contra_flow(is_contra_flow), is_split(is_split)
travel_mode(travel_mode), is_split(is_split)
{
BOOST_ASSERT(0 <= type);
}
// necessary static util functions for stxxl's sorting
static InternalExtractorEdge min_value()
{
return InternalExtractorEdge(0, 0, 0, 0, 0, 0, 0, false, false, false, false, false, false);
return InternalExtractorEdge(0, 0, 0, 0, 0, false, false, false, false, TRAVEL_MODE_INACCESSIBLE, false);
}
static InternalExtractorEdge max_value()
{
return InternalExtractorEdge(
SPECIAL_EDGEID, SPECIAL_NODEID, SPECIAL_NODEID, 0, 0, 0, 0, false, false, false, false, false, false);
SPECIAL_NODEID, SPECIAL_NODEID, 0, 0, 0, false, false, false, false, TRAVEL_MODE_INACCESSIBLE, false);
}
unsigned way_id;
NodeID start;
NodeID target;
short type;
short direction;
double speed;
unsigned name_id;
@ -85,7 +81,7 @@ struct InternalExtractorEdge
bool is_in_tiny_cc;
bool is_duration_set;
bool is_access_restricted;
bool is_contra_flow;
TravelMode travel_mode : 4;
bool is_split;
FixedPointCoordinate source_coordinate;
@ -94,7 +90,7 @@ struct InternalExtractorEdge
struct CmpEdgeByStartID
{
typedef InternalExtractorEdge value_type;
using value_type = InternalExtractorEdge;
bool operator()(const InternalExtractorEdge &a, const InternalExtractorEdge &b) const
{
return a.start < b.start;
@ -107,7 +103,7 @@ struct CmpEdgeByStartID
struct CmpEdgeByTargetID
{
typedef InternalExtractorEdge value_type;
using value_type = InternalExtractorEdge;
bool operator()(const InternalExtractorEdge &a, const InternalExtractorEdge &b) const
{

View file

@ -36,7 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/Restriction.h"
#include "../Util/MachineInfo.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../typedefs.h"
#include <boost/assert.hpp>
@ -49,6 +49,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <zlib.h>
#include <functional>
#include <iostream>
#include <limits>
#include <thread>

View file

@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/ImportNode.h"
#include "../Util/LuaUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../typedefs.h"
#include <sstream>
@ -76,16 +76,17 @@ void ScriptingEnvironment::initLuaState(lua_State* lua_state)
// .def(luabind::constructor<>())
.def_readonly("id", &ExtractionWay::id)
.def_readwrite("name", &ExtractionWay::name)
.def_readwrite("speed", &ExtractionWay::speed)
.def_readwrite("forward_speed", &ExtractionWay::forward_speed)
.def_readwrite("backward_speed", &ExtractionWay::backward_speed)
.def_readwrite("duration", &ExtractionWay::duration)
.def_readwrite("type", &ExtractionWay::type)
.def_readwrite("access", &ExtractionWay::access)
.def_readwrite("roundabout", &ExtractionWay::roundabout)
.def_readwrite("is_access_restricted", &ExtractionWay::isAccessRestricted)
.def_readwrite("ignore_in_grid", &ExtractionWay::ignoreInGrid)
.def_readwrite("tags", &ExtractionWay::keyVals)
.def_readwrite("direction", &ExtractionWay::direction)
.property("direction", &ExtractionWay::get_direction, &ExtractionWay::set_direction)
.property("forward_mode", &ExtractionWay::get_forward_mode, &ExtractionWay::set_forward_mode)
.property("backward_mode", &ExtractionWay::get_backward_mode, &ExtractionWay::set_backward_mode)
.enum_("constants")[
luabind::value("notSure", 0),
luabind::value("oneway", 1),

View file

@ -34,7 +34,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/cast.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
@ -168,17 +169,17 @@ InputRestrictionContainer XMLParser::ReadXMLRestriction()
if (xmlStrEqual(role, (const xmlChar *)"to") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.toWay = StringToUint((const char *)ref);
restriction.toWay = cast::string_to_uint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"from") &&
xmlStrEqual(type, (const xmlChar *)"way"))
{
restriction.fromWay = StringToUint((const char *)ref);
restriction.fromWay = cast::string_to_uint((const char *)ref);
}
if (xmlStrEqual(role, (const xmlChar *)"via") &&
xmlStrEqual(type, (const xmlChar *)"node"))
{
restriction.restriction.viaNode = StringToUint((const char *)ref);
restriction.restriction.viaNode = cast::string_to_uint((const char *)ref);
}
if (nullptr != type)
@ -231,7 +232,7 @@ ExtractionWay XMLParser::ReadXMLWay()
xmlStrEqual(child_name, (const xmlChar *)"way") == 1)
{
xmlChar *way_id = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
way.id = StringToUint((char *)way_id);
way.id = cast::string_to_uint((char *)way_id);
xmlFree(way_id);
xmlFree(child_name);
break;
@ -265,7 +266,7 @@ ExtractionWay XMLParser::ReadXMLWay()
xmlChar *ref = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"ref");
if (ref != nullptr)
{
way.path.push_back(StringToUint((const char *)ref));
way.path.push_back(cast::string_to_uint((const char *)ref));
xmlFree(ref);
}
}
@ -281,19 +282,19 @@ ImportNode XMLParser::ReadXMLNode()
xmlChar *attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"lat");
if (attribute != nullptr)
{
node.lat = static_cast<int>(COORDINATE_PRECISION * StringToDouble((const char *)attribute));
node.lat = static_cast<int>(COORDINATE_PRECISION * cast::string_to_double((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));
node.lon = static_cast<int>(COORDINATE_PRECISION * cast::string_to_double((const char *)attribute));
xmlFree(attribute);
}
attribute = xmlTextReaderGetAttribute(inputReader, (const xmlChar *)"id");
if (attribute != nullptr)
{
node.node_id = StringToUint((const char *)attribute);
node.node_id = cast::string_to_uint((const char *)attribute);
xmlFree(attribute);
}

View file

@ -30,8 +30,9 @@ 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;
constexpr float COORDINATE_PRECISION = 1000000.f;
struct FixedPointCoordinate
{
@ -40,6 +41,14 @@ 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;

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()
{

View file

@ -41,6 +41,8 @@ struct RouteParameters
void setZoomLevel(const short level);
void setNumberOfResults(const short number);
void setAlternateRouteFlag(const bool flag);
void setUTurn(const bool flag);
@ -77,6 +79,7 @@ struct RouteParameters
bool deprecatedAPI;
bool uturn_default;
unsigned check_sum;
short num_results;
std::string service;
std::string output_format;
std::string jsonp_parameter;

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);
};

View file

@ -45,7 +45,9 @@ namespace boost { namespace interprocess { class named_mutex; } }
#include "../Server/DataStructures/InternalDataFacade.h"
#include "../Server/DataStructures/SharedBarriers.h"
#include "../Server/DataStructures/SharedDataFacade.h"
#include "../Util/SimpleLogger.h"
#include "../Util/make_unique.hpp"
#include "../Util/ProgramOptions.h"
#include "../Util/simple_logger.hpp"
#include <boost/assert.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
@ -56,16 +58,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 +88,6 @@ OSRM_impl::~OSRM_impl()
{
delete plugin_pointer.second;
}
if (use_shared_memory)
{
delete barrier;
}
}
void OSRM_impl::RegisterPlugin(BasePlugin *plugin)
@ -108,7 +107,7 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply)
if (plugin_map.end() != iter)
{
reply.status = http::Reply::ok;
if (use_shared_memory)
if (barrier)
{
// lock update pending
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> pending_lock(
@ -129,7 +128,7 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply)
}
iter->second->HandleRequest(route_parameters, reply);
if (use_shared_memory)
if (barrier)
{
// lock query
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> query_lock(
@ -154,12 +153,12 @@ void OSRM_impl::RunQuery(RouteParameters &route_parameters, http::Reply &reply)
// proxy code for compilation firewall
OSRM::OSRM(const ServerPaths &paths, const bool use_shared_memory)
: OSRM_pimpl_(new OSRM_impl(paths, use_shared_memory))
OSRM::OSRM(ServerPaths paths, const bool use_shared_memory)
: OSRM_pimpl_(osrm::make_unique<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)
{

View file

@ -36,6 +36,7 @@ struct RouteParameters;
#include "../DataStructures/QueryEdge.h"
#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;
};

View file

@ -35,7 +35,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/QueryEdge.h"
#include "../DataStructures/SearchEngine.h"
#include "../Descriptors/BaseDescriptor.h"
#include "../Util/SimpleLogger.h"
#include "../Util/make_unique.hpp"
#include "../Util/StringUtil.h"
#include "../Util/TimingUtil.h"
@ -47,22 +47,22 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
template <class DataFacadeT> class DistanceTablePlugin : public BasePlugin
template <class DataFacadeT> class DistanceTablePlugin final : public BasePlugin
{
private:
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
std::unique_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
public:
explicit DistanceTablePlugin(DataFacadeT *facade) : descriptor_string("table"), facade(facade)
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
}
virtual ~DistanceTablePlugin() {}
const std::string GetDescriptor() const { return descriptor_string; }
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
{
// check number of parameters
if (2 > route_parameters.coordinates.size())
@ -77,7 +77,9 @@ template <class DataFacadeT> class DistanceTablePlugin : public BasePlugin
if (std::any_of(begin(route_parameters.coordinates),
end(route_parameters.coordinates),
[&](FixedPointCoordinate coordinate)
{ return !coordinate.isValid(); }))
{
return !coordinate.isValid();
}))
{
reply = http::Reply::StockReply(http::Reply::badRequest);
return;
@ -98,7 +100,7 @@ template <class DataFacadeT> class DistanceTablePlugin : public BasePlugin
!route_parameters.hints[i].empty())
{
PhantomNode current_phantom_node;
DecodeObjectFromBase64(route_parameters.hints[i], current_phantom_node);
ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
if (current_phantom_node.isValid(facade->GetNumberOfNodes()))
{
phantom_node_vector[i].emplace_back(std::move(current_phantom_node));

View file

@ -30,11 +30,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BasePlugin.h"
#include "../DataStructures/JSONContainer.h"
#include "../Util/StringUtil.h"
#include "../Util/cast.hpp"
#include <string>
class HelloWorldPlugin : public BasePlugin
class HelloWorldPlugin final : public BasePlugin
{
private:
std::string temp_string;
@ -42,9 +42,9 @@ class HelloWorldPlugin : public BasePlugin
public:
HelloWorldPlugin() : descriptor_string("hello") {}
virtual ~HelloWorldPlugin() {}
const std::string GetDescriptor() const { return descriptor_string; }
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &routeParameters, http::Reply &reply)
void HandleRequest(const RouteParameters &routeParameters, http::Reply &reply) final
{
reply.status = http::Reply::ok;
@ -52,20 +52,22 @@ class HelloWorldPlugin : public BasePlugin
std::string temp_string;
json_result.values["title"] = "Hello World";
temp_string = IntToString(routeParameters.zoom_level);
temp_string = cast::integral_to_string(routeParameters.zoom_level);
json_result.values["zoom_level"] = temp_string;
temp_string = UintToString(routeParameters.check_sum);
temp_string = cast::integral_to_string(routeParameters.check_sum);
json_result.values["check_sum"] = temp_string;
json_result.values["instructions"] = (routeParameters.print_instructions ? "yes" : "no");
json_result.values["geometry"] = (routeParameters.geometry ? "yes" : "no");
json_result.values["compression"] = (routeParameters.compression ? "yes" : "no");
json_result.values["output_format"] = (!routeParameters.output_format.empty() ? "yes" : "no");
json_result.values["output_format"] =
(!routeParameters.output_format.empty() ? "yes" : "no");
json_result.values["jsonp_parameter"] = (!routeParameters.jsonp_parameter.empty() ? "yes" : "no");
json_result.values["jsonp_parameter"] =
(!routeParameters.jsonp_parameter.empty() ? "yes" : "no");
json_result.values["language"] = (!routeParameters.language.empty() ? "yes" : "no");
temp_string = UintToString(static_cast<unsigned>(routeParameters.coordinates.size()));
temp_string = cast::integral_to_string(routeParameters.coordinates.size());
json_result.values["location_count"] = temp_string;
JSON::Array json_locations;
@ -77,7 +79,7 @@ class HelloWorldPlugin : public BasePlugin
json_coordinates.values.push_back(coordinate.lat / COORDINATE_PRECISION);
json_coordinates.values.push_back(coordinate.lon / COORDINATE_PRECISION);
json_location.values[UintToString(counter)] = json_coordinates;
json_location.values[cast::integral_to_string(counter)] = json_coordinates;
json_locations.values.push_back(json_location);
++counter;
}

View file

@ -35,17 +35,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
// locates the nearest node in the road network for a given coordinate.
template <class DataFacadeT> class LocatePlugin : public BasePlugin
template <class DataFacadeT> class LocatePlugin final : public BasePlugin
{
public:
explicit LocatePlugin(DataFacadeT *facade) : descriptor_string("locate"), facade(facade) {}
const std::string GetDescriptor() const { return descriptor_string; }
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
{
// check number of parameters
if (route_parameters.coordinates.empty() ||
!route_parameters.coordinates.front().isValid())
if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().isValid())
{
reply = http::Reply::StockReply(http::Reply::badRequest);
return;
@ -63,8 +62,8 @@ template <class DataFacadeT> class LocatePlugin : public BasePlugin
reply.status = http::Reply::ok;
json_result.values["status"] = 0;
JSON::Array json_coordinate;
json_coordinate.values.push_back(result.lat/COORDINATE_PRECISION);
json_coordinate.values.push_back(result.lon/COORDINATE_PRECISION);
json_coordinate.values.push_back(result.lat / COORDINATE_PRECISION);
json_coordinate.values.push_back(result.lon / COORDINATE_PRECISION);
json_result.values["mapped_coordinate"] = json_coordinate;
}

View file

@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BasePlugin.h"
#include "../DataStructures/JSONContainer.h"
#include "../DataStructures/PhantomNodes.h"
#include "../DataStructures/Range.h"
#include <string>
@ -38,14 +39,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* This Plugin locates the nearest point on a street in the road network for a given coordinate.
*/
template <class DataFacadeT> class NearestPlugin : public BasePlugin
template <class DataFacadeT> class NearestPlugin final : public BasePlugin
{
public:
explicit NearestPlugin(DataFacadeT *facade) : facade(facade), descriptor_string("nearest") {}
const std::string GetDescriptor() const { return descriptor_string; }
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
{
// check number of parameters
if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().isValid())
@ -53,12 +54,12 @@ template <class DataFacadeT> class NearestPlugin : public BasePlugin
reply = http::Reply::StockReply(http::Reply::badRequest);
return;
}
auto number_of_results = static_cast<std::size_t>(route_parameters.num_results);
std::vector<PhantomNode> phantom_node_vector;
facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates.front(),
phantom_node_vector,
route_parameters.zoom_level,
1);
static_cast<int>(number_of_results));
JSON::Object json_result;
if (phantom_node_vector.empty() || !phantom_node_vector.front().isValid())
@ -69,17 +70,41 @@ template <class DataFacadeT> class NearestPlugin : public BasePlugin
{
reply.status = http::Reply::ok;
json_result.values["status"] = 0;
JSON::Array json_coordinate;
json_coordinate.values.push_back(phantom_node_vector.front().location.lat /
COORDINATE_PRECISION);
json_coordinate.values.push_back(phantom_node_vector.front().location.lon /
COORDINATE_PRECISION);
json_result.values["mapped_coordinate"] = json_coordinate;
std::string temp_string;
facade->GetName(phantom_node_vector.front().name_id, temp_string);
json_result.values["name"] = temp_string;
}
if (number_of_results > 1)
{
JSON::Array results;
auto vector_length = phantom_node_vector.size();
for (const auto i : osrm::irange<std::size_t>(0, std::min(number_of_results, vector_length)))
{
JSON::Array json_coordinate;
JSON::Object result;
json_coordinate.values.push_back(phantom_node_vector.at(i).location.lat /
COORDINATE_PRECISION);
json_coordinate.values.push_back(phantom_node_vector.at(i).location.lon /
COORDINATE_PRECISION);
result.values["mapped coordinate"] = json_coordinate;
std::string temp_string;
facade->GetName(phantom_node_vector.front().name_id, temp_string);
result.values["name"] = temp_string;
results.values.push_back(result);
}
json_result.values["results"] = results;
}
else
{
JSON::Array json_coordinate;
json_coordinate.values.push_back(phantom_node_vector.front().location.lat /
COORDINATE_PRECISION);
json_coordinate.values.push_back(phantom_node_vector.front().location.lon /
COORDINATE_PRECISION);
json_result.values["mapped_coordinate"] = json_coordinate;
std::string temp_string;
facade->GetName(phantom_node_vector.front().name_id, temp_string);
json_result.values["name"] = temp_string;
}
}
JSON::render(reply.content, json_result);
}

View file

@ -33,15 +33,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
template <class DataFacadeT> class TimestampPlugin : public BasePlugin
template <class DataFacadeT> class TimestampPlugin final : public BasePlugin
{
public:
explicit TimestampPlugin(const DataFacadeT *facade)
: facade(facade), descriptor_string("timestamp")
{
}
const std::string GetDescriptor() const { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
{
reply.status = http::Reply::ok;
JSON::Object json_result;

View file

@ -31,13 +31,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BasePlugin.h"
#include "../Algorithms/ObjectToBase64.h"
#include "../DataStructures/QueryEdge.h"
#include "../DataStructures/SearchEngine.h"
#include "../Descriptors/BaseDescriptor.h"
#include "../Descriptors/GPXDescriptor.h"
#include "../Descriptors/JSONDescriptor.h"
#include "../Util/SimpleLogger.h"
#include "../Util/make_unique.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/StringUtil.h"
#include "../Util/TimingUtil.h"
@ -49,16 +49,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
template <class DataFacadeT> class ViaRoutePlugin : public BasePlugin
template <class DataFacadeT> class ViaRoutePlugin final : public BasePlugin
{
private:
std::unordered_map<std::string, unsigned> descriptor_table;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
std::unique_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);
search_engine_ptr = osrm::make_unique<SearchEngine<DataFacadeT>>(facade);
descriptor_table.emplace("json", 0);
descriptor_table.emplace("gpx", 1);
@ -67,16 +67,18 @@ template <class DataFacadeT> class ViaRoutePlugin : public BasePlugin
virtual ~ViaRoutePlugin() {}
const std::string GetDescriptor() const { return descriptor_string; }
const std::string GetDescriptor() const final { return descriptor_string; }
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply)
void HandleRequest(const RouteParameters &route_parameters, http::Reply &reply) final
{
// check number of parameters
if (2 > route_parameters.coordinates.size() ||
std::any_of(begin(route_parameters.coordinates),
end(route_parameters.coordinates),
[&](FixedPointCoordinate coordinate)
{ return !coordinate.isValid(); }))
{
return !coordinate.isValid();
}))
{
reply = http::Reply::StockReply(http::Reply::badRequest);
return;
@ -97,7 +99,7 @@ template <class DataFacadeT> class ViaRoutePlugin : public BasePlugin
if (checksum_OK && i < route_parameters.hints.size() &&
!route_parameters.hints[i].empty())
{
DecodeObjectFromBase64(route_parameters.hints[i], phantom_node_vector[i]);
ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], phantom_node_vector[i]);
if (phantom_node_vector[i].isValid(facade->GetNumberOfNodes()))
{
continue;
@ -125,7 +127,8 @@ template <class DataFacadeT> class ViaRoutePlugin : public BasePlugin
}
else
{
search_engine_ptr->shortest_path(raw_route.segment_end_coordinates, route_parameters.uturns, raw_route);
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates, route_parameters.uturns, raw_route);
}
if (INVALID_EDGE_WEIGHT == raw_route.shortest_path_length)

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) |

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,9 @@ end
desc "Stop, reprocess and restart."
task :update => [:down,:process,:up] do
end
desc "Remove test cache files."
task :sweep do
system "rm test/cache/*"
end

View file

@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BasicRoutingInterface.h"
#include "../DataStructures/Range.h"
#include "../DataStructures/SearchEngineData.h"
#include "../Util/container.hpp"
#include <boost/assert.hpp>
@ -43,12 +44,12 @@ const double VIAPATH_ALPHA = 0.10;
const double VIAPATH_EPSILON = 0.15; // alternative at most 15% longer
const double VIAPATH_GAMMA = 0.75; // alternative shares at most 75% with the shortest.
template <class DataFacadeT> class AlternativeRouting : private BasicRoutingInterface<DataFacadeT>
template <class DataFacadeT> class AlternativeRouting final : private BasicRoutingInterface<DataFacadeT>
{
typedef BasicRoutingInterface<DataFacadeT> super;
typedef typename DataFacadeT::EdgeData EdgeData;
typedef SearchEngineData::QueryHeap QueryHeap;
typedef std::pair<NodeID, NodeID> SearchSpaceEdge;
using super = BasicRoutingInterface<DataFacadeT>;
using EdgeData = typename DataFacadeT::EdgeData;
using QueryHeap = SearchEngineData::QueryHeap;
using SearchSpaceEdge = std::pair<NodeID, NodeID>;
struct RankedCandidateNode
{
@ -172,7 +173,7 @@ template <class DataFacadeT> class AlternativeRouting : private BasicRoutingInte
return;
}
sort_unique_resize(via_node_candidate_list);
osrm::sort_unique_resize(via_node_candidate_list);
std::vector<NodeID> packed_forward_path;
std::vector<NodeID> packed_reverse_path;

View file

@ -31,8 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/RawRouteData.h"
#include "../DataStructures/SearchEngineData.h"
#include "../DataStructures/TurnInstructions.h"
#include "../Util/ContainerUtils.h"
#include "../Util/SimpleLogger.h"
// #include "../Util/simple_logger.hpp.h"
#include <boost/assert.hpp>
@ -98,7 +97,7 @@ template <class DataFacadeT> class BasicRoutingInterface
// Stalling
for (const auto edge : facade->GetAdjacentEdgeRange(node))
{
const EdgeData &data = facade->GetEdgeData(edge, node);
const EdgeData &data = facade->GetEdgeData(edge);
const bool reverse_flag = ((!forward_direction) ? data.forward : data.backward);
if (reverse_flag)
{
@ -119,7 +118,7 @@ template <class DataFacadeT> class BasicRoutingInterface
for (const auto edge : facade->GetAdjacentEdgeRange(node))
{
const EdgeData &data = facade->GetEdgeData(edge, node);
const EdgeData &data = facade->GetEdgeData(edge);
bool forward_directionFlag = (forward_direction ? data.forward : data.backward);
if (forward_directionFlag)
{
@ -164,7 +163,6 @@ template <class DataFacadeT> class BasicRoutingInterface
recursion_stack.emplace(packed_path[i - 1], packed_path[i]);
}
unpacked_path.emplace_back(packed_path[0], INVALID_EDGE_WEIGHT, TurnInstruction::NoTurn, INVALID_EDGE_WEIGHT);
std::pair<NodeID, NodeID> edge;
while (!recursion_stack.empty())
{
@ -181,17 +179,14 @@ template <class DataFacadeT> class BasicRoutingInterface
// facade->FindEdge does not suffice here in case of shortcuts.
// The above explanation unclear? Think!
EdgeID smaller_edge_id = SPECIAL_EDGEID;
NodeID smaller_node_id = SPECIAL_NODEID;
int edge_weight = std::numeric_limits<EdgeWeight>::max();
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.first);
const int weight = edgeData.distance;
const int weight = facade->GetEdgeData(edge_id).distance;
if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
edgeData.forward)
facade->GetEdgeData(edge_id).forward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.first;
edge_weight = weight;
}
}
@ -207,20 +202,18 @@ template <class DataFacadeT> class BasicRoutingInterface
{
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.second);
const int weight = edgeData.distance;
const int weight = facade->GetEdgeData(edge_id).distance;
if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
edgeData.backward)
facade->GetEdgeData(edge_id).backward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.second;
edge_weight = weight;
}
}
}
BOOST_ASSERT_MSG(edge_weight != INVALID_EDGE_WEIGHT, "edge id invalid");
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id);
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id);
if (ed.shortcut)
{ // unpack
const NodeID middle_node_id = ed.id;
@ -230,91 +223,91 @@ template <class DataFacadeT> class BasicRoutingInterface
}
else
{
unpacked_path.emplace_back(edge.second,
INVALID_EDGE_WEIGHT,
TurnInstruction::NoTurn,
ed.distance);
// BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut");
// unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id);
// const TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id);
BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut");
unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id);
const TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id);
const TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id);
// if (!facade->EdgeIsCompressed(ed.id))
// {
// BOOST_ASSERT(!facade->EdgeIsCompressed(ed.id));
// unpacked_path.emplace_back(facade->GetGeometryIndexForEdgeID(ed.id),
// name_index,
// turn_instruction,
// ed.distance);
// }
// else
// {
// std::vector<unsigned> id_vector;
// facade->GetUncompressedGeometry(facade->GetGeometryIndexForEdgeID(ed.id),
// id_vector);
// const std::size_t start_index =
// (unpacked_path.empty()
// ? ((start_traversed_in_reverse)
// ? id_vector.size() -
// phantom_node_pair.source_phantom.fwd_segment_position - 1
// : phantom_node_pair.source_phantom.fwd_segment_position)
// : 0);
// const std::size_t end_index = id_vector.size();
if (!facade->EdgeIsCompressed(ed.id))
{
BOOST_ASSERT(!facade->EdgeIsCompressed(ed.id));
unpacked_path.emplace_back(facade->GetGeometryIndexForEdgeID(ed.id),
name_index,
turn_instruction,
ed.distance,
travel_mode);
}
else
{
std::vector<unsigned> id_vector;
facade->GetUncompressedGeometry(facade->GetGeometryIndexForEdgeID(ed.id),
id_vector);
// BOOST_ASSERT(start_index >= 0);
// BOOST_ASSERT(start_index <= end_index);
// for (std::size_t i = start_index; i < end_index; ++i)
// {
// unpacked_path.emplace_back(id_vector[i], name_index, TurnInstruction::NoTurn, 0);
// }
// unpacked_path.back().turn_instruction = turn_instruction;
// unpacked_path.back().segment_duration = ed.distance;
// }
const std::size_t start_index =
(unpacked_path.empty()
? ((start_traversed_in_reverse)
? id_vector.size() -
phantom_node_pair.source_phantom.fwd_segment_position - 1
: phantom_node_pair.source_phantom.fwd_segment_position)
: 0);
const std::size_t end_index = id_vector.size();
BOOST_ASSERT(start_index >= 0);
BOOST_ASSERT(start_index <= end_index);
for (std::size_t i = start_index; i < end_index; ++i)
{
unpacked_path.emplace_back(id_vector[i], name_index, TurnInstruction::NoTurn, 0, travel_mode);
}
unpacked_path.back().turn_instruction = turn_instruction;
unpacked_path.back().segment_duration = ed.distance;
}
}
}
// if (SPECIAL_EDGEID != phantom_node_pair.target_phantom.packed_geometry_id)
// {
// std::vector<unsigned> id_vector;
// facade->GetUncompressedGeometry(phantom_node_pair.target_phantom.packed_geometry_id,
// id_vector);
// const bool is_local_path = (phantom_node_pair.source_phantom.packed_geometry_id ==
// phantom_node_pair.target_phantom.packed_geometry_id) &&
// unpacked_path.empty();
if (SPECIAL_EDGEID != phantom_node_pair.target_phantom.packed_geometry_id)
{
std::vector<unsigned> id_vector;
facade->GetUncompressedGeometry(phantom_node_pair.target_phantom.packed_geometry_id,
id_vector);
const bool is_local_path = (phantom_node_pair.source_phantom.packed_geometry_id ==
phantom_node_pair.target_phantom.packed_geometry_id) &&
unpacked_path.empty();
// std::size_t start_index = 0;
// if (is_local_path)
// {
// start_index = phantom_node_pair.source_phantom.fwd_segment_position;
// if (target_traversed_in_reverse)
// {
// start_index =
// id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position;
// }
// }
std::size_t start_index = 0;
if (is_local_path)
{
start_index = phantom_node_pair.source_phantom.fwd_segment_position;
if (target_traversed_in_reverse)
{
start_index =
id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position;
}
}
// std::size_t end_index = phantom_node_pair.target_phantom.fwd_segment_position;
// if (target_traversed_in_reverse)
// {
// std::reverse(id_vector.begin(), id_vector.end());
// end_index =
// id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position;
// }
std::size_t end_index = phantom_node_pair.target_phantom.fwd_segment_position;
if (target_traversed_in_reverse)
{
std::reverse(id_vector.begin(), id_vector.end());
end_index =
id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position;
}
// if (start_index > end_index)
// {
// start_index = std::min(start_index, id_vector.size()-1);
// }
if (start_index > end_index)
{
start_index = std::min(start_index, id_vector.size()-1);
}
// SimpleLogger().Write() << "start_index: " << start_index << ", end_index: " << end_index;
// for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i))
// {
// BOOST_ASSERT(i < id_vector.size());
// unpacked_path.emplace_back(PathData{id_vector[i],
// phantom_node_pair.target_phantom.name_id,
// TurnInstruction::NoTurn,
// 0});
// }
// }
for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i))
{
BOOST_ASSERT(i < id_vector.size());
BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode>0 );
unpacked_path.emplace_back(PathData{id_vector[i],
phantom_node_pair.target_phantom.name_id,
TurnInstruction::NoTurn,
0,
phantom_node_pair.target_phantom.forward_travel_mode});
}
}
// there is no equivalent to a node-based node in an edge-expanded graph.
// two equivalent routes may start (or end) at different node-based edges
@ -349,17 +342,14 @@ template <class DataFacadeT> class BasicRoutingInterface
recursion_stack.pop();
EdgeID smaller_edge_id = SPECIAL_EDGEID;
NodeID smaller_node_id = SPECIAL_NODEID;
int edge_weight = std::numeric_limits<EdgeWeight>::max();
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.first);
const int weight = edgeData.distance;
const int weight = facade->GetEdgeData(edge_id).distance;
if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) &&
edgeData.forward)
facade->GetEdgeData(edge_id).forward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.first;
edge_weight = weight;
}
}
@ -368,20 +358,18 @@ template <class DataFacadeT> class BasicRoutingInterface
{
for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second))
{
auto const & edgeData = facade->GetEdgeData(edge_id, edge.second);
const int weight = edgeData.distance;
const int weight = facade->GetEdgeData(edge_id).distance;
if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) &&
edgeData.backward)
facade->GetEdgeData(edge_id).backward)
{
smaller_edge_id = edge_id;
smaller_node_id = edge.second;
edge_weight = weight;
}
}
}
BOOST_ASSERT_MSG(edge_weight != std::numeric_limits<EdgeWeight>::max(), "edge weight invalid");
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id, smaller_node_id);
const EdgeData &ed = facade->GetEdgeData(smaller_edge_id);
if (ed.shortcut)
{ // unpack
const NodeID middle_node_id = ed.id;

View file

@ -39,10 +39,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <unordered_map>
#include <vector>
template <class DataFacadeT> class ManyToManyRouting : public BasicRoutingInterface<DataFacadeT>
template <class DataFacadeT> class ManyToManyRouting final : public BasicRoutingInterface<DataFacadeT>
{
typedef BasicRoutingInterface<DataFacadeT> super;
typedef SearchEngineData::QueryHeap QueryHeap;
using super = BasicRoutingInterface<DataFacadeT>;
using QueryHeap = SearchEngineData::QueryHeap;
SearchEngineData &engine_working_data;
struct NodeBucket
@ -54,7 +54,7 @@ template <class DataFacadeT> class ManyToManyRouting : public BasicRoutingInterf
{
}
};
typedef std::unordered_map<NodeID, std::vector<NodeBucket>> SearchSpaceWithBuckets;
using SearchSpaceWithBuckets = std::unordered_map<NodeID, std::vector<NodeBucket>>;
public:
ManyToManyRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)

View file

@ -35,10 +35,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../DataStructures/SearchEngineData.h"
#include "../typedefs.h"
template <class DataFacadeT> class ShortestPathRouting : public BasicRoutingInterface<DataFacadeT>
template <class DataFacadeT> class ShortestPathRouting final : public BasicRoutingInterface<DataFacadeT>
{
typedef BasicRoutingInterface<DataFacadeT> super;
typedef SearchEngineData::QueryHeap QueryHeap;
using super = BasicRoutingInterface<DataFacadeT>;
using QueryHeap = SearchEngineData::QueryHeap;
SearchEngineData &engine_working_data;
public:

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;
};

View file

@ -39,7 +39,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../../Util/StringUtil.h"
#include "../../typedefs.h"
#include "../../Include/osrm/Coordinate.h"
#include <osrm/Coordinate.h>
#include <string>
@ -62,7 +62,7 @@ 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 EdgeDataT GetEdgeData(const EdgeID e, NodeID node)
{
@ -70,8 +70,6 @@ template <class EdgeDataT> class BaseDataFacade
return edge;
}
// virtual const EdgeDataT &GetEdgeData( const EdgeID e ) const = 0;
virtual EdgeID BeginEdges(const NodeID n) const = 0;
virtual EdgeID EndEdges(const NodeID n) const = 0;
@ -98,6 +96,8 @@ template <class 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;
@ -106,10 +106,11 @@ template <class EdgeDataT> class BaseDataFacade
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 zoom_level,
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 unsigned GetCheckSum() const = 0;

View file

@ -42,7 +42,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../../Util/BoostFileSystemFix.h"
#include "../../Util/GraphLoader.h"
#include "../../Util/ProgramOptions.h"
#include "../../Util/SimpleLogger.h"
#include "../../Util/simple_logger.hpp"
#include <osrm/Coordinate.h>
@ -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;
@ -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)
@ -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())
{
@ -372,7 +379,7 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
bool FindPhantomNodeForCoordinate(const FixedPointCoordinate &input_coordinate,
PhantomNode &resulting_phantom_node,
const unsigned zoom_level)
const unsigned zoom_level) final
{
if (!m_static_rtree.get())
{
@ -387,7 +394,7 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
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())
{
@ -398,14 +405,14 @@ template <class EdgeDataT> class InternalDataFacade : public BaseDataFacade<Edge
input_coordinate, resulting_phantom_node_vector, zoom_level, number_of_results);
}
unsigned GetCheckSum() const { return m_check_sum; }
unsigned GetCheckSum() const final { return m_check_sum; }
unsigned GetNameIndexFromEdgeID(const unsigned id) const
unsigned GetNameIndexFromEdgeID(const unsigned id) const final
{
return m_name_ID_list.at(id);
};
void GetName(const unsigned name_id, std::string &result) const
void GetName(const unsigned name_id, std::string &result) const final
{
if (UINT_MAX == name_id)
{
@ -424,13 +431,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 +447,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

View file

@ -38,7 +38,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "../../DataStructures/StaticRTree.h"
#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 +56,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 +69,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 +113,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 +141,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 +189,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 +199,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 +224,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;
@ -271,7 +276,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).isValid())
{
SimpleLogger().Write() << "coordinate " << i << " not valid";
}
@ -280,55 +285,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,39 +342,44 @@ 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)
const unsigned zoom_level) final
{
if (!m_static_rtree.get())
if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first)
{
LoadRTree();
}
return m_static_rtree->FindPhantomNodeForCoordinate(
return m_static_rtree->second->FindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node, zoom_level);
}
@ -378,25 +387,25 @@ template <class EdgeDataT> class SharedDataFacade : public BaseDataFacade<EdgeDa
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(
return m_static_rtree->second->IncrementalFindPhantomNodeForCoordinate(
input_coordinate, resulting_phantom_node_vector, zoom_level, number_of_results);
}
unsigned GetCheckSum() const { return m_check_sum; }
unsigned GetCheckSum() const final { return m_check_sum; }
unsigned GetNameIndexFromEdgeID(const unsigned id) const
unsigned GetNameIndexFromEdgeID(const unsigned id) const final
{
return m_name_ID_list.at(id);
};
void GetName(const unsigned name_id, std::string &result) const
void GetName(const unsigned name_id, std::string &result) const final
{
if (UINT_MAX == name_id)
{
@ -415,7 +424,7 @@ template <class 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

View file

@ -29,14 +29,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define SHARED_DATA_TYPE_H_
#include "../../Util/OSRMException.h"
#include "../../Util/SimpleLogger.h"
#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 );

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;
}

View file

@ -25,13 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "APIGrammar.h"
#include "RequestHandler.h"
#include "APIGrammar.h"
#include "Http/Request.h"
#include "../DataStructures/JSONContainer.h"
#include "../Library/OSRM.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
@ -61,17 +62,17 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply
// req.agent << ( 0 == req.agent.length() ? "- " :" ") << request;
time_t ltime;
struct tm *Tm;
struct tm *time_stamp;
ltime = time(nullptr);
Tm = localtime(&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 +88,11 @@ void RequestHandler::handle_request(const http::Request &req, http::Reply &reply
{
reply = http::Reply::StockReply(http::Reply::badRequest);
reply.content.clear();
const unsigned position = static_cast<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 +113,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");

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;

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
{
@ -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'; }
}

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));

View file

@ -0,0 +1,127 @@
#ifndef MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP
#define MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP
#include <utility>
namespace mapbox { namespace util {
template <typename T>
class recursive_wrapper
{
public:
using type = T;
private:
T* p_;
public:
~recursive_wrapper();
recursive_wrapper();
recursive_wrapper(recursive_wrapper const& operand);
recursive_wrapper(T const& operand);
recursive_wrapper(recursive_wrapper&& operand);
recursive_wrapper(T&& operand);
private:
void assign(const T& rhs);
public:
inline recursive_wrapper& operator=(recursive_wrapper const& rhs)
{
assign( rhs.get() );
return *this;
}
inline recursive_wrapper& operator=(T const& rhs)
{
assign( rhs );
return *this;
}
inline void swap(recursive_wrapper& operand) noexcept
{
T* temp = operand.p_;
operand.p_ = p_;
p_ = temp;
}
recursive_wrapper& operator=(recursive_wrapper&& rhs) noexcept
{
swap(rhs);
return *this;
}
recursive_wrapper& operator=(T&& rhs)
{
get() = std::move(rhs);
return *this;
}
public:
T& get() { return *get_pointer(); }
const T& get() const { return *get_pointer(); }
T* get_pointer() { return p_; }
const T* get_pointer() const { return p_; }
operator T const&() const { return this->get(); }
operator T&() { return this->get(); }
};
template <typename T>
recursive_wrapper<T>::~recursive_wrapper()
{
delete p_;
}
template <typename T>
recursive_wrapper<T>::recursive_wrapper()
: p_(new T)
{
}
template <typename T>
recursive_wrapper<T>::recursive_wrapper(recursive_wrapper const& operand)
: p_(new T( operand.get() ))
{
}
template <typename T>
recursive_wrapper<T>::recursive_wrapper(T const& operand)
: p_(new T(operand))
{
}
template <typename T>
recursive_wrapper<T>::recursive_wrapper(recursive_wrapper&& operand)
: p_(operand.p_)
{
operand.p_ = nullptr;
}
template <typename T>
recursive_wrapper<T>::recursive_wrapper(T&& operand)
: p_(new T( std::move(operand) ))
{
}
template <typename T>
void recursive_wrapper<T>::assign(const T& rhs)
{
this->get() = rhs;
}
template <typename T>
inline void swap(recursive_wrapper<T>& lhs, recursive_wrapper<T>& rhs) noexcept
{
lhs.swap(rhs);
}
}}
#endif // MAPBOX_UTIL_VARIANT_RECURSIVE_WRAPPER_HPP

View file

@ -0,0 +1,740 @@
#ifndef MAPBOX_UTIL_VARIANT_HPP
#define MAPBOX_UTIL_VARIANT_HPP
#include <utility>
#include <typeinfo>
#include <type_traits>
#include <stdexcept> // runtime_error
#include <new> // operator new
#include <cstddef> // size_t
#include <iosfwd>
#include <string>
#include "recursive_wrapper.hpp"
#ifdef _MSC_VER
// http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
#ifdef NDEBUG
#define VARIANT_INLINE __forceinline
#else
#define VARIANT_INLINE __declspec(noinline)
#endif
#else
#ifdef NDEBUG
#define VARIANT_INLINE inline __attribute__((always_inline))
#else
#define VARIANT_INLINE __attribute__((noinline))
#endif
#endif
#define VARIANT_MAJOR_VERSION 0
#define VARIANT_MINOR_VERSION 1
#define VARIANT_PATCH_VERSION 0
// translates to 100
#define VARIANT_VERSION (VARIANT_MAJOR_VERSION*100000) + (VARIANT_MINOR_VERSION*100) + (VARIANT_PATCH_VERSION)
namespace mapbox { namespace util { namespace detail {
static constexpr std::size_t invalid_value = std::size_t(-1);
template <typename T, typename...Types>
struct direct_type;
template <typename T, typename First, typename...Types>
struct direct_type<T, First, Types...>
{
static constexpr std::size_t index = std::is_same<T, First>::value
? sizeof...(Types) : direct_type<T, Types...>::index;
};
template <typename T>
struct direct_type<T>
{
static constexpr std::size_t index = invalid_value;
};
template <typename T, typename...Types>
struct convertible_type;
template <typename T, typename First, typename...Types>
struct convertible_type<T, First, Types...>
{
static constexpr std::size_t index = std::is_convertible<T, First>::value
? sizeof...(Types) : convertible_type<T, Types...>::index;
};
template <typename T>
struct convertible_type<T>
{
static constexpr std::size_t index = invalid_value;
};
template <typename T, typename...Types>
struct value_traits
{
static constexpr std::size_t direct_index = direct_type<T, Types...>::index;
static constexpr std::size_t index =
(direct_index == invalid_value) ? convertible_type<T, Types...>::index : direct_index;
};
template <typename T, typename...Types>
struct is_valid_type;
template <typename T, typename First, typename... Types>
struct is_valid_type<T, First, Types...>
{
static constexpr bool value = std::is_convertible<T, First>::value
|| is_valid_type<T, Types...>::value;
};
template <typename T>
struct is_valid_type<T> : std::false_type {};
template <std::size_t N, typename ... Types>
struct select_type
{
static_assert(N < sizeof...(Types), "index out of bounds");
};
template <std::size_t N, typename T, typename ... Types>
struct select_type<N, T, Types...>
{
using type = typename select_type<N - 1, Types...>::type;
};
template <typename T, typename ... Types>
struct select_type<0, T, Types...>
{
using type = T;
};
} // namespace detail
// static visitor
template <typename R = void>
struct static_visitor
{
using result_type = R;
protected:
static_visitor() {}
~static_visitor() {}
};
template <std::size_t arg1, std::size_t ... others>
struct static_max;
template <std::size_t arg>
struct static_max<arg>
{
static const std::size_t value = arg;
};
template <std::size_t arg1, std::size_t arg2, std::size_t ... others>
struct static_max<arg1, arg2, others...>
{
static const std::size_t value = arg1 >= arg2 ? static_max<arg1, others...>::value :
static_max<arg2, others...>::value;
};
template<typename... Types>
struct variant_helper;
template<typename T, typename... Types>
struct variant_helper<T, Types...>
{
VARIANT_INLINE static void destroy(const std::size_t id, void * data)
{
if (id == sizeof...(Types))
{
reinterpret_cast<T*>(data)->~T();
}
else
{
variant_helper<Types...>::destroy(id, data);
}
}
VARIANT_INLINE static void move(const std::size_t old_id, void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(std::move(*reinterpret_cast<T*>(old_value)));
//std::memcpy(new_value, old_value, sizeof(T));
// ^^ DANGER: this should only be considered for relocatable types e.g built-in types
// Also, I don't see any measurable performance benefit just yet
}
else
{
variant_helper<Types...>::move(old_id, old_value, new_value);
}
}
VARIANT_INLINE static void copy(const std::size_t old_id, const void * old_value, void * new_value)
{
if (old_id == sizeof...(Types))
{
new (new_value) T(*reinterpret_cast<const T*>(old_value));
}
else
{
variant_helper<Types...>::copy(old_id, old_value, new_value);
}
}
};
template<> struct variant_helper<>
{
VARIANT_INLINE static void destroy(const std::size_t, void *) {}
VARIANT_INLINE static void move(const std::size_t, void *, void *) {}
VARIANT_INLINE static void copy(const std::size_t, const void *, void *) {}
};
namespace detail {
template <typename T>
struct unwrapper
{
T const& operator() (T const& obj) const
{
return obj;
}
T& operator() (T & obj) const
{
return obj;
}
};
template <typename T>
struct unwrapper<recursive_wrapper<T>>
{
auto operator() (recursive_wrapper<T> const& obj) const
-> typename recursive_wrapper<T>::type const&
{
return obj.get();
}
};
template <typename F, typename V, typename...Types>
struct dispatcher;
template <typename F, typename V, typename T, typename...Types>
struct dispatcher<F, V, T, Types...>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const& v, F f)
{
if (v.get_type_index() == sizeof...(Types))
{
return f(unwrapper<T>()(v. template get<T>()));
}
else
{
return dispatcher<F, V, Types...>::apply_const(v, f);
}
}
VARIANT_INLINE static result_type apply(V & v, F f)
{
if (v.get_type_index() == sizeof...(Types))
{
return f(unwrapper<T>()(v. template get<T>()));
}
else
{
return dispatcher<F, V, Types...>::apply(v, f);
}
}
};
template<typename F, typename V>
struct dispatcher<F, V>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const&, F)
{
throw std::runtime_error(std::string("unary dispatch: FAIL ") + typeid(V).name());
}
VARIANT_INLINE static result_type apply(V &, F)
{
throw std::runtime_error(std::string("unary dispatch: FAIL ") + typeid(V).name());
}
};
template <typename F, typename V, typename T, typename...Types>
struct binary_dispatcher_rhs;
template <typename F, typename V, typename T0, typename T1, typename...Types>
struct binary_dispatcher_rhs<F, V, T0, T1, Types...>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f)
{
if (rhs.get_type_index() == sizeof...(Types)) // call binary functor
{
return f(unwrapper<T0>()(lhs. template get<T0>()),
unwrapper<T1>()(rhs. template get<T1>()));
}
else
{
return binary_dispatcher_rhs<F, V, T0, Types...>::apply_const(lhs, rhs, f);
}
}
VARIANT_INLINE static result_type apply(V & lhs, V & rhs, F f)
{
if (rhs.get_type_index() == sizeof...(Types)) // call binary functor
{
return f(unwrapper<T0>()(lhs. template get<T0>()),
unwrapper<T1>()(rhs. template get<T1>()));
}
else
{
return binary_dispatcher_rhs<F, V, T0, Types...>::apply(lhs, rhs, f);
}
}
};
template<typename F, typename V, typename T>
struct binary_dispatcher_rhs<F, V, T>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const&, V const&, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
VARIANT_INLINE static result_type apply(V &, V &, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
};
template <typename F, typename V, typename T, typename...Types>
struct binary_dispatcher_lhs;
template <typename F, typename V, typename T0, typename T1, typename...Types>
struct binary_dispatcher_lhs<F, V, T0, T1, Types...>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const& lhs, V const& rhs, F f)
{
if (lhs.get_type_index() == sizeof...(Types)) // call binary functor
{
return f(lhs. template get<T1>(), rhs. template get<T0>());
}
else
{
return binary_dispatcher_lhs<F, V, T0, Types...>::apply_const(lhs, rhs, f);
}
}
VARIANT_INLINE static result_type apply(V & lhs, V & rhs, F f)
{
if (lhs.get_type_index() == sizeof...(Types)) // call binary functor
{
return f(lhs. template get<T1>(), rhs. template get<T0>());
}
else
{
return binary_dispatcher_lhs<F, V, T0, Types...>::apply(lhs, rhs, f);
}
}
};
template<typename F, typename V, typename T>
struct binary_dispatcher_lhs<F, V, T>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const&, V const&, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
VARIANT_INLINE static result_type apply(V &, V &, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
};
template <typename F, typename V, typename...Types>
struct binary_dispatcher;
template <typename F, typename V, typename T, typename...Types>
struct binary_dispatcher<F, V, T, Types...>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const& v0, V const& v1, F f)
{
if (v0.get_type_index() == sizeof...(Types))
{
if (v0.get_type_index() == v1.get_type_index())
{
return f(v0. template get<T>(), v1. template get<T>()); // call binary functor
}
else
{
return binary_dispatcher_rhs<F, V, T, Types...>::apply_const(v0, v1, f);
}
}
else if (v1.get_type_index() == sizeof...(Types))
{
return binary_dispatcher_lhs<F, V, T, Types...>::apply_const(v0, v1, f);
}
return binary_dispatcher<F, V, Types...>::apply_const(v0, v1, f);
}
VARIANT_INLINE static result_type apply(V & v0, V & v1, F f)
{
if (v0.get_type_index() == sizeof...(Types))
{
if (v0.get_type_index() == v1.get_type_index())
{
return f(v0. template get<T>(), v1. template get<T>()); // call binary functor
}
else
{
return binary_dispatcher_rhs<F, V, T, Types...>::apply(v0, v1, f);
}
}
else if (v1.get_type_index() == sizeof...(Types))
{
return binary_dispatcher_lhs<F, V, T, Types...>::apply(v0, v1, f);
}
return binary_dispatcher<F, V, Types...>::apply(v0, v1, f);
}
};
template<typename F, typename V>
struct binary_dispatcher<F, V>
{
using result_type = typename F::result_type;
VARIANT_INLINE static result_type apply_const(V const&, V const&, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
VARIANT_INLINE static result_type apply(V &, V &, F)
{
throw std::runtime_error("binary dispatch: FAIL");
}
};
// comparator functors
struct equal_comp
{
template <typename T>
bool operator()(T const& lhs, T const& rhs) const
{
return lhs == rhs;
}
};
struct less_comp
{
template <typename T>
bool operator()(T const& lhs, T const& rhs) const
{
return lhs < rhs;
}
};
template <typename Variant, typename Comp>
class comparer : public static_visitor<bool>
{
public:
explicit comparer(Variant const& lhs) noexcept
: lhs_(lhs) {}
comparer& operator=(comparer const&) = delete;
// visitor
template<typename T>
bool operator()(T const& rhs_content) const
{
T const& lhs_content = lhs_.template get<T>();
return Comp()(lhs_content, rhs_content);
}
private:
Variant const& lhs_;
};
// operator<< helper
template <typename Out>
class printer : public static_visitor<>
{
public:
explicit printer(Out & out)
: out_(out) {}
printer& operator=(printer const&) = delete;
// visitor
template <typename T>
void operator()(T const& operand) const
{
out_ << operand;
}
private:
Out & out_;
};
} // namespace detail
struct no_init {};
template<typename... Types>
class variant
{
private:
static const std::size_t data_size = static_max<sizeof(Types)...>::value;
static const std::size_t data_align = static_max<alignof(Types)...>::value;
using data_type = typename std::aligned_storage<data_size, data_align>::type;
using helper_type = variant_helper<Types...>;
std::size_t type_index;
data_type data;
public:
VARIANT_INLINE variant()
: type_index(sizeof...(Types) - 1)
{
new (&data) typename detail::select_type<0, Types...>::type();
}
VARIANT_INLINE variant(no_init)
: type_index(detail::invalid_value) {}
// http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers
template <typename T, class = typename std::enable_if<
detail::is_valid_type<typename std::remove_reference<T>::type, Types...>::value>::type>
VARIANT_INLINE variant(T && val) noexcept
: type_index(detail::value_traits<typename std::remove_reference<T>::type, Types...>::index)
{
constexpr std::size_t index = sizeof...(Types) - detail::value_traits<typename std::remove_reference<T>::type, Types...>::index - 1;
using target_type = typename detail::select_type<index, Types...>::type;
new (&data) target_type(std::forward<T>(val)); // nothrow
}
VARIANT_INLINE variant(variant<Types...> const& old)
: type_index(old.type_index)
{
helper_type::copy(old.type_index, &old.data, &data);
}
VARIANT_INLINE variant(variant<Types...>&& old) noexcept
: type_index(old.type_index)
{
helper_type::move(old.type_index, &old.data, &data);
}
friend void swap(variant<Types...> & first, variant<Types...> & second)
{
using std::swap; //enable ADL
swap(first.type_index, second.type_index);
swap(first.data, second.data);
}
VARIANT_INLINE variant<Types...>& operator=(variant<Types...> other)
{
swap(*this, other);
return *this;
}
// conversions
// move-assign
template <typename T>
VARIANT_INLINE variant<Types...>& operator=(T && rhs) noexcept
{
variant<Types...> temp(std::forward<T>(rhs));
swap(*this, temp);
return *this;
}
// copy-assign
template <typename T>
VARIANT_INLINE variant<Types...>& operator=(T const& rhs)
{
variant<Types...> temp(rhs);
swap(*this, temp);
return *this;
}
template<typename T>
VARIANT_INLINE bool is() const
{
return (type_index == detail::direct_type<T, Types...>::index);
}
VARIANT_INLINE bool valid() const
{
return (type_index != detail::invalid_value);
}
template<typename T, typename... Args>
VARIANT_INLINE void set(Args&&... args)
{
helper_type::destroy(type_index, &data);
new (&data) T(std::forward<Args>(args)...);
type_index = detail::direct_type<T, Types...>::index;
}
template<typename T>
VARIANT_INLINE T& get()
{
if (type_index == detail::direct_type<T, Types...>::index)
{
return *reinterpret_cast<T*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
template<typename T>
VARIANT_INLINE T const& get() const
{
if (type_index == detail::direct_type<T, Types...>::index)
{
return *reinterpret_cast<T const*>(&data);
}
else
{
throw std::runtime_error("in get()");
}
}
VARIANT_INLINE std::size_t get_type_index() const
{
return type_index;
}
// visitor
// unary
template <typename F, typename V>
auto VARIANT_INLINE
static visit(V const& v, F f)
-> decltype(detail::dispatcher<F, V, Types...>::apply_const(v, f))
{
return detail::dispatcher<F, V, Types...>::apply_const(v, f);
}
// non-const
template <typename F, typename V>
auto VARIANT_INLINE
static visit(V & v, F f)
-> decltype(detail::dispatcher<F, V, Types...>::apply(v, f))
{
return detail::dispatcher<F, V, Types...>::apply(v, f);
}
// binary
// const
template <typename F, typename V>
auto VARIANT_INLINE
static binary_visit(V const& v0, V const& v1, F f)
-> decltype(detail::binary_dispatcher<F, V, Types...>::apply_const(v0, v1, f))
{
return detail::binary_dispatcher<F, V, Types...>::apply_const(v0, v1, f);
}
// non-const
template <typename F, typename V>
auto VARIANT_INLINE
static binary_visit(V& v0, V& v1, F f)
-> decltype(detail::binary_dispatcher<F, V, Types...>::apply(v0, v1, f))
{
return detail::binary_dispatcher<F, V, Types...>::apply(v0, v1, f);
}
~variant() noexcept
{
helper_type::destroy(type_index, &data);
}
// comparison operators
// equality
VARIANT_INLINE bool operator==(variant const& rhs) const
{
if (this->get_type_index() != rhs.get_type_index())
return false;
detail::comparer<variant, detail::equal_comp> visitor(*this);
return visit(rhs, visitor);
}
// less than
VARIANT_INLINE bool operator<(variant const& rhs) const
{
if (this->get_type_index() != rhs.get_type_index())
{
return this->get_type_index() < rhs.get_type_index();
// ^^ borrowed from boost::variant
}
detail::comparer<variant, detail::less_comp> visitor(*this);
return visit(rhs, visitor);
}
};
// unary visitor interface
// const
template <typename V, typename F>
auto VARIANT_INLINE static apply_visitor(F f, V const& v) -> decltype(V::visit(v, f))
{
return V::visit(v, f);
}
// non-const
template <typename V, typename F>
auto VARIANT_INLINE static apply_visitor(F f, V & v) -> decltype(V::visit(v, f))
{
return V::visit(v, f);
}
// binary visitor interface
// const
template <typename V, typename F>
auto VARIANT_INLINE static apply_visitor(F f, V const& v0, V const& v1) -> decltype(V::binary_visit(v0, v1, f))
{
return V::binary_visit(v0, v1, f);
}
// non-const
template <typename V, typename F>
auto VARIANT_INLINE static apply_visitor(F f, V & v0, V & v1) -> decltype(V::binary_visit(v0, v1, f))
{
return V::binary_visit(v0, v1, f);
}
// getter interface
template<typename ResultType, typename T>
ResultType & get(T & var)
{
return var.template get<ResultType>();
}
template<typename ResultType, typename T>
ResultType const& get(T const& var)
{
return var.template get<ResultType>();
}
// operator<<
template <typename charT, typename traits, typename... Types>
VARIANT_INLINE std::basic_ostream<charT, traits>&
operator<< (std::basic_ostream<charT, traits>& out, variant<Types...> const& rhs)
{
detail::printer<std::basic_ostream<charT, traits>> visitor(out);
apply_visitor(visitor, rhs);
return out;
}
}}
#endif // MAPBOX_UTIL_VARIANT_HPP

View file

@ -24,13 +24,13 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../DataStructures/DeallocatingVector.h"
#include "../DataStructures/Percent.h"
#include "../DataStructures/QueryEdge.h"
#include "../DataStructures/Range.h"
#include "../DataStructures/StaticGraph.h"
#include "../Util/GraphLoader.h"
#include "../Util/SimpleLogger.h"
#include "../Util/simple_logger.hpp"
#include "../Util/OSRMException.h"
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
@ -38,69 +38,68 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
#include <vector>
typedef QueryEdge::EdgeData EdgeData;
typedef StaticGraph<EdgeData> QueryGraph;
using EdgeData = QueryEdge::EdgeData;
using QueryGraph = StaticGraph<EdgeData>;
int main(int argc, char *argv[])
{
LogPolicy::GetInstance().Unmute();
if (argc != 2)
{
SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " <file.hsgr>";
return 1;
}
try
{
if (argc != 2)
{
SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " <file.hsgr>";
return 1;
}
boost::filesystem::path hsgr_path(argv[1]);
std::vector<QueryGraph::NodeArrayEntry> node_list;
std::vector<QueryGraph::EdgeArrayEntry> edge_list;
SimpleLogger().Write() << "loading graph from " << hsgr_path.string();
unsigned m_check_sum = 0;
unsigned m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum);
SimpleLogger().Write() << "announced " << m_number_of_nodes
unsigned m_number_of_nodes =
readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum);
SimpleLogger().Write() << "expecting " << m_number_of_nodes
<< " nodes, checksum: " << m_check_sum;
BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty");
// BOOST_ASSERT_MSG(0 != edge_list.size(), "edge list empty");
SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size()
<< " edges";
std::shared_ptr<QueryGraph> m_query_graph = std::make_shared<QueryGraph>(node_list, edge_list);
auto m_query_graph = std::make_shared<QueryGraph>(node_list, edge_list);
BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed");
BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed");
Percent p(m_query_graph->GetNumberOfNodes());
for (const auto u : osrm::irange(0u, m_query_graph->GetNumberOfNodes()))
Percent progress(m_query_graph->GetNumberOfNodes());
for (const auto node_u : osrm::irange(0u, m_query_graph->GetNumberOfNodes()))
{
for (const auto eid : m_query_graph->GetAdjacentEdgeRange(u))
for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u))
{
const EdgeData &data = m_query_graph->GetEdgeData(eid);
if (!data.shortcut)
{
continue;
}
const unsigned v = m_query_graph->GetTarget(eid);
const EdgeID first_edge_id = m_query_graph->FindEdgeInEitherDirection(u, data.id);
if (SPECIAL_EDGEID == first_edge_id)
const unsigned node_v = m_query_graph->GetTarget(eid);
const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id);
if (SPECIAL_EDGEID == edge_id_1)
{
SimpleLogger().Write(logWARNING) << "cannot find first segment of edge (" << u
<< "," << data.id << "," << v << "), eid: " << eid;
BOOST_ASSERT(false);
return 1;
throw OSRMException("cannot find first segment of edge (" +
std::to_string(node_u) + "," + std::to_string(data.id) +
"," + std::to_string(node_v) + "), eid: " +
std::to_string(eid));
}
const EdgeID second_edge_id = m_query_graph->FindEdgeInEitherDirection(data.id, v);
if (SPECIAL_EDGEID == second_edge_id)
const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v);
if (SPECIAL_EDGEID == edge_id_2)
{
SimpleLogger().Write(logWARNING) << "cannot find second segment of edge (" << u
<< "," << data.id << "," << v << "), eid: " << eid;
BOOST_ASSERT(false);
return 1;
throw OSRMException("cannot find second segment of edge (" +
std::to_string(node_u) + "," + std::to_string(data.id) +
"," + std::to_string(node_v) + "), eid: " +
std::to_string(eid));
}
}
p.printIncrement();
progress.printStatus(node_u);
}
m_query_graph.reset();
SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK";

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