From 597ac9485c0924338db465e7c7f9c536bd4dffa0 Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Tue, 27 Oct 2026 16:11:05 +0200 Subject: [PATCH] routing: snap CH ends onto roads, keep a parked car's heading A point between the two carriageways of a dual carriageway (Khreshchatyk, the default origin without a fix) started on whichever side had a CH junction nearby, and a route could begin the wrong way round: 9.1 km where A* found 4.7 km. - CH: start and end are projected onto the nearest road segments, as the core's routers do (findRouteSegment), then followed in the road's travel direction to the first sidecar junction; every such junction seeds the one search with the snap distance and the driving time to it (plus the reverse-heading penalty). The approach and exit stretches are part of the route; start and end on one road use the road itself. The nearest-junction snap stays as the fallback. - A junction splits into one node per arriving and leaving edge, all at its coordinates, so the old "4 nearest nodes" were often one junction. - The heading a route starts with is kept while the car stands where it stopped, also across a restart: a parked record (heading and position, /datastore/navicore-backend/parked.txt) is saved once per stop at a new spot and restored at start-up, also as the map's first position. Bench, 18 pairs against plain A* (2 disputed, 8 on roads, 8 jittered 15-40 m): worst CH/A* time x2.13 -> x1.29, median x0.996 -> x0.980; the disputed pair 9.1 km -> 1.5 km. CH route time median 458 -> 606 ms. Co-Authored-By: Claude Opus 5.5 --- backends/osmand/ch/ch_sidecar.h | 47 +++- backends/osmand/ch_planner.cpp | 332 +++++++++++++++++++++++--- backends/osmand/ch_planner.h | 5 +- backends/osmand/config.cpp | 1 + backends/osmand/config.h | 2 + backends/osmand/navigation_worker.cpp | 10 +- backends/osmand/osmand_engine.cpp | 59 ++++- backends/osmand/reroute_state.h | 81 ++++++- tests/ch_test.cpp | 11 + tests/reroute_state_test.cpp | 32 +++ 10 files changed, 526 insertions(+), 54 deletions(-) diff --git a/backends/osmand/ch/ch_sidecar.h b/backends/osmand/ch/ch_sidecar.h index 0b3afac..cba4453 100644 --- a/backends/osmand/ch/ch_sidecar.h +++ b/backends/osmand/ch/ch_sidecar.h @@ -248,6 +248,24 @@ class Sidecar { out.push_back({b.second.node, std::sqrt((double)b.first) * scale, b.second.x, b.second.y}); } + // The nodes at a road point (a junction splits into one node per arriving and + // per leaving edge, all at its coordinates); empty when the point is no node. + void nodes_at(int x31, int y31, std::vector& out) + { + out.clear(); + const int64_t gx = ((int64_t)x31 - header_.grid_min_x) >> header_.grid_shift; + const int64_t gy = ((int64_t)y31 - header_.grid_min_y) >> header_.grid_shift; + if (gx < 0 || gy < 0 || gx >= (int64_t)header_.grid_w || gy >= (int64_t)header_.grid_h) return; + const u32 c = (u32)(gy * header_.grid_w + gx); + u32 bounds[2]; + if (!file_->read(header_.off_grid_first + (uint64_t)c * 4, bounds, sizeof bounds) || bounds[1] <= bounds[0]) return; + entries_.resize(bounds[1] - bounds[0]); + if (!file_->read(header_.off_grid + (uint64_t)bounds[0] * sizeof(SidecarGridEntry), entries_.data(), + entries_.size() * sizeof(SidecarGridEntry))) return; + for (const SidecarGridEntry& e : entries_) + if (e.x == x31 && e.y == y31) out.push_back(e.node); + } + private: explicit Sidecar(std::unique_ptr file) : file_(std::move(file)) {} @@ -341,16 +359,33 @@ class Router { sources_.push_back({s.node, (u32)std::lround(120.0 * s.metres + reverse_penalty(sx, sy, s, start_heading_degrees))}); for (const auto& t : to_) targets_.push_back({t.node, (u32)std::lround(120.0 * t.metres)}); - u32 meet = 0; - const u32 total = query_.run(sources_.data(), sources_.size(), targets_.data(), targets_.size(), - meet, cancelled); - if (total == INF) return cancelled && cancelled() ? Status::Cancelled : Status::NoRoute; - const u32 from = query_.source_of(meet), to = query_.target_of(meet); + u32 from = 0, to = 0, total = 0; + const Status status = route_seeded(sources_, targets_, runs, total, cancelled, from, to); + if (status != Status::Ok) return status; u32 offsets = 0; for (const auto& s : sources_) if (s.node == from) offsets += s.cost; for (const auto& t : targets_) if (t.node == to) offsets += t.cost; - if (!query_.path_edges(from, to, meet, edges_)) return Status::Inconsistent; cost = total - std::min(total, offsets); + return status; + } + + // The cheapest route from any source seed to any target seed, seeds' costs + // included (cost: the whole, in ms); from/to name the seeds it uses. Runs are + // empty when both are one node. + Status route_seeded(const std::vector::Seed>& sources, + const std::vector::Seed>& targets, + std::vector& runs, u32& cost, const std::function& cancelled, + u32& from, u32& to) + { + runs.clear(); + u32 meet = 0; + const u32 total = query_.run(sources.data(), sources.size(), targets.data(), targets.size(), + meet, cancelled); + if (total == INF) return cancelled && cancelled() ? Status::Cancelled : Status::NoRoute; + from = query_.source_of(meet); + to = query_.target_of(meet); + if (!query_.path_edges(from, to, meet, edges_)) return Status::Inconsistent; + cost = total; return merge(runs) ? Status::Ok : Status::Inconsistent; } diff --git a/backends/osmand/ch_planner.cpp b/backends/osmand/ch_planner.cpp index 5402ff1..d8e09b0 100644 --- a/backends/osmand/ch_planner.cpp +++ b/backends/osmand/ch_planner.cpp @@ -2,12 +2,16 @@ #include "ch/ch_sidecar.h" +#include "binaryRoutePlanner.h" +#include "generalRouter.h" #include "routeResultPreparation.h" +#include "routeSegment.h" #include #include #include +#include #include #include #include @@ -28,6 +32,199 @@ std::string base_name(const std::string& path) return slash == std::string::npos ? path : path.substr(slash + 1); } +// Start and end are snapped onto roads as the core's own routers do (the nearest +// segment of each nearby road), then follow the road in its travel direction to +// the first junction the sidecar knows. Snapping straight to the nearest junctions +// instead put a point between the two carriageways of a dual carriageway onto +// whichever side had a junction nearby, and a route started the wrong way round +// (2026-10-27, Khreshchatyk). +constexpr double kSnapMsPerMetre = 120.0; // the distance to the road, as the node snap +constexpr double kReversePenaltyMs = 60000.0; // starting against the car's heading +constexpr double kMaxSnapMetres = 1000.0; +constexpr double kMaxApproachMetres = 5000.0; // along a road to its first junction +constexpr std::size_t kSnapRoads = 8; // nearest roads tried at each end + +double metres_between(int x1, int y1, int x2, int y2) +{ + return std::hypot(static_cast(x2) - x1, static_cast(y2) - y1) * + onc_ch::metres_per_unit((static_cast(y1) + y2) / 2.0); +} + +// Degrees clockwise from north (31-bit y grows southwards). +double bearing_between(int x1, int y1, int x2, int y2) +{ + const double degrees = std::atan2(static_cast(x2) - x1, static_cast(y1) - y2) * + 180.0 / M_PI; + return degrees < 0.0 ? degrees + 360.0 : degrees; +} + +// The point projected onto the nearest segment (lo, lo + 1) of one road. +struct RoadSnap { + SHARED_PTR road; + int lo = 0, hi = 0; + int x = 0, y = 0; + double metres = 0; + int oneway = 0; // the router's: 1 forward (rising point index) only, -1 backward only +}; + +std::vector snap_roads(RoutingContext* context, int x, int y) +{ + std::vector snaps; + const auto nearest = findRouteSegment(x, y, context); + if (!nearest) return snaps; + std::vector> points{nearest}; + points.insert(points.end(), nearest->others.begin(), nearest->others.end()); + const auto& router = context->config->router; + for (const auto& point : points) { + if (snaps.size() >= kSnapRoads) break; + if (!point || !point->road || !router->acceptLine(point->road)) continue; + RoadSnap snap; + snap.road = point->road; + snap.lo = std::min(point->getSegmentStart(), point->getSegmentEnd()); + snap.hi = std::max(point->getSegmentStart(), point->getSegmentEnd()); + snap.x = point->preciseX; + snap.y = point->preciseY; + snap.metres = metres_between(x, y, snap.x, snap.y); + snap.oneway = router->isOneWay(point->road); + if (snap.hi == snap.lo || snap.hi >= static_cast(snap.road->pointsX.size()) || + snap.metres > kMaxSnapMetres) + continue; + snaps.push_back(snap); + } + return snaps; +} + +bool may_travel(const RoadSnap& snap, bool forward) +{ + return forward ? snap.oneway >= 0 : snap.oneway <= 0; +} + +double speed_of(RoutingContext* context, const RoadSnap& snap, bool forward) +{ + return std::max(1.0, context->config->router->defineRoutingSpeed(snap.road, forward)); +} + +// One way onto (start) or off (end) the hierarchy along a road: the stretch between +// the projected point and a junction, in travel order, and what driving it costs. +struct Approach { + SHARED_PTR road; + int start = 0, end = 0; // point indexes in travel order + double cost_ms = 0; + std::vector nodes; +}; + +// From the projection along rising (up) or falling point indexes to the first +// point that is a junction of the sidecar. +bool walk_to_node(onc_ch::Sidecar& sidecar, const RoadSnap& snap, bool up, int& index, + double& metres, std::vector& nodes) +{ + const auto& road = snap.road; + const int count = static_cast(road->pointsX.size()); + int x = snap.x, y = snap.y; + metres = 0; + for (index = up ? snap.hi : snap.lo; index >= 0 && index < count; index += up ? 1 : -1) { + const int px = static_cast(road->pointsX[index]); + const int py = static_cast(road->pointsY[index]); + metres += metres_between(x, y, px, py); + x = px; + y = py; + if (metres > kMaxApproachMetres) return false; + sidecar.nodes_at(px, py, nodes); + if (!nodes.empty()) return true; + } + return false; +} + +// start: drive from the point to a junction; otherwise arrive at the point from one. +std::vector approaches(onc_ch::Sidecar& sidecar, RoutingContext* context, + const std::vector& snaps, bool start, + double heading_degrees) +{ + std::vector output; + for (const RoadSnap& snap : snaps) { + for (const bool forward : {true, false}) { + if (!may_travel(snap, forward)) continue; + // A start drives on in the travel direction; an end is reached from behind. + const bool up = start ? forward : !forward; + Approach approach; + int index = 0; + double metres = 0; + if (!walk_to_node(sidecar, snap, up, index, metres, approach.nodes)) continue; + approach.road = snap.road; + if (start) { + approach.start = forward ? snap.lo : snap.hi; + approach.end = index; + } else { + approach.start = index; + approach.end = forward ? snap.hi : snap.lo; + } + approach.cost_ms = kSnapMsPerMetre * snap.metres + + 1000.0 * metres / speed_of(context, snap, forward); + if (start && heading_degrees >= 0.0) { + const auto& road = snap.road; + const int from = forward ? snap.lo : snap.hi, to = forward ? snap.hi : snap.lo; + const double travel = bearing_between(road->pointsX[from], road->pointsY[from], + road->pointsX[to], road->pointsY[to]); + if (std::fabs(std::remainder(travel - heading_degrees, 360.0)) > 120.0) + approach.cost_ms += kReversePenaltyMs; + } + output.push_back(std::move(approach)); + } + } + return output; +} + +// Start and end on one road, the end ahead in an allowed direction: the road +// itself, without a junction in between. False when there is no such run. +bool same_road_run(RoutingContext* context, const RoadSnap& from, const RoadSnap& to, + double heading_degrees, Approach& run) +{ + if (from.road->getId() != to.road->getId()) return false; + const auto& road = from.road; + bool found = false; + for (const bool forward : {true, false}) { + if (!may_travel(from, forward)) continue; + const int a = forward ? from.lo : from.hi; // the segment end behind the start + const int b = forward ? to.lo : to.hi; // the one behind the end + const bool same_segment = from.lo == to.lo; + const bool ahead = same_segment + ? metres_between(road->pointsX[a], road->pointsY[a], to.x, to.y) > + metres_between(road->pointsX[a], road->pointsY[a], from.x, from.y) + : (forward ? to.lo > from.lo : to.lo < from.lo); + if (!ahead) continue; + double metres = 0; + if (same_segment) { + metres = metres_between(from.x, from.y, to.x, to.y); + } else { + int x = from.x, y = from.y; + for (int i = forward ? from.hi : from.lo; ; i += forward ? 1 : -1) { + metres += metres_between(x, y, road->pointsX[i], road->pointsY[i]); + x = road->pointsX[i]; + y = road->pointsY[i]; + if (i == b) break; + } + metres += metres_between(x, y, to.x, to.y); + } + double cost = kSnapMsPerMetre * (from.metres + to.metres) + + 1000.0 * metres / speed_of(context, from, forward); + if (heading_degrees >= 0.0) { + const int c = forward ? from.hi : from.lo; + const double travel = bearing_between(road->pointsX[a], road->pointsY[a], + road->pointsX[c], road->pointsY[c]); + if (std::fabs(std::remainder(travel - heading_degrees, 360.0)) > 120.0) + cost += kReversePenaltyMs; + } + if (!found || cost < run.cost_ms) { + run.road = road; + run.start = a; + run.end = forward ? to.hi : to.lo; + run.cost_ms = cost; + found = true; + } + } + return found; +} + } // namespace class ChPlanner::Impl { @@ -91,42 +288,117 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR timing_ = Timing(); why.clear(); auto step = Clock::now(); + const auto progress = context->progress; + const auto cancelled = [&progress] { return progress && progress->isCancelled(); }; + onc_ch::Sidecar& sidecar = *impl_->sidecar; + + // Onto the roads, then along them to the hierarchy. + const auto from_roads = snap_roads(context.get(), start_x, start_y); + const auto to_roads = snap_roads(context.get(), end_x, end_y); + const auto starts = approaches(sidecar, context.get(), from_roads, true, start_heading_degrees); + const auto ends = approaches(sidecar, context.get(), to_roads, false, -1.0); + Approach direct; + bool has_direct = false; + for (const RoadSnap& from : from_roads) + for (const RoadSnap& to : to_roads) { + Approach run; + if (same_road_run(context.get(), from, to, start_heading_degrees, run) && + (!has_direct || run.cost_ms < direct.cost_ms)) { + direct = run; + has_direct = true; + } + } + timing_.snap_ms = ms_since(step); + std::vector runs; onc_ch::u32 cost = 0; - const auto progress = context->progress; - const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost, - start_heading_degrees, - [&progress] { return progress && progress->isCancelled(); }); - timing_.search_ms = ms_since(step); - timing_.settled = impl_->router->settled(); - timing_.base_edges = impl_->router->edges().size(); - timing_.road_runs = runs.size(); - if (status == onc_ch::Router::Status::NoRoute) { why = "no_route_in_sidecar"; return {}; } - if (status == onc_ch::Router::Status::Inconsistent) { why = "sidecar_inconsistent"; return {}; } - if (status == onc_ch::Router::Status::Cancelled) { why = "cancelled"; return {}; } - if (runs.empty()) { why = "too_short_for_sidecar"; return {}; } - - // Each stretch needs its RouteDataObject: loading the tile at a point of the road - // yields the road, found by its id (the way HHRoutePlanner finds its network roads). - step = Clock::now(); + const Approach* first = nullptr; + const Approach* last = nullptr; + bool use_direct = false; + if (!starts.empty() && !ends.empty()) { + timing_.road_snap = true; + // Every junction node of every approach, at that approach's cost (the + // cheapest approach where two reach one node). + using Seed = onc_ch::BasicQuery::Seed; + std::map source_of, target_of; + const auto add = [](std::map& owner, + const std::vector& from) { + for (const Approach& approach : from) + for (const onc_ch::u32 node : approach.nodes) { + auto it = owner.find(node); + if (it == owner.end() || approach.cost_ms < it->second->cost_ms) + owner[node] = &approach; + } + }; + add(source_of, starts); + add(target_of, ends); + std::vector sources, targets; + for (const auto& kv : source_of) + sources.push_back({kv.first, static_cast(std::lround(kv.second->cost_ms))}); + for (const auto& kv : target_of) + targets.push_back({kv.first, static_cast(std::lround(kv.second->cost_ms))}); + step = Clock::now(); + onc_ch::u32 from = 0, to = 0; + const auto status = impl_->router->route_seeded(sources, targets, runs, cost, cancelled, from, to); + timing_.search_ms = ms_since(step); + timing_.settled = impl_->router->settled(); + if (status == onc_ch::Router::Status::Cancelled) { why = "cancelled"; return {}; } + if (status == onc_ch::Router::Status::Inconsistent) { why = "sidecar_inconsistent"; return {}; } + const bool found = status == onc_ch::Router::Status::Ok; + if (found) { + first = source_of[from]; + last = target_of[to]; + } + use_direct = has_direct && (!found || direct.cost_ms <= cost); + if (!found && !use_direct) { why = "no_route_in_sidecar"; return {}; } + } else if (has_direct) { + use_direct = true; + } else { + // No road near enough to snap onto: the nearest junctions, as before. + step = Clock::now(); + const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost, + start_heading_degrees, cancelled); + timing_.search_ms = ms_since(step); + timing_.settled = impl_->router->settled(); + if (status == onc_ch::Router::Status::NoRoute) { why = "no_route_in_sidecar"; return {}; } + if (status == onc_ch::Router::Status::Inconsistent) { why = "sidecar_inconsistent"; return {}; } + if (status == onc_ch::Router::Status::Cancelled) { why = "cancelled"; return {}; } + if (runs.empty()) { why = "too_short_for_sidecar"; return {}; } + } + timing_.base_edges = use_direct ? 0 : impl_->router->edges().size(); + timing_.road_runs = use_direct ? 0 : runs.size(); + Segments results; - results.reserve(runs.size()); - for (const onc_ch::RoadRun& run : runs) { - SHARED_PTR road; - for (const auto& segment : context->loadRouteSegment(run.anchor_x, run.anchor_y)) { - if (segment && segment->getRoad()->getId() == run.road) { - road = segment->getRoad(); - break; + if (use_direct) { + results.push_back(std::make_shared(direct.road, direct.start, direct.end)); + timing_.direct = true; + } else { + // Each stretch needs its RouteDataObject: loading the tile at a point of the road + // yields the road, found by its id (the way HHRoutePlanner finds its network roads). + step = Clock::now(); + results.reserve(runs.size() + 2); + if (first && first->start != first->end) + results.push_back(std::make_shared(first->road, first->start, first->end)); + for (const onc_ch::RoadRun& run : runs) { + SHARED_PTR road; + for (const auto& segment : context->loadRouteSegment(run.anchor_x, run.anchor_y)) { + if (segment && segment->getRoad()->getId() == run.road) { + road = segment->getRoad(); + break; + } } + const int points = road ? static_cast(road->pointsX.size()) : 0; + if (!road || run.start < 0 || run.end < 0 || run.start >= points || run.end >= points) { + why = "road_missing_in_maps"; + return {}; + } + results.push_back(std::make_shared(road, run.start, run.end)); } - const int points = road ? static_cast(road->pointsX.size()) : 0; - if (!road || run.start < 0 || run.end < 0 || run.start >= points || run.end >= points) { - why = "road_missing_in_maps"; - return {}; - } - results.push_back(std::make_shared(road, run.start, run.end)); + if (last && last->start != last->end) + results.push_back(std::make_shared(last->road, last->start, last->end)); + timing_.roads_ms = ms_since(step); + if (results.empty()) { why = "too_short_for_sidecar"; return {}; } } - timing_.roads_ms = ms_since(step); step = Clock::now(); prepareResult(context.get(), results); diff --git a/backends/osmand/ch_planner.h b/backends/osmand/ch_planner.h index 67d018d..fcfe6e5 100644 --- a/backends/osmand/ch_planner.h +++ b/backends/osmand/ch_planner.h @@ -26,12 +26,15 @@ class ChPlanner { using Segments = std::vector>; struct Timing { - double search_ms = 0; // snap start/end, hierarchy query, unpack + double snap_ms = 0; // start/end onto roads, along them to junctions + double search_ms = 0; // hierarchy query, unpack double roads_ms = 0; // load the route's roads from the maps double prepare_ms = 0; // prepareResult + makeStartEndPointsPrecise std::size_t road_runs = 0; std::size_t base_edges = 0; std::size_t settled = 0; + bool road_snap = false; // snapped onto roads (else to the nearest junctions) + bool direct = false; // start and end on one road: no hierarchy needed }; // Maps the sidecar and checks it was built from exactly these map files diff --git a/backends/osmand/config.cpp b/backends/osmand/config.cpp index 9fb54d7..9dbda38 100644 --- a/backends/osmand/config.cpp +++ b/backends/osmand/config.cpp @@ -81,6 +81,7 @@ Config Config::from_environment() config.fonts = path("OPEN_NAVICORE_OSMAND_FONTS", config.fonts); config.search_index = path("OPEN_NAVICORE_OSMAND_SEARCH_INDEX", config.search_index); config.recents = path("OPEN_NAVICORE_OSMAND_RECENTS", config.recents); + config.parked = path("OPEN_NAVICORE_OSMAND_PARKED", config.parked); config.vector_cache = path("OPEN_NAVICORE_OSMAND_VECTOR_CACHE", config.vector_cache); config.language_marker = path("OPEN_NAVICORE_OSMAND_LANGUAGE_MARKER", config.language_marker); config.hmi_language_file = path("OPEN_NAVICORE_OSMAND_HMI_LANGUAGE", config.hmi_language_file); diff --git a/backends/osmand/config.h b/backends/osmand/config.h index 66d26c0..8d5f629 100644 --- a/backends/osmand/config.h +++ b/backends/osmand/config.h @@ -16,6 +16,8 @@ struct Config { std::string map = "/navi_map/osm"; std::string fonts = "/datastore/navicore-backend/fonts"; std::string recents = "/datastore/navicore-backend/recents.tsv"; + // Where the car stopped last and which way it pointed (HeadingMemory::Parked). + std::string parked = "/datastore/navicore-backend/parked.txt"; // Address search index built from the maps (search/search_index.h); // without it search uses OsmAnd's slower name search. // Lives with the maps it is built from. diff --git a/backends/osmand/navigation_worker.cpp b/backends/osmand/navigation_worker.cpp index 112a9c8..b92691a 100644 --- a/backends/osmand/navigation_worker.cpp +++ b/backends/osmand/navigation_worker.cpp @@ -816,11 +816,13 @@ class NavigationWorker::Impl { request.heading_degrees.value_or(-1.0)); if (!segments.empty() && accept_route(segments, "ch")) { const ChPlanner::Timing& timing = ch_->last_timing(); - char line[160]; + char line[200]; std::snprintf(line, sizeof(line), - "worker=ch_route search_ms=%.1f roads_ms=%.0f prepare_ms=%.0f runs=%zu edges=%zu settled=%zu", - timing.search_ms, timing.roads_ms, timing.prepare_ms, timing.road_runs, - timing.base_edges, timing.settled); + "worker=ch_route snap=%s snap_ms=%.0f search_ms=%.1f roads_ms=%.0f prepare_ms=%.0f " + "runs=%zu edges=%zu settled=%zu", + timing.direct ? "same_road" : timing.road_snap ? "road" : "node", + timing.snap_ms, timing.search_ms, timing.roads_ms, timing.prepare_ms, + timing.road_runs, timing.base_edges, timing.settled); trace(line); found.push_back(std::move(segments)); } else if (!cancel->isAborted()) { diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index 07e351b..d0db501 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -328,6 +328,35 @@ ui::GeoPoint simulated_position(const ui::RouteAlternative& route, return route.geometry.back(); } +// The parked record: "heading latitude longitude" on one line, written to +// ".tmp" and renamed over the target, as the recents are. +bool load_parked(const std::string& path, HeadingMemory::Parked& parked) +{ + std::FILE* input = std::fopen(path.c_str(), "r"); + if (!input) return false; + const bool ok = std::fscanf(input, "%lf %lf %lf", &parked.heading_degrees, &parked.latitude, + &parked.longitude) == 3; + std::fclose(input); + return ok && std::isfinite(parked.heading_degrees) && std::fabs(parked.latitude) <= 90.0 && + std::fabs(parked.longitude) <= 180.0; +} + +bool save_parked(const std::string& path, const HeadingMemory::Parked& parked) +{ + const std::string temporary = path + ".tmp"; + std::FILE* output = std::fopen(temporary.c_str(), "w"); + if (!output) return false; + bool ok = std::fprintf(output, "%.1f %.7f %.7f\n", parked.heading_degrees, parked.latitude, + parked.longitude) > 0; + ok = std::fflush(output) == 0 && ok; + ok = std::fclose(output) == 0 && ok; + if (!ok) { + std::remove(temporary.c_str()); + return false; + } + return std::rename(temporary.c_str(), path.c_str()) == 0; +} + bool seeded_destinations(const std::string& query, std::vector& output) { @@ -444,6 +473,16 @@ bool OsmAndEngine::initialize(const Config& config, { config_ = config; configure_language(); + // Where the car was parked: the map opens there, and a first route from the + // spot starts the way the car points. + { + HeadingMemory::Parked parked; + if (load_parked(config.parked, parked)) { + heading_memory_.restore(parked); + last_location_ = {parked.latitude, parked.longitude}; + trace("parked=restored"); + } + } simulation_enabled_ = config.simulate_route; bench_detour_.enable(config.simulate_detour); if (config.voice) { @@ -737,7 +776,8 @@ void OsmAndEngine::check_off_route(const ui::GuidanceState& state, trace_result("reroute=submit", revision, static_cast(state.off_route_metres)); navigation_worker_->submit_route(revision, *navigation_->destination(), position, false, - heading_memory_.heading(now)); + heading_memory_.start_heading(now, position.latitude, + position.longitude)); } void OsmAndEngine::apply_map_commands() @@ -858,7 +898,13 @@ bool OsmAndEngine::apply_camera() { // Also while searching: a destination picked there starts this way. const auto moving = motion_.predict(now_s); - heading_memory_.observe(moving.valid, moving.speed_mps, moving.heading_degrees, now); + const ui::GeoPoint here = current_location(); + heading_memory_.observe(moving.valid, moving.speed_mps, moving.heading_degrees, now, + has_valid_position_ ? &here.latitude : nullptr, + has_valid_position_ ? &here.longitude : nullptr); + HeadingMemory::Parked parked; + if (heading_memory_.take_save(parked)) + trace(save_parked(config_.parked, parked) ? "parked=saved" : "error=parked_save"); } const auto screen = navigation_->screen(); if (screen == ui::Screen::Search) { @@ -1600,11 +1646,12 @@ void OsmAndEngine::submit_navigation_requests() submitted_route_revision_ = navigation_->route_revision(); trace_result("engine=route_submit", submitted_route_revision_, 1u); if (ensure_navigation_worker()) { + const ui::GeoPoint origin = current_location(); navigation_worker_->submit_route(submitted_route_revision_, - *navigation_->destination(), current_location(), - true, - heading_memory_.heading( - std::chrono::steady_clock::now())); + *navigation_->destination(), origin, true, + heading_memory_.start_heading( + std::chrono::steady_clock::now(), + origin.latitude, origin.longitude)); } } } diff --git a/backends/osmand/reroute_state.h b/backends/osmand/reroute_state.h index b1654c3..fe72be5 100644 --- a/backends/osmand/reroute_state.h +++ b/backends/osmand/reroute_state.h @@ -7,36 +7,103 @@ namespace navicore_osmand { // The driving direction a new route starts with: the motion heading while the -// car moves, kept for a while after it stops (lights, a queue) and forgotten -// after that, since a parked car's last heading says little. +// car moves, and kept for a while after it stops (lights, a queue). A car that +// stands where it stopped still points that way, so start_heading() also keeps +// it there for good (parked, the nav restarted, a saved record), until the car +// has moved away without a heading (a slow manoeuvre in a car park). class HeadingMemory { public: using Clock = std::chrono::steady_clock; static constexpr double kMinSpeedMps = 1.5; // the camera's heading threshold static constexpr std::chrono::seconds kKeepAfterStop{30}; - - void observe(bool valid, double speed_mps, double heading_degrees, Clock::time_point now) + static constexpr double kSameSpotMetres = 30.0; // GPS noise of a standing car + + // Where the car stopped and which way it pointed. + struct Parked { + double heading_degrees = 0.0; + double latitude = 0.0; + double longitude = 0.0; + }; + + // position: the car's position with the motion, when known. + void observe(bool valid, double speed_mps, double heading_degrees, Clock::time_point now, + const double* latitude = nullptr, const double* longitude = nullptr) { - if (!valid || speed_mps < kMinSpeedMps) + if (!valid || speed_mps < kMinSpeedMps) { + // Stopped: a new spot is worth saving once. + if (moving_ && position_known_ && (!saved_ || !near(saved_spot_, spot_.latitude, spot_.longitude))) { + saved_spot_ = spot_; + saved_ = true; + save_pending_ = true; + } + moving_ = false; return; + } heading_degrees_ = heading_degrees; seen_at_ = now; known_ = true; + live_ = true; + moving_ = true; + if (latitude && longitude) { + spot_ = {heading_degrees, *latitude, *longitude}; + position_known_ = true; + } } // The heading if one was seen within max_age. std::optional heading(Clock::time_point now, Clock::duration max_age = kKeepAfterStop) const { - if (!known_ || now - seen_at_ > max_age) + if (!live_ || now - seen_at_ > max_age) return std::nullopt; return heading_degrees_; } + // The direction a route from `latitude, longitude` starts with: the recent + // heading, or the one the car had where it stopped, while it is still there. + std::optional start_heading(Clock::time_point now, double latitude, + double longitude) const + { + if (const auto recent = heading(now)) return recent; + if (!known_ || !position_known_ || !near(spot_, latitude, longitude)) return std::nullopt; + return spot_.heading_degrees; + } + // A saved record from before a restart; real motion replaces it. + void restore(const Parked& parked) + { + if (known_) return; + heading_degrees_ = parked.heading_degrees; + spot_ = parked; + saved_spot_ = parked; + known_ = position_known_ = saved_ = true; + } + // The spot to save, once per stop at a new spot. + bool take_save(Parked& parked) + { + if (!save_pending_) return false; + save_pending_ = false; + parked = saved_spot_; + return true; + } private: - bool known_ = false; + static bool near(const Parked& spot, double latitude, double longitude) + { + const double north = (latitude - spot.latitude) * 111320.0; + const double east = (longitude - spot.longitude) * 111320.0 * + std::cos(spot.latitude * 3.14159265358979323846 / 180.0); + return std::sqrt(north * north + east * east) <= kSameSpotMetres; + } + + bool known_ = false; // a heading, seen or restored + bool live_ = false; // seen in this run: heading() may use it double heading_degrees_ = 0.0; Clock::time_point seen_at_{}; + bool moving_ = false; + bool position_known_ = false; + Parked spot_; // the last moving position and heading + bool saved_ = false; + Parked saved_spot_; + bool save_pending_ = false; }; // When the car has left the route long enough to ask for a new one, and how diff --git a/tests/ch_test.cpp b/tests/ch_test.cpp index bcdce9a..1f1ff63 100644 --- a/tests/ch_test.cpp +++ b/tests/ch_test.cpp @@ -188,6 +188,17 @@ int main() sidecar->nearest_nodes(2000000000, 2000000000, 4, found); assert(found.empty()); + // nodes_at: the nodes at exactly a point (node ids are renumbered: compare counts) + for (u32 n = 0; n < g.n; n += 7) { + std::vector at; + sidecar->nodes_at(g.x[n], g.y[n], at); + size_t expected = 0; + for (u32 m = 0; m < g.n; ++m) expected += g.x[m] == g.x[n] && g.y[m] == g.y[n]; + assert(at.size() == expected && expected >= 1); + sidecar->nodes_at(g.x[n] + 1, g.y[n], at); + for (u32 m = 0; m < g.n; ++m) assert(!(g.x[m] == g.x[n] + 1 && g.y[m] == g.y[n]) || !at.empty()); + } + // a route between two node positions costs what Dijkstra says (snapping onto the nodes // themselves is at distance zero, so the neighbours' snap penalty keeps them out) Router router(*sidecar); diff --git a/tests/reroute_state_test.cpp b/tests/reroute_state_test.cpp index b6503f9..d556116 100644 --- a/tests/reroute_state_test.cpp +++ b/tests/reroute_state_test.cpp @@ -169,9 +169,41 @@ void test_heading_memory_keeps_a_moving_heading_for_a_while() CHECK(*memory.heading(t0 + std::chrono::seconds(41)) == 180.0); } +void test_heading_memory_keeps_a_parked_heading_at_its_spot() +{ + HeadingMemory memory; + const auto t0 = Clock::now(); + const double lat = 50.4501, lon = 30.5234; + memory.observe(true, 10.0, 41.0, t0, &lat, &lon); + // Stopped: saved once, and kept at the spot long after the 30 s. + memory.observe(true, 0.0, 0.0, t0 + std::chrono::seconds(5)); + HeadingMemory::Parked parked; + CHECK(memory.take_save(parked) && parked.heading_degrees == 41.0 && parked.latitude == lat); + CHECK(!memory.take_save(parked)); + memory.observe(true, 0.0, 0.0, t0 + std::chrono::seconds(6)); + CHECK(!memory.take_save(parked)); // still the same stop + const auto later = t0 + std::chrono::hours(3); + CHECK(!memory.heading(later)); + CHECK(memory.start_heading(later, lat + 0.0001, lon) && + *memory.start_heading(later, lat + 0.0001, lon) == 41.0); // ~11 m: GPS noise + // Moved away (slowly, no heading): forgotten there. + CHECK(!memory.start_heading(later, lat + 0.001, lon)); // ~111 m + // After a restart the saved spot gives the heading, but only there. + HeadingMemory restarted; + restarted.restore(parked); + CHECK(!restarted.heading(t0)); + CHECK(restarted.start_heading(t0, lat, lon) && *restarted.start_heading(t0, lat, lon) == 41.0); + CHECK(!restarted.start_heading(t0, lat + 0.001, lon)); + CHECK(!restarted.take_save(parked)); + // Real motion replaces the restored record. + restarted.observe(true, 8.0, 222.0, t0, &lat, &lon); + CHECK(*restarted.start_heading(t0, lat + 0.001, lon) == 222.0); +} + int main() { test_off_route_needs_sustained_distance(); + test_heading_memory_keeps_a_parked_heading_at_its_spot(); test_arrival_and_threshold_clear_the_timer(); test_failed_request_backs_off(); test_detour_starts_once_and_times_out();