Repository navigation
[GSoC] Pedestrian area routing: Build area polygons and generate medial axis - #6195
Conversation
There was a problem hiding this comment.
Added two new build stages. kParseAreaWays and kBuildAreas
| // Second pass over the ways to collect the geometry of ways that | ||
| // are members of pedestrian area relations | ||
| if (start_stage <= BuildStage::kParseAreaWays && BuildStage::kParseAreaWays <= end_stage) { | ||
| if (config.get<bool>("mjolnir.pedestrian_areas", false)) { | ||
| PBFGraphParser::ParseAreaWays(config.get_child("mjolnir"), input_files, ways_bin, way_nodes_bin, | ||
| osm_data); | ||
|
|
||
| // Write the OSMData to files if the end stage is less than enhancing | ||
| if (end_stage <= BuildStage::kEnhance) { | ||
| osm_data.write_to_temp_files(tile_dir); | ||
| } | ||
| } | ||
| log_stage(BuildStage::kParseAreaWays); | ||
| } | ||
|
|
There was a problem hiding this comment.
Runs ParseAreaWays only when the pedestrian_areas option is on. This stage is needed because members ways of pedestrian area relations, weren't parsed because the order of the stages
| // Builds pedestrian areas | ||
| if (start_stage <= BuildStage::kBuildAreas && BuildStage::kBuildAreas <= end_stage) { | ||
| if (config.get<bool>("mjolnir.pedestrian_areas", false)) { | ||
| AreaBuilder::BuildAreas(config.get_child("mjolnir"), ways_bin, way_nodes_bin, osm_data); | ||
|
|
||
| // Write the OSMData to files if the end stage is less than enhancing | ||
| if (end_stage <= BuildStage::kEnhance) { | ||
| osm_data.write_to_temp_files(tile_dir); | ||
| } | ||
| } | ||
| log_stage(BuildStage::kBuildAreas); | ||
| } | ||
|
|
There was a problem hiding this comment.
Calls, AreaBuilder::BuildAreas, gated behind the pedestrian_areas option. This is where polygons and medial axis get built, before kContructEdges
| // TODO: doxygen comment | ||
| static void ParseAreaWays(const boost::property_tree::ptree& pt, | ||
| const std::vector<std::string>& input_files, | ||
| const std::string& ways_file, | ||
| const std::string& way_nodes_file, | ||
| OSMData& osmdata); | ||
|
|
There was a problem hiding this comment.
Second selective pass over the ways. Declared static like the other Parse* methods. It reads area_relations to know which member ways to collect
|
|
||
| #include <string> | ||
|
|
||
| typedef struct GEOSGeom_t GEOSGeometry; |
There was a problem hiding this comment.
forward declaration so we don't have geos_c.h in the header
There was a problem hiding this comment.
why make GenerateMedialAxis a member of AreaBuilder anyway? I'd suggest to just define it as a free standing function in an anonymous namespace in the source file.
There was a problem hiding this comment.
I know we have this weird convention to wrap the functions that represent a build stage into a class, but feel free to break that pattern if it does not make sense to you.
| void PBFGraphParser::ParseAreaWays(const boost::property_tree::ptree& pt, | ||
| const std::vector<std::string>& input_files, | ||
| const std::string& ways_file, | ||
| const std::string& way_nodes_file, | ||
| OSMData& osmdata) { | ||
| SCOPED_TIMER(); | ||
|
|
||
| // we need area_relations to know which ways to collect, read it from disk if needed | ||
| if (!osmdata.initialized) | ||
| osmdata.read_from_temp_files(pt.get<std::string>("tile_dir")); | ||
|
|
||
| // nothing to do if there are no area relations | ||
| if (osmdata.area_relations.empty()) | ||
| return; | ||
|
|
||
| // collect the way ids we need (outer and inner members of the area relations) | ||
| std::unordered_set<uint64_t> needed_way_ids; | ||
| for (const auto& entry : osmdata.area_relations) | ||
| needed_way_ids.insert(entry.second.way_id); | ||
|
|
||
| LOG_INFO("Parsing area ways... looking for " + std::to_string(needed_way_ids.size()) + " ways"); | ||
|
|
||
| // open the existing ways/way_nodes files | ||
| sequence<OSMWay> ways(ways_file, false); | ||
| sequence<OSMWayNode> way_nodes(way_nodes_file, false); | ||
|
|
||
| uint32_t found = 0; | ||
| for (const auto& file : input_files) { | ||
| osmium::io::Reader reader(file, osmium::osm_entity_bits::way); | ||
| while (osmium::memory::Buffer buffer = reader.read()) { | ||
| for (const auto& item : buffer) { | ||
| const auto& osm_way = static_cast<const osmium::Way&>(item); | ||
|
|
||
| // skip ways we don't care about | ||
| if (!needed_way_ids.count(static_cast<uint64_t>(osm_way.id()))) | ||
| continue; | ||
|
|
||
| // gather the node ids of this way | ||
| std::vector<uint64_t> nodes; | ||
| nodes.reserve(osm_way.nodes().size()); | ||
| for (const auto& node : osm_way.nodes()) { | ||
| nodes.push_back(node.ref()); | ||
| } | ||
|
|
||
| // Do not add ways with < 2 nodes. Log error or add to a problem list | ||
| // TODO - find out if we do need these, why they exist... | ||
| if (nodes.size() < 2) | ||
| continue; | ||
|
|
||
| // the index this way will have in the ways file | ||
| uint32_t way_index = static_cast<uint32_t>(ways.size()); | ||
|
|
||
| // store each node as a way node referencing this way by index | ||
| for (size_t i = 0; i < nodes.size(); ++i) { | ||
| OSMNode osm_node{nodes[i]}; | ||
| osm_node.intersection_ = i == 0 || i == nodes.size() - 1; | ||
| way_nodes.push_back({osm_node, way_index, static_cast<uint32_t>(i)}); | ||
| } | ||
|
|
||
| // build the way with the area bit set, no lua transform needed | ||
| OSMWay w{static_cast<uint64_t>(osm_way.id())}; | ||
| w.set_node_count(nodes.size()); | ||
| w.set_area(true); | ||
| ways.push_back(w); | ||
| ++found; | ||
| } | ||
| } | ||
| reader.close(); | ||
| } | ||
|
|
||
| LOG_INFO("Finished parsing area ways, found " + std::to_string(found) + " of " + | ||
| std::to_string(needed_way_ids.size())); | ||
| } | ||
|
|
There was a problem hiding this comment.
Second pass over the PBF but without lua. We only keep those ways whose id is in our relation ways set. Appends each collected way to ways.bin and way_nodes.bin with the area bit set. The coordinates get filled in later during ParseNodes
| } | ||
|
|
||
| TEST(area_routing, area_member_ways_collected) { | ||
| const std::string ascii_map = R"( | ||
| A----B | ||
| | | | ||
| D----C | ||
| )"; | ||
|
|
||
| // the member way has no routable tags, so lua discards it during ParseWays | ||
| const gurka::ways ways = { | ||
| {"ABCDA", {}}, | ||
| }; | ||
|
|
||
| // the relation carries the area tags | ||
| const gurka::relations relations = { | ||
| {{{ | ||
| {gurka::way_member, "ABCDA", "outer"}, | ||
| }}, | ||
| {{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}}, | ||
| }; | ||
|
|
||
| const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100); | ||
| const std::string workdir = "test/data/gurka_area_members"; | ||
|
|
||
| // run up to ParseRelations, the member way was discarded by lua | ||
| auto map = | ||
| gurka::buildtiles(layout, ways, {}, relations, workdir, | ||
| {{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}}, | ||
| mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kParseRelations); | ||
|
|
||
| EXPECT_THROW(gurka::findWay(map, "ABCDA"), std::runtime_error); | ||
|
|
||
| // run the new stage on top of the partial build | ||
| gurka::buildtiles(layout, ways, {}, relations, workdir, | ||
| {{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}}, | ||
| mjolnir::BuildStage::kParseAreaWays, mjolnir::BuildStage::kParseAreaWays); | ||
|
|
||
| // now the member way was collected with the area bit set | ||
| auto way = gurka::findWay(map, "ABCDA"); | ||
| EXPECT_TRUE(way.area()); | ||
|
|
||
| // its geometry was collected too. Coords aren't yet since ParseNodes runs after ParseAreaWays | ||
| auto b_nodes = gurka::findWayNodes(map, "B"); | ||
| ASSERT_FALSE(b_nodes.empty()); | ||
| EXPECT_FALSE(b_nodes.front().node.latlng().IsValid()); | ||
| } |
There was a problem hiding this comment.
Verifies kParseAreaWays.
Phase 1 runs up to kParseRelations: member way was discarded so we check it's not in ways.bin
Phase 2 runs kParseAreaWays: And now we see the way is there and also with the area bit
We also check that coordinates aren't set yet since kParseNodes runs later.
| TEST(area_routing, area_relations_collected) { | ||
| const std::string ascii_map = R"( | ||
| A----B | ||
| | | | ||
| D----C | ||
| )"; | ||
|
|
||
| // the member way has no routable tags, so lua discards it during ParseWays | ||
| const gurka::ways ways = { | ||
| {"ABCDA", {}}, | ||
| }; | ||
|
|
||
| // the relation carries the area tags | ||
| const gurka::relations relations = { | ||
| {{{ | ||
| {gurka::way_member, "ABCDA", "outer"}, | ||
| }}, | ||
| {{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}}, | ||
| }; | ||
|
|
||
| const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100); | ||
| const std::string workdir = "test/data/gurka_area_relations"; | ||
|
|
||
| // run up to ParseRelations so area_relations is filled and written to temp files | ||
| auto map = | ||
| gurka::buildtiles(layout, ways, {}, relations, workdir, | ||
| {{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}}, | ||
| mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kParseRelations); | ||
|
|
||
| // load the OSMData from the temp files and check the area relation members | ||
| const auto tile_dir = map.config.get<std::string>("mjolnir.tile_dir"); | ||
| mjolnir::OSMData osmdata{}; | ||
| osmdata.read_from_temp_files(tile_dir); | ||
|
|
||
| // the area relation collected its member way as an outer | ||
| ASSERT_FALSE(osmdata.area_relations.empty()); | ||
| const auto way_id = map.way_osm_ids.at("ABCDA"); | ||
| bool found_outer = false; | ||
| for (const auto& [rel_id, member] : osmdata.area_relations) { | ||
| if (member.way_id == way_id && member.is_outer) { | ||
| found_outer = true; | ||
| } | ||
| } | ||
| EXPECT_TRUE(found_outer); | ||
| } |
There was a problem hiding this comment.
Verifies that area_relations collects the members with the correct outer/inner role. This covers the coverage gap from the previous PR
| TEST(area_routing, area_polygons_assembled) { | ||
| const std::string ascii_map = R"( | ||
| A-----------------B | ||
| | | | ||
| | E----F I-J | | ||
| | | | | | | | ||
| | G----H K-L | | ||
| | | | ||
| D-----------------C | ||
| )"; | ||
|
|
||
| const gurka::ways ways = { | ||
| {"ABCDA", {}}, | ||
| {"EFHGE", {}}, | ||
| {"IJLKI", {}}, | ||
| }; | ||
| const gurka::relations relations = { | ||
| {{{ | ||
| {gurka::way_member, "ABCDA", "outer"}, | ||
| {gurka::way_member, "EFHGE", "inner"}, | ||
| {gurka::way_member, "IJLKI", "inner"}, | ||
| }}, | ||
| {{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}}, | ||
| }; | ||
|
|
||
| const auto layout = gurka::detail::map_to_coordinates(ascii_map, 10); | ||
|
|
||
| auto map = gurka::buildtiles(layout, ways, {}, relations, "test/data/gurka_area_polygons", | ||
| {{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}}, | ||
| mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kBuildAreas); | ||
|
|
||
| SUCCEED(); |
There was a problem hiding this comment.
Verifies the polygon assembly with holes, since kBuildAreas only lives inside of the function yet, this test is useless unless there are prints in the areabuilder.cc code that let us see data as the number of polygons, holes...
There was a problem hiding this comment.
for example, with the prints we can see that it works fine:
3 ways -> 3 raw polygon(s) -> 1 final polygon(s)
polygon 0 has 2 hole(s)
and for the first test that also runs up to this stage:
1 ways -> 1 raw polygon(s) -> 1 final polygon(s)
polygon 0 has 0 hole(s)
|
|
||
| constexpr double kMinAreaSquareMeters = 100.0; | ||
| constexpr double kDensifyToleranceMeters = 1.0; | ||
|
|
There was a problem hiding this comment.
kMinAreaSquareMeters : areas smaller than this skip the medial axis
kDensifyToleranceMeters : max spacing between points when densifying the boundary
| // way_id > relation_id, to know which relation each area way belongs to | ||
| std::unordered_map<uint64_t, uint64_t> way_to_relation; | ||
| for (const auto& entry : osmdata.area_relations) { | ||
| way_to_relation[entry.second.way_id] = entry.first; | ||
| } |
There was a problem hiding this comment.
maps each member way id to its relation id, so we know to which area each way belongs to
| // grab the way and its first node | ||
| size_t current_way_node_index = 0; | ||
| while (current_way_node_index < way_nodes.size()) { | ||
| auto way_node = *way_nodes[current_way_node_index]; | ||
| const auto way = *ways[way_node.way_index]; | ||
| const auto first_way_node_index = current_way_node_index; | ||
| const auto last_way_node_index = | ||
| first_way_node_index + way.node_count() - way_node.way_shape_node_index - 1; |
There was a problem hiding this comment.
walks the way nodes the same way as kConstructEdges does, way by way, using node_count to find the way's node range.
| // if it is an area, collect and store its shape | ||
| if (way.area()) { | ||
| std::vector<midgard::PointLL> shape; | ||
| for (auto node_idx = first_way_node_index; node_idx <= last_way_node_index; node_idx++) { | ||
| shape.push_back((*way_nodes[node_idx]).node.latlng()); | ||
| } | ||
| auto it = way_to_relation.find(way.way_id()); | ||
| uint64_t area_key = (it != way_to_relation.end()) ? it->second : way.way_id(); | ||
| area_ways[area_key].push_back(std::move(shape)); | ||
| } | ||
| current_way_node_index = last_way_node_index + 1; | ||
| } |
There was a problem hiding this comment.
For each area, collect its coordinates. If it belongs to a relation, we group by its relation id, if it's a simple way, group by its own id. This way both mapping area handled in the same way.
There was a problem hiding this comment.
while collecting the geometry, also record the nodes flagged as intersections
| // reference point for the local projection, first point of the first way | ||
| const midgard::PointLL center = shapes.front().front(); | ||
| midgard::DistanceApproximator<midgard::PointLL> aprox(center); | ||
| const double meter_per_lng = aprox.GetMetersPerLngDegree(); | ||
|
|
||
| // project each way to meters and create a GEOS line for each one | ||
| std::vector<GEOSGeometry*> lines; | ||
| for (const auto& shape : shapes) { | ||
| if (shape.size() < 2) { | ||
| continue; | ||
| } | ||
| // sequence of meter coords of the nodes of a way | ||
| GEOSCoordSequence* seq = GEOSCoordSeq_create(shape.size(), 2); | ||
| for (size_t i = 0; i < shape.size(); i++) { | ||
| double x = (shape[i].lng() - center.lng()) * meter_per_lng; | ||
| double y = (shape[i].lat() - center.lat()) * midgard::kMetersPerDegreeLat; | ||
| GEOSCoordSeq_setX(seq, i, x); | ||
| GEOSCoordSeq_setY(seq, i, y); |
There was a problem hiding this comment.
GEOS works in cartesian coordinates, so we project to local meters relative to the reference point, using the already in Valhalla function DistanceApproximator. We keep the center and scale to project back later
| // create a line with these points | ||
| GEOSGeometry* line = GEOSGeom_createLineString(seq); | ||
| if (line) { | ||
| lines.push_back(line); | ||
| } | ||
| } | ||
| if (lines.empty()) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Build one line string per way from the projected coordinates
| continue; | ||
| } | ||
| // with the lines we created, returns a collection of polygons | ||
| GEOSGeometry* polygons = GEOSPolygonize(lines.data(), lines.size()); |
There was a problem hiding this comment.
GEOSpolygonize assemble the lines into polygons, finds the closed rings, handling the case where several ways together form one ring. It returns th epolygon already with its hole, plus the inner as a separete leftover polygon
| std::vector<GEOSGeometry*> final_polygons; | ||
| for (int i = 0; i < num_polygons; ++i) { | ||
| const GEOSGeometry* poly_i = GEOSGetGeometryN(polygons, i); | ||
| GEOSGeometry* point = GEOSPointOnSurface(poly_i); | ||
| bool fills_a_hole = false; | ||
| for (int j = 0; j < num_polygons; ++j) { | ||
| if (i == j || GEOSGetNumInteriorRings(GEOSGetGeometryN(polygons, j)) == 0) { | ||
| continue; | ||
| } | ||
| const GEOSGeometry* exterior = GEOSGetExteriorRing(GEOSGetGeometryN(polygons, j)); | ||
| GEOSGeometry* shell = GEOSGeom_createPolygon(GEOSGeom_clone(exterior), nullptr, 0); | ||
| char inside_shell = GEOSContains(shell, point); | ||
| char inside_poly = GEOSContains(GEOSGetGeometryN(polygons, j), point); | ||
| GEOSGeom_destroy(shell); | ||
| if (inside_shell == 1 && inside_poly == 0) { | ||
| fills_a_hole = true; | ||
| break; | ||
| } | ||
| } | ||
| GEOSGeom_destroy(point); | ||
| if (!fills_a_hole) { | ||
| final_polygons.push_back(GEOSGeom_clone(poly_i)); | ||
| } | ||
| } |
There was a problem hiding this comment.
Since it returns the inners as a separate polygon, we detect those (a polygon whose interior point falls inside another polygon's hole) and drop them, keeping the outer with its holes
| for (GEOSGeometry* poly : final_polygons) { | ||
| double area = 0; | ||
| GEOSArea(poly, &area); | ||
| // skip areas that are too small to be worth routing through | ||
| if (area < kMinAreaSquareMeters) { | ||
| continue; | ||
| } | ||
| GenerateMedialAxis(poly, center, meter_per_lng); | ||
| } |
There was a problem hiding this comment.
skip areas smaller than the threshold, otherwise generate medial axis
| // densify the polygon boundary so the voronoi diagram has enough points | ||
| GEOSGeometry* densified = GEOSDensify(polygon, kDensifyToleranceMeters); | ||
| if (!densified) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
densify the polygon boundary so the Voronoi diagram has enough points to produce a smooth skeleton
| // compute the voronoi diagram using the densified polygon vertices | ||
| GEOSGeometry* voronoi = GEOSVoronoiDiagram(densified, nullptr, 0.0, GEOS_VORONOI_ONLY_EDGES); | ||
| if (!voronoi) { | ||
| GEOSGeom_destroy(densified); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Compute the voronoi diagram of the boundary points, with the GEOS_VORONOI_ONLY_EDGES flag, it returns the edges as line strings.
| // keep only the voronoi edges that fall completely inside the polygon | ||
| std::vector<GEOSGeometry*> medial_edges; | ||
| for (int i = 0; i < num_voronoi_edges; ++i) { | ||
| const GEOSGeometry* edge = GEOSGetGeometryN(voronoi, i); | ||
| if (GEOSContains(polygon, edge) == 1) { | ||
| medial_edges.push_back(GEOSGeom_clone(edge)); | ||
| } | ||
| } |
There was a problem hiding this comment.
GEOSContains keeps only the Voronoi edges completely inside the polygon, this results into the raw medial axis.
| // clean up the kept edges | ||
| for (GEOSGeometry* edge : medial_edges) { | ||
| GEOSGeom_destroy(edge); | ||
| } | ||
| GEOSGeom_destroy(voronoi); | ||
| GEOSGeom_destroy(densified); |
There was a problem hiding this comment.
Clean up all the GEOS geomtries. The kept edges, are clones, so they're destoyed separately from the Voronoi collection
…to pedestrian-area-ways-clean
| auto vertex_key = [](double x, double y) { | ||
| return std::make_pair(std::llround(x * 1000.0), std::llround(y * 1000.0)); | ||
| }; |
There was a problem hiding this comment.
Vertices coming out of the Voronoi sharing an endpoint can differ in the last bits, rounding make those compare exactly, so the graph doesn't end up disconnected
| std::map<std::pair<int64_t, int64_t>, int> vertex_ids; | ||
| std::vector<midgard::Point2d> vertex_coords; |
There was a problem hiding this comment.
vertex_ids answers if I have seen this point before, and the vector vector_coords answers where the vertex N(id) is.
We need the map to unify duplicate endpoints, and the vector to recover the actual geometry later when stitching the chains
| bool visible_within(const GEOSGeometry* poly, const midgard::Point2d& a, const midgard::Point2d& b) { | ||
| namespace { | ||
| bool visible_within(const GEOSPreparedGeometry* prepared, | ||
| const midgard::Point2d& a, | ||
| const midgard::Point2d& b) { | ||
| GEOSCoordSequence* seq = GEOSCoordSeq_create(2, 2); | ||
| GEOSCoordSeq_setXY(seq, 0, a.x(), a.y()); | ||
| GEOSCoordSeq_setXY(seq, 1, b.x(), b.y()); | ||
| GEOSGeometry* segment = GEOSGeom_createLineString(seq); | ||
| const bool visible = segment && GEOSContains(poly, segment) == 1; | ||
| const bool visible = segment && GEOSPreparedCovers(prepared, segment) == 1; |
There was a problem hiding this comment.
Switched this to take a prepared geometry and use GEOSPreparedCovers instead of GEOSContains. the main reason : the polygon is prepared once per polygon and reused across all the visibility checks, which is a great saving since it's called many times against the same geometry
|
|
||
| // way_id > relation_id, to know which relation each area way belongs to | ||
| std::unordered_map<uint64_t, uint64_t> way_to_relation; | ||
| way_to_relation.reserve(osmdata.area_relations.size()); |
There was a problem hiding this comment.
reserve since we know the size from area_relations
| @@ -104,26 +109,46 @@ void AreaBuilder::BuildAreas(const boost::property_tree::ptree& /*pt*/, | |||
| shape.push_back(node.latlng()); | |||
| if (node.intersection()) { | |||
| area_shared_nodes[area_key].push_back({node.osmid_, node.latlng()}); | |||
| area_perimeter_nodes.insert(node.osmid_); | |||
| } | |||
| } | |||
| area_ways[area_key].push_back(std::move(shape)); | |||
| } | |||
| current_way_node_index = last_way_node_index + 1; | |||
| } | |||
|
|
|||
| } else if (way.pedestrian_forward() || way.pedestrian_backward()) { | |||
| pedestrian_way_spans[way.way_id()] = {first_way_node_index, last_way_node_index}; | |||
| // second pass collecting pedestrian ways, filtered against the perimeter set | |||
| current_way_node_index = 0; | |||
| while (current_way_node_index < way_nodes.size()) { | |||
| auto way_node = *way_nodes[current_way_node_index]; | |||
| const auto way = *ways[way_node.way_index]; | |||
| const auto first_way_node_index = current_way_node_index; | |||
| const auto last_way_node_index = | |||
| first_way_node_index + way.node_count() - way_node.way_shape_node_index - 1; | |||
|
|
|||
| if (!way.area() && (way.pedestrian_forward() || way.pedestrian_backward())) { | |||
| bool touches_area = false; | |||
| for (auto node_idx = first_way_node_index; node_idx <= last_way_node_index; node_idx++) { | |||
| const auto& node = (*way_nodes[node_idx]).node; | |||
| if (node.intersection()) { | |||
| if (node.intersection() && area_perimeter_nodes.count(node.osmid_)) { | |||
| touches_area = true; | |||
| pedestrian_node_ways[node.osmid_].push_back( | |||
| {way.way_id(), static_cast<uint32_t>(node_idx - first_way_node_index)}); | |||
| } | |||
| } | |||
| // only ways that touch an area can be crossing candidates, so we only need | |||
| // to remember where their nodes live in the file for those | |||
| if (touches_area) { | |||
| pedestrian_way_spans[way.way_id()] = {first_way_node_index, last_way_node_index}; | |||
| } | |||
There was a problem hiding this comment.
Split the single sweep into two. The first pass handles areas an records every perimeter node into area_perimeter_nodes. The second pass handles pedestrians ways but only keeps a entry when the node is in that set, so the map stays proportional to the nodes that actually touch areas instead of every pedestrian node on the continent.
|
|
||
| constexpr double kMinAreaSquareMeters = 100.0; | ||
| constexpr double kDensifyToleranceMeters = 1.0; | ||
| constexpr double kDensifyToleranceMeters = 4.0; |
There was a problem hiding this comment.
raising the meters, makes it run much faster without any visual difference
chrstnbwnkl
left a comment
There was a problem hiding this comment.
I haven't gotten to the end yet, give me a little more time to go through the remainder @pacoalbacetec. So far mostly comments on adding comments, plus some nitpicks. Anything labeled as a nit is optional of course :)
| // Note, we also allow dataset_id to be set by config, which happens at tile build | ||
| if (osmdata.max_changeset_id_ == 0) { | ||
| osmdata.max_changeset_id_ = max_osm_id; | ||
| osmdata.max_node_id = max_osm_id; |
There was a problem hiding this comment.
nit: move this outside of this if block, otherwise the pedestrian area stuff won't work if you bring your own dataset id.
| namespace valhalla { | ||
| namespace mjolnir { | ||
| // can two points be joined by a straight segment that stays inside the polygon? | ||
| namespace { |
There was a problem hiding this comment.
nit: we usually put the anonymous namespace at the very top instead of nesting it into another namespace
| * @param polygon the area polygon, in local meter coordinates | ||
| * @return the skeleton of the medial axis as a list of chains | ||
| */ | ||
| static std::vector<std::vector<midgard::Point2d>> GenerateMedialAxis(const GEOSGeometry* polygon); |
There was a problem hiding this comment.
Nit: can you make this a free standing function in the anonymous namespace? Then there's no need to forward declare anything
| std::unordered_map<uint64_t, WaySpan> pedestrian_way_spans; | ||
|
|
||
| // first pass for areas, collect each area's shape, and remember which nodes lie on some perimeter. | ||
| std::unordered_set<uint64_t> area_perimeter_nodes; |
There was a problem hiding this comment.
those are a lot of sets and maps, can you add a short comment above all their declarations so it's clear what they're for? Also, I assume at this point the 64 bit keys are either way IDs or relation IDs, maybe also worth a comment.
| auto it = way_to_relation.find(way.way_id()); | ||
| uint64_t area_key = (it != way_to_relation.end()) ? it->second : way.way_id(); | ||
| if (way.name_index() != 0) { | ||
| area_name_indices[area_key] = way.name_index(); |
There was a problem hiding this comment.
for areas that are ways, this is fine, but what about relations? Then the area_key is the relation ID, but you're still getting the name from the way, where it's actually on the relation.
| } | ||
|
|
||
| initGEOS(nullptr, nullptr); | ||
|
|
There was a problem hiding this comment.
now that you've filled all the mappings you need, it'd be nice to have a little comment what you're about to do with all this information next.
|
|
||
| uint64_t next_synthetic_osm_id = osmdata.max_way_id + 1; | ||
| uint64_t next_synthetic_node_id = osmdata.max_node_id + 1; | ||
| for (const auto& [relation_id, shapes] : area_ways) { |
There was a problem hiding this comment.
relation_id is a bit of a misnomer at this point, because it might be a relation or a way ID
| if (shared_it != area_shared_nodes.end()) { | ||
| for (const auto& [node_id, ll] : shared_it->second) { | ||
| if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) { | ||
| entrances.push_back({node_id, ll}); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
nit: can this be refactored to look like this so it's one nesting level less?
| if (shared_it != area_shared_nodes.end()) { | |
| for (const auto& [node_id, ll] : shared_it->second) { | |
| if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) { | |
| entrances.push_back({node_id, ll}); | |
| } | |
| } | |
| } | |
| if (shared_it == area_shared_nodes.end()) { | |
| continue; | |
| } | |
| for (const auto& [node_id, ll] : shared_it->second) { | |
| if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) { | |
| entrances.push_back({node_id, ll}); | |
| } | |
| } |
| } | ||
| // reference point for the local projection, first point of the first way | ||
| const midgard::PointLL center = shapes.front().front(); | ||
| midgard::DistanceApproximator<midgard::PointLL> aprox(center); |
There was a problem hiding this comment.
nit: could use midgard::AzimuthalEquidistant here.
| const double meter_per_lng = aprox.GetMetersPerLngDegree(); | ||
|
|
||
| // project the entrances to meters and build a GEOS point for each one | ||
| std::vector<std::pair<uint64_t, midgard::Point2d>> entrances_m; |
There was a problem hiding this comment.
this function is already ~300 lines long, maybe this projection stuff could be turned into an anonymous function?
chrstnbwnkl
left a comment
There was a problem hiding this comment.
Thanks for your patience @pacoalbacetec while I'm trying to review this 😄 The overall logic is not that simple, but we've talked about it plenty of times before. For future reviewers, or who ever is interested in the implementation, this is the rough outline:
- preparation: construct the areas, find shared nodes, construct all the other mappings
- go through each (multi-)polygon and
a. filter the irrelevant ones (by area, whether they're reachable, or already crossed by existing ways),
b. find and group nearby entrances
c. construct the medial axis
d. connect entrances to it
I only have some small change requests, in order of decreasing relevance:
- some more comments and todos
- use our own
DistanceSquaredmember functions where possible - look into using
GEOSPolygonize_validinstead of rolling your own removal of hole polygons (not a must if it turns out to be too much work)
Other than that I think this is good enough for a public beta! As we talked about in our weekly meetings, we agreed on a number of simplifications that we might want to revisit in the future to cover some edge cases, but this should cover ~80-90% of pedestrian areas in a way that significantly improves routing across these! Really nice work @pacoalbacetec 🥳
| for (int i = 0; i < num_polygons; ++i) { | ||
| const GEOSGeometry* poly_i = GEOSGetGeometryN(polygons, i); | ||
| GEOSGeometry* point = GEOSPointOnSurface(poly_i); | ||
| bool fills_a_hole = false; |
There was a problem hiding this comment.
I think we can do something simpler here: instead of calling GEOSPolygonize and then untangling holes and non-holes, we should be able to simply call GEOSPolygonize_valid (see docs). This should give you a single polygon/multipolygon instead of a std::vector of polygons, but it seems to be the correct way that handles nested holes better and avoids this O(n^2) loop. What do you think?
| for (size_t i = 0; i < entrance_points.size(); ++i) { | ||
| double distance = 0; | ||
| GEOSDistance(poly, entrance_points[i], &distance); | ||
| if (distance < kEntranceToleranceMeters) { |
There was a problem hiding this comment.
Probably a good idea to leave a todo about the exact value of this tolerance. I feel like 0.5 is a bit too high, and we might revisit this in the future. Ideally an entrance should have zero distance to the polygon it belongs to, right? So I'm tempted to change the tolerance to something like std::numerical_limits<double>::epsilon() 😄
| int num_groups = 0; | ||
| for (size_t i = 0; i < poly_entrances.size(); ++i) { | ||
| for (size_t j = 0; j < i && group_of[i] == -1; ++j) { | ||
| const double dx = poly_entrances[i].second.x() - poly_entrances[j].second.x(); |
There was a problem hiding this comment.
can just call Point2d::DistanceSquared() here instead
| group_of[i] = num_groups++; | ||
| } | ||
| } | ||
| if (num_groups < static_cast<int>(poly_entrances.size())) { |
There was a problem hiding this comment.
Can you leave some comments here? The code reads like you're looking for the entrance with the least relative distance to all the other entrances in the group, but it took me a little to get to that conclusion
| for (size_t i = 0; i < medial_axis[c].size(); ++i) { | ||
| const auto& p = medial_axis[c][i]; | ||
| const double dx = p.x() - entrance.x(); | ||
| const double dy = p.y() - entrance.y(); |
There was a problem hiding this comment.
again, use the existing DistanceSquared member functions
| const auto& seg = segments[current_segment]; | ||
| const int next_vertex = (seg.first == current_vertex) ? seg.second : seg.first; | ||
| // stop at a fork, continue at degree 2 vertex | ||
| if (incident[next_vertex].size() != 2) { |
There was a problem hiding this comment.
nit: can you reuse the is_important lambda up here as well?
| int current_vertex = start_vertex; | ||
| int current_segment = start_segment; | ||
| while (true) { | ||
| used[current_segment] = true; |
There was a problem hiding this comment.
I think it's fine to leave the chain walking code duplicated, but it should be possible to reuse it for the removal loop above, right? maybe just leave a little todo
| if (removed[s] || used[s]) { | ||
| continue; | ||
| } | ||
| chains.push_back(walk_chain(segments[s].first, static_cast<int>(s))); |
There was a problem hiding this comment.
have you seen loops like this in the wild? just wondering, I couldn't come up with an example in my head 😄
| // clean up the kept edges | ||
| for (GEOSGeometry* edge : medial_edges) { | ||
| GEOSGeom_destroy(edge); | ||
| } | ||
| GEOSGeom_destroy(voronoi); | ||
| GEOSGeom_destroy(densified); |
There was a problem hiding this comment.
it's painful to read through all these manual C object desstruction calls. Is it possible to use some sort of RAII as it is done in Geometry in valhalla/mjolnir/admin.h ?
There was a problem hiding this comment.
alternatively, one can use a built-in C++ construct for that - std::unique_ptr
auto raw_ptr = GEOSVoronoiDiagram(densified, nullptr, 0.0, GEOS_VORONOI_ONLY_EDGES);
auto smart_ptr = std::unique_ptr(raw_ptr, GEOSGeom_destroy);or somewhat like that.
| OSMWay w{static_cast<uint64_t>(osm_way.id())}; | ||
| w.set_node_count(nodes.size()); | ||
| w.set_area(true); | ||
| ways.push_back(w); |
There was a problem hiding this comment.
Basically this logic adds new edges into the graph that surround such pedestrian areas. We are typically trying to keep graph reasonably small.
Have you considered to keep areas in a separate file? I've tried to follow the code path but I still got no idea if having such "perimeter edges" is a desired outcome or a side-effect.
There was a problem hiding this comment.
For some of these areas it makes sense to not create synthetic ways inside them and instead just route on the perimeter (e.g. when the area is very small), so we keep them and later decide whether or not to actually use them as routable ways. If we created synthetic ways inside an area, we'll discard the perimeter for now.
We decided to possibly revisit that idea in the future, because it's easy to think of examples where having the perimeter as well as synthesized edges in the area might be necessary.
There was a problem hiding this comment.
We don't set any OSMWay properties here aside area. Shouldn't we at least add something like "pedestrian access" to it?
There was a problem hiding this comment.
That's left to the kBuildAreas stage, after it's been decided to keep the perimeter. I suppose you could do it here as well, but it's more concise to set these where we also set the access flags etc. for the synthetic ways.
There was a problem hiding this comment.
Makes perfect sense. Still, I would appreciate a comment about this here as it introduces a new state for that object - "exists but not filled"
There was a problem hiding this comment.
I was thinking about this item and what I really don't like here is that after this PR we will have some OSMWays in "fully ok" state and some others OSMWays in "not fully processed" state led in the same file/collection.
Can we make it somehow less surprising?
There was a problem hiding this comment.
I understand that
- separating these ways into different files is cleaner and more easy to comprehend
- using RAII is the cleaner way for interacting with the GEOS C API
but the GSoC project is about to end, so I would really try to get a first version merged.
The challenge with GSoC is to onboard somebody onto this codebase, show them how it is to work on such a large and complex codebase, while also enabling them to work on something innovative, all at the same time, all in this short time window. So we have to cut some corners to get this feature done, and these are precisely the things I deem "nice to have".
There was a problem hiding this comment.
It's true that I did give @pacoalbacetec some things to improve in my last review, but the end (of the project) is nigh now 😄
There was a problem hiding this comment.
@chrstnbwnkl don't get me wrong, I'm not pressing "request changes" regarding these items. Valhalla codebase has so many places to improve, so adding these two will barely make any difference. We can address these items later.
There was a problem hiding this comment.
No worries, I just wanted to make clear that I'm not opposed to your ideas, just maybe we can wait a week or two to make them happen (or forever append them to the infinite list of things we could improve in the library 😄)
chrstnbwnkl
left a comment
There was a problem hiding this comment.
This is good to merge for me! Nice to see the change to how geos polygonization is used is such a small change 😄
Continuation of #6127
What is this PR about
Enables pedestrian routing through pedestrian areas (
highway=pedestrian+area=yes). For each area it generates a traversal skeleton along the medial axis and connects the area's entrances to it, so a pedestrian can cross a square directly.Implementation
ParseAreaWays: areas tagged only on the relation have member ways with no routable tags, so lua drops them during regular way parsing. This pass recovers the ways referenced by area relations and marks them so their geometry survives to the builder.BuildAreas: assembles each area's polygon/s from its member ways (including inner members), computes the medial axis via a Voronoi diagram of the densified boundary, prunes branches, connects each entrance to the nearest skeleton vertex it can reach without leaving the polygon, and materialises the result as synthetic footways. ConstructEdges then turns those into edges like any other way.Synthetic ids: generated ways and nodes get ids above the highest real way and node ids, so they never collide with real OSM ids, and are kept out of the final tiles.Decisions we made
Performance
BuildAreas on Germany started at ~114s. With GEOSPrepare on the Voronoi filter
and the two-pass node collection it dropped to ~65s, and raising the densify
tolerance takes it further:
2m -> ~33s
4m -> ~19s
Roughly 6 minutes projected for a full Europe build.
Notes
This is a fully functional version that we've tested on real data (Germany and
Europe builds) with really good results. We've marked a number of TODOs in the code for things that work well but could be improved further down the line.
Here's a before/after from Plaza de Santo Domingo in Murcia, Spain, without the feature the route goes around the square, with it it crosses straight through:
Before:

After:

A note on stability
This is a functional first version. It works well and noticeably improves routing
across pedestrian areas, though there are still things that could be refined and
improved further down the line (marked as TODOs in the code). None of that affects
existing behaviour: the whole feature sits behind the
mjolnir.pedestrian_areasconfig option and is off by default, so unless it's explicitly enabled Valhalla
builds and routes exactly as it does today.