diff --git a/.claude/skills/build-open-navicore/SKILL.md b/.claude/skills/build-open-navicore/SKILL.md index b90a2ed..a34f14c 100644 --- a/.claude/skills/build-open-navicore/SKILL.md +++ b/.claude/skills/build-open-navicore/SKILL.md @@ -43,10 +43,22 @@ workspace that holds this repository, so set them from a linked worktree): | `OSMAND_QNX_ROOT` | the OsmAnd QNX build tree (`osmand-qnx-build`): compiler, core, Qt | | `IFSBUILD_DIR` | ifs-build checkout (`ifs-build`), for `make ifs` | -`navigation.ifs` is the whole navigation for the radio (about 100 MiB): the -provider and its config, the backend, OsmAnd core and its resource bundle -(`OSMAND_RESOURCES_BUNDLE`, default next to the core in the OsmAnd build), -all under `/open-navicore`. Maps and other data are not in it. +`make ifs` writes two things (2026-10-28): + +- `build/qnx/ifs/navigation.ifs` (~0.8 MB): the provider, its config, `boot.sh` + and `50-navicore.pre`; the slot's `50-navicore.ifs` on the radio. +- `build/qnx/navicore-data/navicore/`: the backend `libOpenNaviBackendOsmAnd.so`, + OsmAnd core and its resource bundle (`OSMAND_RESOURCES_BUNDLE`, default next to + the core in the OsmAnd build) as plain files for the slot's data dir; the image + links them into `/open-navicore` at boot. They left the image on 2026-10-24 + (boot time). Maps and other data are in neither. + +Install: skill `deploy-open-navicore` (a backend change is the backend file only). + +Build trees on the D: drive fail at configure (`configure_file ... Operation not +permitted`): build into a Linux path with `BUILD=` or from a clone there. A +linked worktree has no `third_party/lvgl` checkout; copy the main checkout's +(same commit) into the clone. `make ifs` also needs `STOCK_NV_NAVIGATION_CFG=` once (QR39.5, SHA-256 `c889c2b4…d680e`, not committed; take it read-only diff --git a/.claude/skills/deploy-open-navicore/SKILL.md b/.claude/skills/deploy-open-navicore/SKILL.md index 10e0c28..1fb1ed6 100644 --- a/.claude/skills/deploy-open-navicore/SKILL.md +++ b/.claude/skills/deploy-open-navicore/SKILL.md @@ -1,88 +1,103 @@ --- name: deploy-open-navicore -description: Install Open NaviCore on the VP4R bench radio - one image, navigation.ifs (provider, OsmAnd backend, OsmAnd core and resources), staged upload, rename swap, one reboot; verification and rollback. Use when deploying a new build, checking what is installed, or rolling back to the native navigation. +description: Install Open NaviCore on the VP4R bench radio (vp4r layer, A/B slots) - the OsmAnd backend as a plain file in the slot's data dir (deploy_backend.sh), the small provider image 50-navicore.ifs in the slot's ifs dir; staged upload, rename swap, one reboot; verification and rollback. Use when deploying a new build, checking what is installed, or rolling back. --- # Deploy Open NaviCore to the radio -A new version of the navigation is one file, `navigation.ifs`, and one -reboot: +Checked on the bench unit 2026-10-28. The unit boots through the vp4r layer +(`/datastore/vp4r`, `vp4r-loader`): it picks the A/B slot in +`/datastore/vp4r/slot` (`a` or `b`) and mounts `slots//ifs/NN-*.ifs` at `/`. +The navigation is two kinds of file per slot: | On the unit | What | Installed by | |---|---|---| -| `/datastore/navicore/navigation.ifs`, mounted at `/` at boot by the boot overlay | all code under `/open-navicore/`: provider `libNaviCore.so`, its `nv_navigation.cfg` and `boot.sh`, the backend `libOpenNaviBackendOsmAnd.so`, OsmAnd core and resource bundle | `deploy/navigation-ifs/deploy_navigation_ifs.sh` | -| `/datastore/navicore-backend/` | data only: `maps/*.obf`, `recents.tsv`, `vectorcache/`, the bench marker files | by hand (maps), or written by the backend | +| `/datastore/vp4r/slots//data/navicore/` | plain files: the backend `libOpenNaviBackendOsmAnd.so`, `libOsmAndCore_shared.so`, `libOsmAndCore_ResourcesBundle_shared.so`; the image's `50-navicore.pre` links them into `/open-navicore` at every boot (log `/datastore/vp4r/log/navicore.log`: `link rc=0`) | backend: `deploy/navigation-ifs/deploy_backend.sh`; core and bundle by hand (they rarely change) | +| `/datastore/vp4r/slots//ifs/50-navicore.ifs` (~0.8 MB) | `make ifs`'s `navigation.ifs`: provider `libNaviCore.so`, its `nv_navigation.cfg` (also at `/pas/scfg`), `boot.sh`, `/etc/vp4r/init.d/50-navicore.pre`; mounted at `/` | not scripted yet, see 1b | +| `/datastore/navicore-backend/` | data only: `maps/*.obf`, `recents.tsv`, `vectorcache/`, the bench marker files (`osmand-turns`, `disable-ch`, ...) | by hand (maps), or written by the backend | -Every change (UI, map, routing, provider) is a new image. There is no -backend-only install; the code is read-only in the mounted image. +The OsmAnd libraries are out of the image since 2026-10-24: images are mounted +inside the boot barrier and a 100 MB image made boots fail the RH850's J6 startup +window (`50-navicore.pre` header). **Stale:** `/datastore/navicore/navigation.ifs` +(a 110 MB full image of 2026-10-21) is no longer booted, and +`deploy_navigation_ifs.sh` still installs to that path; do not use it for the slot. + +Most changes (UI, map, routing, turn instructions: everything in +`backends/osmand`) are the backend only. The image changes only with the provider +(`src/`), its config, `boot.sh` or `50-navicore.pre`. ## 0. Before touching the unit -- Build first (skill `build-open-navicore`): `make test`, `make` and - `make ifs` pass. +- Build first (skill `build-open-navicore`): `make test`, `make` (and `make ifs` + for an image). `make ifs` also writes `build/qnx/navicore-data/navicore/` (the + three libraries). - Follow the workspace skill `record-unit-modification`: confirm the unit's identity, write the ledger entry first (`pending restart`), update it after the check. - Bench deploy and the one documented reboot are covered by the standing authorization in the workspace `AGENTS.md`. A second reboot is not: ask. - Never loop a reboot. + Never loop a reboot. Other sessions may be using the unit: ask before rebooting. - The unit needs dev-tools mounted (`/usr/bin/bench_rename`, - `/usr/bin/vp4r-sync`, `/usr/bin/vp4r-reboot`); the script checks. -- Space: the image is about 100 MiB and the swap keeps one previous image, - so `/datastore` needs one image of free space (it had 128 MiB on - 2026-10-15, before the old per-file backend copies were removed). + `/usr/bin/vp4r-sync`, `/usr/bin/vp4r-reboot`, `/usr/bin/sha256sum`). +- Space: a backend is ~31 MB and each install keeps the previous one as + `libOpenNaviBackendOsmAnd.before-.so`; delete old ones when space runs low. -## 1. Install +## 1a. Install the backend (the usual case) ```sh -deploy/navigation-ifs/deploy_navigation_ifs.sh build/qnx/ifs/navigation.ifs \ - /bin/ifs-deploy --dry-run # plan only -deploy/navigation-ifs/deploy_navigation_ifs.sh build/qnx/ifs/navigation.ifs \ - /bin/ifs-deploy +deploy/navigation-ifs/deploy_backend.sh build/qnx/navicore-data/navicore/libOpenNaviBackendOsmAnd.so --dry-run +deploy/navigation-ifs/deploy_backend.sh build/qnx/navicore-data/navicore/libOpenNaviBackendOsmAnd.so ``` -It uploads with ifs-build's `ifs-deploy` as `navigation.ifs.new` (read-back -verified by scp), pulls the current image to local `ifs-deploy-backups/`, -then on the unit renames `navigation.ifs` to `navigation.previous.ifs` and -`navigation.ifs.new` to `navigation.ifs` (no copies), flushes and checks the -installed file with the unit's `/usr/bin/sha256sum` (dev-tools) against the -host hash, renaming the previous image back on a mismatch. Never copy over a -mounted IFS in place (a truncated in-place copy once made `mountifs` crash -at boot); renaming is safe. Do **not** use ifs-build's generic `deploy-ifs` -target: it uploads to `/datastore/ifs-overrides`, which the navigation hook -does not read. +It reads the booted slot, uploads (`scp -O`) as `libOpenNaviBackendOsmAnd.so.new`, +checks its sha256 on the unit, renames the active file to +`libOpenNaviBackendOsmAnd.before-.so` and the new one into place (no copies), +flushes and reads back the hash. Then one reboot: `/usr/bin/vp4r-sync`, then +`/usr/bin/vp4r-reboot` (workspace skill `dev-tools-on-radio`). ssh returns in +about a minute. It installs into the booted slot only; the other slot keeps its +own files. -Settings: `RADIO_HOST` (default the bench unit), `RADIO_SSH_KEY` (default -`$HOME/priv_openssh`), `NAVIGATION_IFS_DIR`, `BACKUP_DIR`, `RADIO_SYNC`, -`RADIO_RENAME` (script header). +## 1b. Install the provider image -Then one reboot: `/usr/bin/vp4r-sync`, then `/usr/bin/vp4r-reboot` -(workspace skill `dev-tools-on-radio`). ssh returns in about a minute. +Not scripted for the slot layout yet. By hand, the same pattern: upload +`build/qnx/ifs/navigation.ifs` as `slots//ifs/50-navicore.ifs.new`, check its +sha256 on the unit, `bench_rename` the active `50-navicore.ifs` away (keep it), +`bench_rename` the new one into place, `vp4r-sync`, one reboot. Never copy over a +mounted IFS in place (a truncated in-place copy once made `mountifs` crash at +boot); renaming is safe. Do **not** use ifs-build's generic `deploy-ifs` target. ## 2. Verify -- `/bin/cat /datastore/boot_overlay.log`: the last block has - `open_navicore_mount_rc=0` and `open_navicore_config_link_rc=0`. -- `for f in /open-navicore/*; do echo $f; done` lists the provider, backend, - core and bundle; `nv_navigation` maps them: +- `/bin/cat /datastore/vp4r/log/navicore.log`: the last three lines are + `link rc=0`; `/bin/cat /datastore/vp4r/log/boot.log` for the mounts. +- `ls -l /open-navicore/` (dev-tools `ls`): the three libraries are links into + `slots//data/navicore/`; `nv_navigation` maps them: `/proc/boot/pidin -p mem` (pid from `/proc/boot/pidin -f an`). - Provider trace `/bin/cat /tmp/open-navi.log`; backend trace `/bin/cat /tmp/open-navicore-osmand.log` (start, attach, - `init=resources`, `surface_created=...`, `cluster=publish_status`). + `init=resources`, `surface_created=...`, `cluster=publish_status`; per route + `worker=turns source=organic_maps`, `worker=omaps turns=N ms=M`, or + `worker=omaps_error why=...`). - On screen: hold the day/night button 1.5 s in free drive for the developer menu (build commit, frame rate, raw car inputs, cluster). -- Hash on the unit: `/usr/bin/sha256sum /datastore/navicore/navigation.ifs` - equals the host's `sha256sum build/qnx/ifs/navigation.ifs`. +- Hash on the unit: `/usr/bin/sha256sum + /datastore/vp4r/slots//data/navicore/libOpenNaviBackendOsmAnd.so` equals + the host's. - Update the ledger entry to `active`, or record what failed. ## 3. Rollback -- Previous version: on the unit `/bin/rm navigation.ifs; - /usr/bin/bench_rename navigation.previous.ifs navigation.ifs`, flush, - reboot (or install a local backup from `ifs-deploy-backups/` with the - script). -- Back to the native navigation: `touch /datastore/navicore/disabled` and - reboot (the boot hook leaves the factory config in place). +- Previous backend: on the unit, in `slots//data/navicore/`, + `/usr/bin/bench_rename libOpenNaviBackendOsmAnd.so libOpenNaviBackendOsmAnd.bad.so` + and the wanted `libOpenNaviBackendOsmAnd.before-.so` back to + `libOpenNaviBackendOsmAnd.so`, flush, reboot. +- Turn instructions from OsmAnd instead of Organic Maps, no reinstall: + `touch /datastore/navicore-backend/osmand-turns`, restart the navigation. +- Without the three library files the provider keeps its built-in backend + (`50-navicore.pre`). +- Back to the native navigation: the old marker `touch + /datastore/navicore/disabled` was read by the pre-vp4r boot hook; not + checked with the vp4r layer (2026-10-28). - A provider that crashes at every start makes System Manager reset the unit after three relaunches; ssh comes up first, so the marker can be created between resets. diff --git a/AGENTS.md b/AGENTS.md index a8d3823..d6748e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,15 @@ # Agent notes for open_navicore +## Failures: obvious, not silent + +- An obvious failure is better than a silent fallback (owner preference, 2026-10-28). + When a component fails, make it visible (the feature visibly missing, an error + trace line), do not quietly substitute an older or weaker path that hides it. +- A fallback is only for an explicit switch: e.g. OsmAnd's own manoeuvres run only + when Organic Maps' turns are switched off (marker `osmand-turns`), never because + Organic Maps' code failed on a route (that route gets no turns and + `worker=omaps_error`). + ## Merging pull requests - Merge with **rebase**, not squash (owner preference, 2026-10-20): diff --git a/backends/osmand/CMakeLists.txt b/backends/osmand/CMakeLists.txt index 7614dad..6e422c5 100644 --- a/backends/osmand/CMakeLists.txt +++ b/backends/osmand/CMakeLists.txt @@ -99,8 +99,20 @@ add_custom_target(build_info_git -P ${ONC_ROOT}/cmake/build_info.cmake BYPRODUCTS ${_build_info} VERBATIM) +# Turn instructions: Organic Maps' car turn generator on OsmAnd's routes +# (omaps_turns.cpp; the vendored OM code in third_party/organicmaps-routing). A +# static library so that OM's shim headers stay out of the backend's include path. +include(${ONC_ROOT}/third_party/organicmaps-routing/sources.cmake) +add_library(organicmaps_turns STATIC omaps_turns.cpp ${ONC_ORGANICMAPS_SOURCES}) +target_include_directories(organicmaps_turns PRIVATE ${ONC_ORGANICMAPS_INCLUDES} + ${ONC_OSMAND_INCLUDES} ${CMAKE_CURRENT_SOURCE_DIR}) +target_compile_definitions(organicmaps_turns PRIVATE ${ONC_OSMAND_DEFINES}) +# Vendored code: its warnings are upstream's. +target_compile_options(organicmaps_turns PRIVATE ${ONC_OSMAND_FLAGS} -w) + add_library(osmand_backend SHARED osmand_backend.cpp config.cpp session.cpp osmand_engine.cpp navigation_worker.cpp ch_planner.cpp + route_maneuvers.cpp thread_priority.cpp crash_reporter.cpp frame_metrics.cpp build_info.cpp gpu_upload_context.cpp ui/gl_overlay_compositor.cpp @@ -111,7 +123,7 @@ target_include_directories(osmand_backend PRIVATE ${ONC_OSMAND_INCLUDES} ${CMAKE_CURRENT_BINARY_DIR}) target_compile_definitions(osmand_backend PRIVATE ${ONC_OSMAND_DEFINES}) target_compile_options(osmand_backend PRIVATE ${ONC_WARNINGS} ${ONC_OSMAND_FLAGS}) -target_link_libraries(osmand_backend PRIVATE navigation_ui osmand_core EGL GLESv2 z c) +target_link_libraries(osmand_backend PRIVATE navigation_ui organicmaps_turns osmand_core EGL GLESv2 z c) set_target_properties(osmand_backend PROPERTIES OUTPUT_NAME OpenNaviBackendOsmAnd LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} SKIP_BUILD_RPATH ON) target_link_options(osmand_backend PRIVATE -Wl,--as-needed -static-libstdc++ -static-libgcc diff --git a/backends/osmand/config.cpp b/backends/osmand/config.cpp index 9dbda38..4470478 100644 --- a/backends/osmand/config.cpp +++ b/backends/osmand/config.cpp @@ -78,6 +78,8 @@ Config Config::from_environment() map_is_directory ? config.map + "/car.chr" : config.map + ".chr"); if (marker_or_environment("OPEN_NAVICORE_OSMAND_CH_DISABLE", "/datastore/navicore-backend/disable-ch")) config.ch_sidecar.clear(); + config.osmand_turns = marker_or_environment("OPEN_NAVICORE_OSMAND_TURNS", + "/datastore/navicore-backend/osmand-turns"); 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); diff --git a/backends/osmand/config.h b/backends/osmand/config.h index 8d5f629..0cbb728 100644 --- a/backends/osmand/config.h +++ b/backends/osmand/config.h @@ -35,6 +35,10 @@ struct Config { // cannot serve a route. Empty when disabled (marker // /datastore/navicore-backend/disable-ch, or OPEN_NAVICORE_OSMAND_CH_DISABLE=1). std::string ch_sidecar = ""; + // Turn instructions come from Organic Maps' turn generator (omaps_turns.h). + // OsmAnd's own only with the marker /datastore/navicore-backend/osmand-turns + // (or OPEN_NAVICORE_OSMAND_TURNS=1); never as a fallback when OM fails. + bool osmand_turns = false; // Bench tools (markers in /datastore/navicore-backend, see README). bool simulate_route = false; // enable-route-simulation diff --git a/backends/osmand/navigation_worker.cpp b/backends/osmand/navigation_worker.cpp index b92691a..cdc80b0 100644 --- a/backends/osmand/navigation_worker.cpp +++ b/backends/osmand/navigation_worker.cpp @@ -7,6 +7,7 @@ #include "diagnostics.h" #include "junction_shape.h" #include "route_check.h" +#include "route_maneuvers.h" #include "search/search_index.h" #include "session.h" #include "ui/localization.h" @@ -219,46 +220,6 @@ std::string duration_label(double seconds) return ui::loc::format_duration_minutes(static_cast(std::lround(seconds / 60.0))); } -ui::ManeuverKind maneuver_kind(int value) -{ - switch (value) { - case TurnType::TL: return ui::ManeuverKind::Left; - case TurnType::TSLL: return ui::ManeuverKind::SlightLeft; - case TurnType::TSHL: return ui::ManeuverKind::SharpLeft; - case TurnType::TR: return ui::ManeuverKind::Right; - case TurnType::TSLR: return ui::ManeuverKind::SlightRight; - case TurnType::TSHR: return ui::ManeuverKind::SharpRight; - case TurnType::KL: return ui::ManeuverKind::KeepLeft; - case TurnType::KR: return ui::ManeuverKind::KeepRight; - case TurnType::TU: - case TurnType::TRU: return ui::ManeuverKind::UTurn; - case TurnType::RNDB: - case TurnType::RNLB: return ui::ManeuverKind::Roundabout; - default: return ui::ManeuverKind::Straight; - } -} - -// OsmAnd lane value: bit 0 = the route uses the lane, bits 1-4 its main -// turn, bits 5-9 a second turn (TurnType::getPrimaryTurn/getSecondaryTurn). -std::vector lanes_of(const SHARED_PTR& turn) -{ - std::vector lanes; - if (!turn) - return lanes; - for (const int value : turn->getLanes()) { - ui::Lane lane; - const int primary = TurnType::getPrimaryTurn(value); - const int secondary = TurnType::getSecondaryTurn(value); - lane.kind = maneuver_kind(primary ? primary : TurnType::C); - lane.combined = secondary != 0; - if (lane.combined) - lane.also = maneuver_kind(secondary); - lane.recommended = (value & 1) != 0; - lanes.push_back(lane); - } - return lanes; -} - // Routing runs for seconds. nv_navigation is pinned to one core, where the // render thread (priority 20) leaves it about half the CPU: a 15 km route // took 7.3 s there against 3.7 s free to use either core (route_bench, @@ -289,52 +250,21 @@ void place_worker_thread(int priority = kWorkerPriority, const char* name = "wor trace(line); } -using Segments = std::vector>; - -// Bearings over the first 10 m of each road, as OsmAnd's own turn decision -// (getTurnInfo, DIST_BEARING_DETECT). -constexpr float kJunctionBearingMetres = 10.0f; - -// The junction at the start of segments[index] (where OsmAnd puts the -// turn): the route's and every other road's direction, relative to the -// incoming direction (positive clockwise). Other roads: the segment's -// attached roads at its start point (prepareResult / -// attachRoadSegments: the incoming road's continuation and each road the -// router could leave the node by; one-way roads that only enter the node -// are not attached), plus the route's own road behind the node, which -// OsmAnd does not attach (same way id). -ui::JunctionShape junction_of(Segments& segments, std::size_t index) -{ - if (index == 0 || index >= segments.size()) return {}; - const auto& previous = segments[index - 1]; - const auto& current = segments[index]; - if (!previous || !current || !previous->object || !current->object) return {}; - const double incoming = - previous->getBearingEnd(previous->getEndPointIndex(), kJunctionBearingMetres); - const int start = current->getStartPointIndex(); - const double route = current->getBearingBegin(start, kJunctionBearingMetres); - std::vector arms; - for (const auto& attached : current->getAttachedRoutes(start)) { - if (!attached || !attached->object) continue; - arms.push_back(degreesDiff(attached->getBearingBegin(), incoming)); - } - const bool forward = current->getEndPointIndex() > start; - const int points = static_cast(current->object->getPointsLength()); - if (current->object->getId() != previous->object->getId() && - (forward ? start > 0 : start < points - 1)) { - const double behind = - current->object->directionRoute(start, !forward, kJunctionBearingMetres) / M_PI * - 180.0; - arms.push_back(degreesDiff(behind, incoming)); - } - return make_junction_shape(degreesDiff(route, incoming), arms); -} - // One trace line per manoeuvre of the main route (bounded), so that a live // drive can be checked against the cluster picture: the junction // description, the junction picture (0: none) and the symbol sent. constexpr std::size_t kJunctionTraceMax = 40; +// Metres between two route points (equirectangular; route points are metres apart). +double metres_between(const ui::GeoPoint& a, const ui::GeoPoint& b) +{ + constexpr double kDegrees = M_PI / 180.0; + const double mean = (a.latitude + b.latitude) * 0.5 * kDegrees; + const double dy = (b.latitude - a.latitude) * 111320.0; + const double dx = (b.longitude - a.longitude) * 111320.0 * std::cos(mean); + return std::sqrt(dx * dx + dy * dy); +} + void trace_junction(std::size_t number, const ui::Maneuver& maneuver) { const auto& j = maneuver.junction; @@ -391,11 +321,13 @@ class NavigationWorker::Impl { std::vector map_paths, std::string routing_xml, const std::string& search_index, - std::string ch_sidecar) + std::string ch_sidecar, + bool organic_turns) : obfs_(std::move(obfs)), wakeup_(std::move(wakeup)), map_paths_(std::move(map_paths)), routing_xml_(std::move(routing_xml)), - ch_sidecar_(std::move(ch_sidecar)) + ch_sidecar_(std::move(ch_sidecar)), organic_turns_(organic_turns) { + trace(organic_turns_ ? "worker=turns source=organic_maps" : "worker=turns source=osmand"); // Opened here, read only by the worker thread started below. trace(index_.open(search_index) ? "worker=search_index" : "worker=no_search_index"); // Start only after every request/result flag below has completed @@ -806,6 +738,33 @@ class NavigationWorker::Impl { if (request.heading_degrees) trace_result("worker=route_heading", request.revision, static_cast(*request.heading_degrees)); + // Organic Maps' turns for each route found, while its routing context (the + // roads at every node) is alive; parallel to |found|. + std::vector found_turns; + const auto annotate = [&](RoutingContext& context) { + while (found_turns.size() < found.size()) { + if (!organic_turns_) { + found_turns.emplace_back(); + continue; + } + const auto annotate_started = std::chrono::steady_clock::now(); + omaps::Result result = omaps::annotate( + context, found[found_turns.size()], request.origin.latitude, + request.origin.longitude, request.destination.latitude, + request.destination.longitude); + const long long ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - annotate_started).count(); + char line[200]; + if (result.ok) + std::snprintf(line, sizeof(line), "worker=omaps turns=%zu ms=%lld", + result.turns.size(), ms); + else + std::snprintf(line, sizeof(line), "worker=omaps_error why=%.150s ms=%lld", + result.error.c_str(), ms); + trace(line); + found_turns.push_back(std::move(result)); + } + }; // Both ends on one sidecar node: a route of a few metres, which A* finds // at once and HH (seconds over the whole network) often does not. bool skip_hh = false; @@ -825,6 +784,7 @@ class NavigationWorker::Impl { timing.road_runs, timing.base_edges, timing.settled); trace(line); found.push_back(std::move(segments)); + annotate(*context); } else if (!cancel->isAborted()) { trace(("worker=ch_fallback why=" + (why.empty() ? std::string("route_rejected") : why)).c_str()); skip_hh = why == "too_short_for_sidecar"; @@ -835,6 +795,7 @@ class NavigationWorker::Impl { auto context = new_context(); found = route_hh(front_end, context, sx, sy, ex, ey, request.alternatives && kAlternativeRoutes); + annotate(*context); } if (found.empty() && !cancel->isAborted()) { // A* (no HH data, or HH found nothing usable). @@ -847,7 +808,10 @@ class NavigationWorker::Impl { std::vector intermediates_y; auto segments = front_end.searchRoute(context, sx, sy, ex, ey, intermediates_x, intermediates_y, nullptr); - if (!segments.empty()) found.push_back(std::move(segments)); + if (!segments.empty()) { + found.push_back(std::move(segments)); + annotate(*context); + } } if (cancel->isAborted() || found.empty()) return {}; { @@ -860,12 +824,26 @@ class NavigationWorker::Impl { trace(line); } // Fastest first; the others are labelled against it. - std::stable_sort(found.begin(), found.end(), [](const Segments& a, const Segments& b) { - return duration_of(a) < duration_of(b); + std::vector order(found.size()); + for (std::size_t index = 0; index < order.size(); ++index) order[index] = index; + std::stable_sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) { + return duration_of(found[a]) < duration_of(found[b]); }); + { + std::vector sorted; + std::vector sorted_turns; + for (const std::size_t index : order) { + sorted.push_back(std::move(found[index])); + sorted_turns.push_back(std::move(found_turns[index])); + } + found = std::move(sorted); + found_turns = std::move(sorted_turns); + } std::vector output; for (std::size_t index = 0; index < found.size() && index < kMaxRoutes; ++index) { - ui::RouteAlternative alternative = convert(request, found, index); + // Organic Maps switched off: OsmAnd's own manoeuvres (no Result). + const omaps::Result* turns = organic_turns_ ? &found_turns[index] : nullptr; + ui::RouteAlternative alternative = convert(request, found, index, turns); if (alternative.geometry.size() < 2) continue; output.push_back(std::move(alternative)); } @@ -883,8 +861,10 @@ class NavigationWorker::Impl { // One routing result as a UI route; geometry shorter than two points // means unusable. + // turns: Organic Maps' turns for this route (omaps_turns.h); null or failed: + // OsmAnd's own manoeuvres. ui::RouteAlternative convert(const Request& request, std::vector& found, - std::size_t route_index) + std::size_t route_index, const omaps::Result* turns) { Segments& segments = found[route_index]; // getStreetName takes it non-const ui::RouteAlternative alternative; @@ -892,15 +872,22 @@ class NavigationWorker::Impl { : "car-alternative-" + std::to_string(route_index); alternative.reason = "Fastest"; alternative.arrival = "--"; + // Per segment: route distance and geometry index at its start, its road. + std::vector distance_at(segments.size(), 0.0); + std::vector geometry_at(segments.size(), 0); + std::vector road_of(segments.size()); for (std::size_t segment_index = 0; segment_index < segments.size(); ++segment_index) { const auto& segment = segments[segment_index]; + distance_at[segment_index] = alternative.distance_metres; + geometry_at[segment_index] = + alternative.geometry.empty() ? 0 : alternative.geometry.size() - 1u; if (!segment) continue; const double distance_at_start = alternative.distance_metres; - const std::size_t geometry_at_start = alternative.geometry.size(); // Native road names (the design fonts include Cyrillic). std::string road = segment->getStreetName( "", false, segments, static_cast(segment_index)); + road_of[segment_index] = road; int limit = 0; if (segment->object) { const float metres_per_second = @@ -911,25 +898,6 @@ class NavigationWorker::Impl { if (alternative.roads.empty() || alternative.roads.back().name != road || alternative.roads.back().speed_limit_kmh != limit) alternative.roads.push_back({distance_at_start, road, limit}); - if (segment->turnType && - segment->turnType->getValue() != TurnType::C) { - ui::Maneuver maneuver; - maneuver.kind = maneuver_kind(segment->turnType->getValue()); - maneuver.road = road; - maneuver.distance_from_start_metres = distance_at_start; - maneuver.geometry_index = geometry_at_start; - maneuver.roundabout_exit = segment->turnType->getExitOut(); - maneuver.lanes = lanes_of(segment->turnType); - maneuver.left_side = segment->turnType->isLeftSide(); - maneuver.turn_angle_degrees = segment->turnType->getTurnAngle(); - if (!segment->turnType->isRoundAbout()) { - maneuver.junction = junction_of(segments, segment_index); - summarize_lanes(maneuver.lanes, maneuver.junction); - } - if (route_index == 0 && alternative.maneuvers.size() < kJunctionTraceMax) - trace_junction(alternative.maneuvers.size(), maneuver); - alternative.maneuvers.push_back(std::move(maneuver)); - } alternative.distance_metres += segment->distance; alternative.duration_seconds += segment->segmentTime; const int start = segment->getStartPointIndex(); @@ -947,6 +915,23 @@ class NavigationWorker::Impl { alternative.duration = duration_label(alternative.duration_seconds); alternative.distance = distance_label(alternative.distance_metres); if (alternative.geometry.size() < 2) return alternative; + // The manoeuvres: at their route point, a segment's start or (Organic Maps' + // turns) any point in it; the distance along the geometry from the segment start. + for (auto& placed : route_maneuvers(segments, turns)) { + if (placed.segment >= segments.size()) continue; + ui::Maneuver maneuver = std::move(placed.maneuver); + const std::size_t at = std::min(placed.route_point, alternative.geometry.size() - 1u); + const std::size_t from = std::min(geometry_at[placed.segment], at); + double metres = distance_at[placed.segment]; + for (std::size_t i = from; i < at; ++i) + metres += metres_between(alternative.geometry[i], alternative.geometry[i + 1]); + maneuver.road = road_of[placed.segment]; + maneuver.distance_from_start_metres = std::min(metres, alternative.distance_metres); + maneuver.geometry_index = at; + if (route_index == 0 && alternative.maneuvers.size() < kJunctionTraceMax) + trace_junction(alternative.maneuvers.size(), maneuver); + alternative.maneuvers.push_back(std::move(maneuver)); + } ui::Maneuver arrive; arrive.kind = ui::ManeuverKind::Arrive; arrive.road = request.destination.title; @@ -1051,6 +1036,8 @@ class NavigationWorker::Impl { std::vector map_paths_; std::string routing_xml_; std::string ch_sidecar_; // empty: contraction-hierarchy routing is off + // Turn instructions from Organic Maps' generator (omaps_turns.h); false: OsmAnd's. + bool organic_turns_ = true; std::unique_ptr ch_; SHARED_PTR routing_config_; std::mutex mutex_; @@ -1080,9 +1067,11 @@ NavigationWorker::NavigationWorker(std::shared_ptr obfs, std::vector map_paths, std::string routing_xml, std::string search_index, - std::string ch_sidecar) + std::string ch_sidecar, + bool organic_turns) : impl_(new Impl(std::move(obfs), std::move(wakeup), std::move(map_paths), - std::move(routing_xml), search_index, std::move(ch_sidecar))) + std::move(routing_xml), search_index, std::move(ch_sidecar), + organic_turns)) { } diff --git a/backends/osmand/navigation_worker.h b/backends/osmand/navigation_worker.h index 373b33f..0d1d35b 100644 --- a/backends/osmand/navigation_worker.h +++ b/backends/osmand/navigation_worker.h @@ -39,12 +39,15 @@ class NavigationWorker { // search_index: the address index file (search/search_index.h); when it // is missing or unreadable, search falls back to OsmAnd's name search. + // organic_turns: turn instructions from Organic Maps' generator + // (omaps_turns.h); false: OsmAnd's own. NavigationWorker(std::shared_ptr obfs, std::shared_ptr wakeup, std::vector map_paths, std::string routing_xml, std::string search_index, - std::string ch_sidecar = std::string()); + std::string ch_sidecar = std::string(), + bool organic_turns = true); ~NavigationWorker(); NavigationWorker(const NavigationWorker&) = delete; NavigationWorker& operator=(const NavigationWorker&) = delete; diff --git a/backends/osmand/omaps_turns.cpp b/backends/osmand/omaps_turns.cpp new file mode 100644 index 0000000..61b306e --- /dev/null +++ b/backends/osmand/omaps_turns.cpp @@ -0,0 +1,947 @@ +// omaps_turns: OsmAnd route -> Organic Maps IRoutingResult -> OM car turns. +// See omaps_turns.h. What the OM code reads from mwm features is read here from +// OsmAnd's RouteDataObject; third_party/organicmaps-routing/README.md lists the mapping +// and the defaults used where OsmAnd has no equivalent. + +#include "omaps_turns.h" + +// OsmAnd first: the OM shims define ASSERT/CHECK/LOG macros. +#include "binaryRead.h" +#include "binaryRoutePlanner.h" +#include "generalRouter.h" +#include "routeSegmentResult.h" +#include "routingConfiguration.h" +#include "routingContext.h" + +#include "routing/car_directions.hpp" +#include "routing/lanes/lane_way.hpp" +#include "routing/lanes/lanes_parser.hpp" +#include "routing/loaded_path_segment.hpp" +#include "routing/route.hpp" +#include "routing/routing_result_graph.hpp" +#include "routing/turn_candidate.hpp" +#include "routing/turns.hpp" +#include "routing/turns_generator.hpp" +#include "routing/turns_generator_utils.hpp" + +#include "geometry/mercator.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace navicore_osmand::omaps +{ +namespace +{ +using ftypes::HighwayClass; +using RoadPtr = SHARED_PTR; + +// ---- road attributes (what OM's LoadPathAttributes reads from a feature) ---------------- + +// ftypes::GetHighwayClass (indexer/ftypes_matcher.cpp) on OsmAnd's tags. +HighwayClass HighwayClassOf(RouteDataObject & road) +{ + std::string const highway = road.getHighway(); + if (highway == "motorway" || highway == "motorway_link" || highway == "trunk" || highway == "trunk_link") + return HighwayClass::Trunk; + if (highway == "primary" || highway == "primary_link") + return HighwayClass::Primary; + if (highway == "secondary" || highway == "secondary_link") + return HighwayClass::Secondary; + if (highway == "tertiary" || highway == "tertiary_link") + return HighwayClass::Tertiary; + if (highway == "unclassified" || highway == "residential" || highway == "living_street" || highway == "road") + return HighwayClass::LivingStreet; + if (highway == "service") + { + // OM checks the 3-level types highway-service-driveway/parking_aisle first. + std::string const service = road.getValue("service"); + if (service == "driveway" || service == "parking_aisle") + return HighwayClass::ServiceMinor; + return HighwayClass::Service; + } + if (highway == "track" || highway == "busway") + return HighwayClass::Service; + if (highway == "pedestrian" || highway == "platform" || highway == "footway" || highway == "bridleway" || + highway == "ladder" || highway == "steps" || highway == "cycleway" || highway == "path" || + highway == "construction") + return HighwayClass::Pedestrian; + std::string const route = road.getValue("route"); + if (route == "ferry" || route == "shuttle_train") + return HighwayClass::Transported; + if (road.getValue("man_made") == "pier") + return HighwayClass::Service; + return HighwayClass::Undefined; +} + +// ftypes::IsLinkChecker. +bool IsLink(RouteDataObject & road) +{ + std::string const highway = road.getHighway(); + return highway == "motorway_link" || highway == "trunk_link" || highway == "primary_link" || + highway == "secondary_link" || highway == "tertiary_link"; +} + +// turn:lanes for the travel direction as OsmAnd's getTurnLanesString reads it +// (oneway: turn:lanes; else turn:lanes:forward/backward). When that is empty, OM's +// fallback (GetLanesMetadataTag: plain turn:lanes) is used. +std::string TurnLanesOf(RouteDataObject & road, int oneway, bool forward) +{ + std::string lanes; + if (oneway != 0) + lanes = road.getValue("turn:lanes"); + else + lanes = road.getValue(forward ? "turn:lanes:forward" : "turn:lanes:backward"); + if (lanes.empty()) + lanes = road.getValue("turn:lanes"); + return lanes; +} + +// ---- graph edges (OM's Edge between two junctions of one feature) ----------------------- + +struct LabEdge +{ + FeatureID feature; // invalid for OM's fake start/finish edges + uint32_t segId = 0; + bool forward = true; + m2::PointD start; + m2::PointD end; + RoadPtr road; + + bool IsFake() const { return !feature.IsValid(); } +}; + +routing::Segment ToSegment(LabEdge const & edge) +{ + if (edge.IsFake()) + return routing::Segment(); + return routing::Segment(0 /* mwm */, edge.feature.m_index, edge.segId, edge.forward); +} + +bool IsUTurnPair(LabEdge const & a, LabEdge const & b) +{ + return a.feature == b.feature && a.segId == b.segId && a.forward != b.forward; +} + +// directions_engine_helpers.cpp IsJoint(), unchanged logic on LabEdge. +bool IsJoint(std::vector const & ingoingEdges, std::vector const & outgoingEdges, + LabEdge const & ingoingRouteEdge, LabEdge const & outgoingRouteEdge) +{ + if (ingoingRouteEdge.feature != outgoingRouteEdge.feature) + return true; + + FeatureID const & featureId = ingoingRouteEdge.feature; + uint32_t const segOut = outgoingRouteEdge.segId; + for (LabEdge const & e : ingoingEdges) + if (e.feature != featureId || std::abs(static_cast(segOut - e.segId)) != 1) + return true; + + uint32_t const segIn = ingoingRouteEdge.segId; + for (LabEdge const & e : outgoingEdges) + { + // It's necessary to compare segments for cases when |featureId| is a loop. + if (e.feature != featureId || std::abs(static_cast(segIn - e.segId)) != 1) + return true; + } + return false; +} + +// ---- the IRoutingResult OM's generator reads ---------------------------------------------- + +struct AdjacentEdges +{ + explicit AdjacentEdges(size_t ingoingTurnsCount = 0) : m_ingoingTurnsCount(ingoingTurnsCount) {} + routing::turns::TurnCandidates m_outgoingTurns; + size_t m_ingoingTurnsCount; +}; + +using AdjacentEdgesMap = std::map; + +// RoutingEngineResult (directions_engine_helpers.cpp) without IRoadGraph. +class LabRoutingResult : public routing::turns::IRoutingResult +{ +public: + LabRoutingResult(routing::RouteJunctions const & path, AdjacentEdgesMap const & adjacentEdges, + routing::TUnpackedPathSegments const & pathSegments) + : m_path(path) + , m_adjacentEdges(adjacentEdges) + , m_pathSegments(pathSegments) + { + for (size_t i = 1; i < path.size(); ++i) + m_routeLength += mercator::DistanceOnEarth(path[i - 1].GetPoint(), path[i].GetPoint()); + } + + routing::TUnpackedPathSegments const & GetSegments() const override { return m_pathSegments; } + + void GetPossibleTurns(routing::SegmentRange const & segmentRange, m2::PointD const & junctionPoint, + size_t & ingoingCount, routing::turns::TurnCandidates & outgoingTurns) const override + { + CHECK(!segmentRange.IsEmpty(), ("SegmentRange presents a fake feature.")); + ingoingCount = 0; + outgoingTurns.candidates.clear(); + auto const adjacentEdges = m_adjacentEdges.find(segmentRange); + if (adjacentEdges == m_adjacentEdges.cend()) + return; + ingoingCount = adjacentEdges->second.m_ingoingTurnsCount; + outgoingTurns = adjacentEdges->second.m_outgoingTurns; + } + + double GetPathLength() const override { return m_routeLength; } + geometry::PointWithAltitude GetStartPoint() const override { return m_path.front(); } + geometry::PointWithAltitude GetEndPoint() const override { return m_path.back(); } + +private: + routing::RouteJunctions const & m_path; + AdjacentEdgesMap const & m_adjacentEdges; + routing::TUnpackedPathSegments const & m_pathSegments; + double m_routeLength = 0.0; +}; + +// OM's Generate() is protected/pure-virtual-based; this exposes the car engine. +class LabCarDirectionsEngine : public routing::CarDirectionsEngine +{ +public: + LabCarDirectionsEngine(routing::MwmDataSource & dataSource) + : routing::CarDirectionsEngine(dataSource, std::make_shared()) + { + SetVehicleType(routing::VehicleType::Car); + } +}; + +// ---- building it from OsmAnd --------------------------------------------------------------- + +m2::PointD Mercator31(uint32_t x31, uint32_t y31) +{ + return mercator::FromLatLon(get31LatitudeY(static_cast(y31)), get31LongitudeX(static_cast(x31))); +} + +struct RoadAtNode +{ + RoadPtr road; + int index = 0; +}; + +struct RoutePoint +{ + uint32_t x31 = 0; + uint32_t y31 = 0; + m2::PointD point; + long osmandSegment = -1; // segment whose edge leaves this point + size_t geometry = 0; // index among the route's points (Turn::route_point) + // Route points within kMergeNodesMetres after this one, folded into it: one junction. + std::vector> merged; +}; + +// Route points closer than this are one junction to a driver. OSM has stubs of a +// few centimetres between two junction nodes (48.516022,34.999655: three ways on a +// 0.3 m segment); OM would see a turn onto the stub and another off it. +double constexpr kMergeNodesMetres = 2.0; + +struct RouteEdgeSource +{ + RoadPtr road; // the route's road object (may be a copy with an inserted point) + int copyFrom = 0; + int copyTo = 0; +}; + +class Builder +{ +public: + Builder(RoutingContext & context) : m_context(context) {} + + Result Run(std::vector> const & route, double startLat, double startLon, + double finishLat, double finishLon); + +private: + std::vector const & RoadsAt(uint32_t x31, uint32_t y31); + std::vector RoadsAt(RoutePoint const & point); // with its merged nodes + uint32_t FeatureIndex(RoadPtr const & road); + int OneWay(RoadPtr const & road); + bool Restricted(RoadPtr const & from, RoadPtr const & to, std::vector const & atNode) const; + LabEdge MakeEdge(RoadPtr const & road, int fromIndex, int toIndex); + void EdgesAt(size_t pathIndex, std::vector & ingoing, std::vector & outgoing); + void LoadPathAttributes(LabEdge const & inEdge, routing::LoadedPathSegment & pathSegment); + void FillPathSegments(); + void DumpPathSegments() const; + + RoutingContext & m_context; + std::map, std::vector> m_nodes; + std::unordered_map m_featureIndex; + + // OM layout: path[0] = path[1] = start, path[2..n+1] = route points, path[n+2] = path[n+3] = finish. + routing::RouteJunctions m_path; + std::vector m_routeEdges; // m_path.size() - 1 edges + std::vector m_points; // route points (path index - 2) + AdjacentEdgesMap m_adjacentEdges; + routing::TUnpackedPathSegments m_pathSegments; +}; + +std::vector const & Builder::RoadsAt(uint32_t x31, uint32_t y31) +{ + auto const key = std::make_pair(x31, y31); + auto it = m_nodes.find(key); + if (it != m_nodes.end()) + return it->second; + std::vector roads; + for (auto const & rs : m_context.loadRouteSegment(static_cast(x31), static_cast(y31))) + roads.push_back({rs->getRoad(), rs->getSegmentStart()}); + return m_nodes.emplace(key, std::move(roads)).first->second; +} + +std::vector Builder::RoadsAt(RoutePoint const & point) +{ + std::vector roads = RoadsAt(point.x31, point.y31); + for (auto const & node : point.merged) + { + auto const & more = RoadsAt(node.first, node.second); + roads.insert(roads.end(), more.begin(), more.end()); + } + return roads; +} + +uint32_t Builder::FeatureIndex(RoadPtr const & road) +{ + auto const inserted = m_featureIndex.emplace(road->getId(), static_cast(m_featureIndex.size())); + return inserted.first->second; +} + +int Builder::OneWay(RoadPtr const & road) +{ + return m_context.config->router->isOneWay(road); +} + +// OsmAnd turn restrictions without a via way: no_* from |from| to |to|, or an only_* +// restriction of |from| whose target road is at this node and is not |to|. +bool Builder::Restricted(RoadPtr const & from, RoadPtr const & to, std::vector const & atNode) const +{ + if (from->getId() == to->getId()) + return false; // staying on the road (or its U-turn) is not a turn restriction + bool hasOnly = false; + bool onlyTargetHere = false; + for (auto const & r : from->restrictions) + { + if (r.via != 0) + continue; + bool const isOnly = r.type == RESTRICTION_ONLY_RIGHT_TURN || r.type == RESTRICTION_ONLY_LEFT_TURN || + r.type == RESTRICTION_ONLY_STRAIGHT_ON; + if (static_cast(r.to) == to->getId()) + return !isOnly; // no_* to |to| forbids it, only_* to |to| allows it + if (isOnly) + { + hasOnly = true; + for (auto const & n : atNode) + if (n.road->getId() == static_cast(r.to)) + onlyTargetHere = true; + } + } + return hasOnly && onlyTargetHere; +} + +LabEdge Builder::MakeEdge(RoadPtr const & road, int fromIndex, int toIndex) +{ + LabEdge edge; + edge.feature = FeatureID(0, FeatureIndex(road)); + edge.forward = toIndex > fromIndex; + edge.segId = static_cast(std::min(fromIndex, toIndex)); + edge.start = Mercator31(road->pointsX[fromIndex], road->pointsY[fromIndex]); + edge.end = Mercator31(road->pointsX[toIndex], road->pointsY[toIndex]); + edge.road = road; + return edge; +} + +// IndexRoadGraph::GetIngoingEdges / GetOutgoingEdges at route point |pathIndex| for a car: +// outgoing = segments the route's ingoing segment can continue to, ingoing = segments +// that can enter the route's outgoing segment. One-way per OsmAnd's car profile; a +// U-turn onto the same segment only at a joint or a road end (IndexGraph::IsUTurnAndRestricted); +// turn restrictions without via ways. +void Builder::EdgesAt(size_t pathIndex, std::vector & ingoing, std::vector & outgoing) +{ + ingoing.clear(); + outgoing.clear(); + if (pathIndex < 2 || pathIndex >= m_path.size() - 2) + return; // fake start / finish point + LabEdge const & inEdge = m_routeEdges[pathIndex - 1]; + if (inEdge.IsFake()) + return; // the jump from the start point: no turn is generated there (GetTurnDirection, index 2) + LabEdge const & outEdge = m_routeEdges[pathIndex]; + + RoutePoint const & p = m_points[pathIndex - 2]; + auto const roads = RoadsAt(p); + bool const isJointPoint = roads.size() >= 2; + + for (auto const & at : roads) + { + RoadPtr const & road = at.road; + int const n = road->getPointsLength(); + int const k = at.index; + int const oneway = OneWay(road); + bool const uTurnAllowed = isJointPoint || k == 0 || k == n - 1; + + // Outgoing. + if (k + 1 < n && oneway >= 0) + outgoing.push_back(MakeEdge(road, k, k + 1)); + if (k > 0 && oneway <= 0) + outgoing.push_back(MakeEdge(road, k, k - 1)); + // Ingoing. + if (k > 0 && oneway >= 0) + ingoing.push_back(MakeEdge(road, k - 1, k)); + if (k + 1 < n && oneway <= 0) + ingoing.push_back(MakeEdge(road, k + 1, k)); + + if (!uTurnAllowed) + { + outgoing.erase(std::remove_if(outgoing.begin(), outgoing.end(), + [&](LabEdge const & e) { return IsUTurnPair(e, inEdge); }), + outgoing.end()); + if (!outEdge.IsFake()) + ingoing.erase(std::remove_if(ingoing.begin(), ingoing.end(), + [&](LabEdge const & e) { return IsUTurnPair(e, outEdge); }), + ingoing.end()); + } + } + + // OSM has overlapping ways: different ways on the same nodes (48.516022,34.999655: + // trunk_link way 39364971 and primary way 1552232458 arrive by the same previous + // node, primary ways 105200764 and 105200761 and trunk_link 1552232459 leave by the + // same next node). Edges that leave (or arrive) along the same next point are one + // road to a driver. OsmAnd drops a road whose next/previous point is the route + // road's own (attachSegments, routeResultPreparation.cpp: "if way contains same + // segment (nodes) as different way (do not attach it)"); OM's own maps have none. + // Keep one edge per next point, the route's own when it is among them. + auto const dedupe = [](std::vector & edges, LabEdge const & route, bool outgoingEdges) + { + auto const far = [outgoingEdges](LabEdge const & e) { return outgoingEdges ? e.end : e.start; }; + std::vector kept; + for (auto const & e : edges) + { + bool const isRoute = !route.IsFake() && e.feature == route.feature && e.segId == route.segId && + e.forward == route.forward; + auto same = std::find_if(kept.begin(), kept.end(), [&](LabEdge const & k) { return far(k) == far(e); }); + if (same == kept.end()) + kept.push_back(e); + else if (isRoute) + *same = e; + } + edges.swap(kept); + }; + dedupe(outgoing, outEdge, true); + dedupe(ingoing, inEdge, false); + + // A merged junction: the stub between its nodes is inside it, not a way out or in. + if (!p.merged.empty()) + { + auto const inside = [&](m2::PointD const & q) + { + if (q == p.point) + return true; + for (auto const & node : p.merged) + if (q == Mercator31(node.first, node.second)) + return true; + return false; + }; + outgoing.erase(std::remove_if(outgoing.begin(), outgoing.end(), + [&](LabEdge const & e) { return inside(e.end); }), + outgoing.end()); + ingoing.erase(std::remove_if(ingoing.begin(), ingoing.end(), + [&](LabEdge const & e) { return inside(e.start); }), + ingoing.end()); + } + + outgoing.erase(std::remove_if(outgoing.begin(), outgoing.end(), + [&](LabEdge const & e) { return Restricted(inEdge.road, e.road, roads); }), + outgoing.end()); + if (!outEdge.IsFake()) + ingoing.erase(std::remove_if(ingoing.begin(), ingoing.end(), + [&](LabEdge const & e) { return Restricted(e.road, outEdge.road, roads); }), + ingoing.end()); +} + +// DirectionsEngine::LoadPathAttributes on an OsmAnd road. +void Builder::LoadPathAttributes(LabEdge const & inEdge, routing::LoadedPathSegment & pathSegment) +{ + if (inEdge.IsFake()) + return; + RouteDataObject & road = *inEdge.road; + bool const isForward = inEdge.forward; + int const oneway = OneWay(inEdge.road); + + pathSegment.m_lanes = routing::turns::lanes::ParseLanes(TurnLanesOf(road, oneway, isForward)); + pathSegment.m_highwayClass = HighwayClassOf(road); + pathSegment.m_isLink = IsLink(road); + pathSegment.m_onRoundabout = road.roundabout(); + pathSegment.m_isOneWay = oneway != 0; + + // OsmAnd's getName(lang)/getRef() index |names| with operator[] and so insert empty + // entries into the shared road object; look the default name/ref up read-only. + auto const nameByRule = [&road](int rule) -> std::string + { + auto const it = road.names.find(rule); + return it == road.names.end() ? std::string() : it->second; + }; + std::string lang; + pathSegment.m_roadNameInfo.m_mwmId = inEdge.feature; + pathSegment.m_roadNameInfo.m_isLink = pathSegment.m_isLink; + pathSegment.m_roadNameInfo.m_junction_ref = road.getValue("junction:ref"); + pathSegment.m_roadNameInfo.m_destination_ref = road.getDestinationRef(isForward); + pathSegment.m_roadNameInfo.m_destination = road.getDestinationName(lang, false, isForward); + pathSegment.m_roadNameInfo.m_ref = nameByRule(road.region->refTypeRule); + pathSegment.m_roadNameInfo.m_name = nameByRule(road.region->nameTypeRule); +} + +// DirectionsEngine::FillPathSegmentsAndAdjacentEdgesMap + GetSegmentRangeAndAdjacentEdges, +// same control flow, on LabEdge. +void Builder::FillPathSegments() +{ + size_t const pathSize = m_path.size(); + CHECK_GREATER(pathSize, 1, ()); + CHECK_EQUAL(m_routeEdges.size() + 1, pathSize, ()); + + auto constexpr kInvalidSegId = std::numeric_limits::max(); + uint32_t startSegId = kInvalidSegId; + + routing::RouteJunctions prevJunctions; + std::vector prevSegments; + std::vector ingoingEdges, outgoingEdges; + for (size_t i = 1; i < pathSize; ++i) + { + auto const & currJunction = m_path[i]; + bool const isCurrJunctionFinish = (i + 1 == pathSize); + + EdgesAt(i, ingoingEdges, outgoingEdges); + if (isCurrJunctionFinish) + outgoingEdges.clear(); + + LabEdge const & inEdge = m_routeEdges[i - 1]; + uint32_t const inSegId = inEdge.segId; + + if (startSegId == kInvalidSegId) + startSegId = inSegId; + + prevJunctions.push_back(m_path[i - 1]); + prevSegments.push_back(ToSegment(inEdge)); + + if (!isCurrJunctionFinish && !inEdge.IsFake() && !IsJoint(ingoingEdges, outgoingEdges, inEdge, m_routeEdges[i])) + continue; + + CHECK_EQUAL(prevJunctions.size(), static_cast(std::abs(int(inSegId) - int(startSegId)) + 1), ()); + + prevJunctions.push_back(currJunction); + + AdjacentEdges adjacentEdges(ingoingEdges.size()); + // GetSegmentRangeAndAdjacentEdges. + routing::turns::TurnCandidates & outgoingTurns = adjacentEdges.m_outgoingTurns; + outgoingTurns.isCandidatesAngleValid = true; + routing::SegmentRange const segmentRange(inEdge.feature, startSegId, inSegId, inEdge.forward, inEdge.start, + inEdge.end); + CHECK(segmentRange.IsCorrect(), ()); + m2::PointD const & ingoingPoint = inEdge.start; + m2::PointD const & junctionPoint = inEdge.end; + for (auto const & edge : outgoingEdges) + { + if (edge.IsFake()) + continue; + double angle = 0; + double const distToJunction = mercator::DistanceOnEarth(junctionPoint, edge.start); + if (distToJunction < routing::turns::kFeaturesNearTurnMeters) + angle = math::RadToDeg(routing::turns::PiMinusTwoVectorsAngle(junctionPoint, ingoingPoint, edge.end)); + else + outgoingTurns.isCandidatesAngleValid = false; + outgoingTurns.candidates.emplace_back(angle, ToSegment(edge), HighwayClassOf(*edge.road), IsLink(*edge.road)); + } + if (outgoingTurns.isCandidatesAngleValid) + std::sort(outgoingTurns.candidates.begin(), outgoingTurns.candidates.end(), + base::LessBy(&routing::turns::TurnCandidate::m_angle)); + + routing::LoadedPathSegment pathSegment; + pathSegment.m_segmentRange = segmentRange; + CHECK_EQUAL(prevSegments.size() + 1, prevJunctions.size(), ()); + pathSegment.m_path = std::move(prevJunctions); + pathSegment.m_segments = std::move(prevSegments); + + LoadPathAttributes(inEdge, pathSegment); + + if (!segmentRange.IsEmpty()) + m_adjacentEdges.emplace(segmentRange, std::move(adjacentEdges)); + + m_pathSegments.push_back(std::move(pathSegment)); + + prevJunctions.clear(); + prevSegments.clear(); + startSegId = kInvalidSegId; + } +} + +// JUNCTION_LAB_OMAPS_DEBUG=1: OM's view of the route on stderr. +void Builder::DumpPathSegments() const +{ + for (size_t i = 0; i < m_pathSegments.size(); ++i) + { + auto const & s = m_pathSegments[i]; + ms::LatLon const a = mercator::ToLatLon(s.m_path.front().GetPoint()); + ms::LatLon const b = mercator::ToLatLon(s.m_path.back().GetPoint()); + std::fprintf(stderr, + "omaps seg %zu: %.6f,%.6f -> %.6f,%.6f points=%zu class=%s link=%d oneway=%d roundabout=%d " + "lanes=%zu name=\"%s\" ref=\"%s\" first=%s\n", + i, a.m_lat, a.m_lon, b.m_lat, b.m_lon, s.m_path.size(), ftypes::DebugPrint(s.m_highwayClass).c_str(), + s.m_isLink, s.m_isOneWay, s.m_onRoundabout, s.m_lanes.size(), s.m_roadNameInfo.m_name.c_str(), + s.m_roadNameInfo.m_ref.c_str(), routing::DebugPrint(s.m_segments.front()).c_str()); + auto const it = m_adjacentEdges.find(s.m_segmentRange); + if (it == m_adjacentEdges.end()) + continue; + std::fprintf(stderr, " ingoing=%zu candidates:", it->second.m_ingoingTurnsCount); + for (auto const & c : it->second.m_outgoingTurns.candidates) + std::fprintf(stderr, " [%.1f %s%s f%u s%u%s]", c.m_angle, ftypes::DebugPrint(c.m_highwayClass).c_str(), + c.m_isLink ? " link" : "", c.m_segment.GetFeatureId(), c.m_segment.GetSegmentIdx(), + c.m_segment.IsForward() ? "+" : "-"); + std::fprintf(stderr, "\n"); + } +} + +using navicore_osmand::ui::ManeuverKind; + +// A turn:lanes arrow as the manoeuvre kind the UI draws for a lane. +ManeuverKind LaneKind(routing::turns::lanes::LaneWay way) +{ + using routing::turns::lanes::LaneWay; + switch (way) + { + case LaneWay::ReverseLeft: + case LaneWay::ReverseRight: return ManeuverKind::UTurn; + case LaneWay::SharpLeft: return ManeuverKind::SharpLeft; + case LaneWay::Left: return ManeuverKind::Left; + case LaneWay::MergeToLeft: return ManeuverKind::KeepLeft; + case LaneWay::SlightLeft: return ManeuverKind::SlightLeft; + case LaneWay::SlightRight: return ManeuverKind::SlightRight; + case LaneWay::MergeToRight: return ManeuverKind::KeepRight; + case LaneWay::Right: return ManeuverKind::Right; + case LaneWay::SharpRight: return ManeuverKind::SharpRight; + case LaneWay::None: + case LaneWay::Through: + case LaneWay::Count: break; + } + return ManeuverKind::Straight; +} + +// OM's direction as the backend's manoeuvre. False: no manoeuvre (none, start, +// arrival; the worker adds its own arrival). +bool ManeuverOf(routing::turns::CarDirection direction, Turn & turn) +{ + using routing::turns::CarDirection; + switch (direction) + { + case CarDirection::GoStraight: turn.kind = ManeuverKind::Straight; return true; + case CarDirection::TurnRight: turn.kind = ManeuverKind::Right; return true; + case CarDirection::TurnSharpRight: turn.kind = ManeuverKind::SharpRight; return true; + case CarDirection::TurnSlightRight: turn.kind = ManeuverKind::SlightRight; return true; + case CarDirection::TurnLeft: turn.kind = ManeuverKind::Left; return true; + case CarDirection::TurnSharpLeft: turn.kind = ManeuverKind::SharpLeft; return true; + case CarDirection::TurnSlightLeft: turn.kind = ManeuverKind::SlightLeft; return true; + // OsmAnd's TU is the left U-turn and TRU (left_side) the right one. + case CarDirection::UTurnLeft: turn.kind = ManeuverKind::UTurn; return true; + case CarDirection::UTurnRight: turn.kind = ManeuverKind::UTurn; turn.left_side = true; return true; + // Leaving a motorway or trunk by a link: "keep left/right" is the instruction a + // driver expects there (OM: "take the exit"). + case CarDirection::ExitHighwayToLeft: turn.kind = ManeuverKind::KeepLeft; return true; + case CarDirection::ExitHighwayToRight: turn.kind = ManeuverKind::KeepRight; return true; + case CarDirection::EnterRoundAbout: + case CarDirection::LeaveRoundAbout: + case CarDirection::StayOnRoundAbout: + turn.kind = ManeuverKind::Roundabout; + turn.roundabout = true; + return true; + case CarDirection::None: + case CarDirection::StartAtEndOfStreet: + case CarDirection::ReachedYourDestination: + case CarDirection::Count: break; + } + return false; +} + +Result Builder::Run(std::vector> const & route, double startLat, double startLon, + double finishLat, double finishLon) +{ + Result result; + + // 1. Flatten OsmAnd's segments into route points and road edges; points closer than + // kMergeNodesMetres to the previous one fold into it (one junction). + std::vector sources; + size_t geometry = 0; + uint32_t lastX = 0, lastY = 0; + for (size_t s = 0; s < route.size(); ++s) + { + auto const & segment = route[s]; + if (!segment || !segment->object) + continue; + RoadPtr const & road = segment->object; + int const start = segment->getStartPointIndex(); + int const end = segment->getEndPointIndex(); + int const step = start <= end ? 1 : -1; + for (int i = start;; i += step) + { + RoutePoint p; + p.x31 = road->pointsX[i]; + p.y31 = road->pointsY[i]; + p.point = Mercator31(p.x31, p.y31); + p.osmandSegment = static_cast(s); + // The same as the previous point of the route (a segment starts where the last + // ended): that point once, also when it was merged into the one before. + bool const same = geometry > 0 && lastX == p.x31 && lastY == p.y31; + lastX = p.x31; + lastY = p.y31; + if (!same) + { + p.geometry = geometry++; + if (!m_points.empty()) + { + m_points.back().osmandSegment = static_cast(s); + if (mercator::DistanceOnEarth(m_points.back().point, p.point) < kMergeNodesMetres) + { + // The next edge starts at the merged junction's first node (step 2 numbers + // it from the map road, as a copy). + m_points.back().merged.emplace_back(p.x31, p.y31); + if (i == end) + break; + continue; + } + // A segment that does not start where the previous one ended (not expected) + // gets an edge numbered from the map road alone (see step 2). + sources.push_back({road, i == start ? i : i - step, i}); + } + m_points.push_back(p); + } + if (i == end) + break; + } + } + if (m_points.size() < 2) + { + result.error = "route has fewer than two points"; + return result; + } + + // 2. Route edges in the map's own point numbering (OsmAnd may route on a copy of a + // road with the precise start/end point inserted). + std::vector realEdges; + for (size_t e = 0; e < sources.size(); ++e) + { + auto const & src = sources[e]; + RoutePoint const & a = m_points[e]; + RoutePoint const & b = m_points[e + 1]; + std::vector ia, ib; + for (auto const & n : RoadsAt(a.x31, a.y31)) + if (n.road->getId() == src.road->getId()) + ia.push_back(n.index); + RoadPtr original; + for (auto const & n : RoadsAt(b.x31, b.y31)) + if (n.road->getId() == src.road->getId()) + { + ib.push_back(n.index); + original = n.road; + } + if (!original) + for (auto const & n : RoadsAt(a.x31, a.y31)) + if (n.road->getId() == src.road->getId()) + original = n.road; + bool const forward = src.copyTo > src.copyFrom; + int from = -1, to = -1; + for (int x : ia) + for (int y : ib) + if (std::abs(x - y) == 1 && (y > x) == forward) + { + from = x; + to = y; + } + LabEdge edge; + if (from >= 0) + { + edge = MakeEdge(original, from, to); + } + else + { + // A point of the copy that the map road does not have: keep the copy's geometry, + // number the segment by the neighbour that exists in the map road. + edge.feature = FeatureID(0, FeatureIndex(src.road)); + edge.forward = forward; + if (!ib.empty()) + edge.segId = static_cast(forward ? ib.front() - 1 : ib.front()); + else if (!ia.empty()) + edge.segId = static_cast(forward ? ia.front() : ia.front() - 1); + else + edge.segId = static_cast(std::min(src.copyFrom, src.copyTo)); + edge.start = a.point; + edge.end = b.point; + edge.road = original ? original : src.road; + } + realEdges.push_back(edge); + } + + // 3. OM's layout with fake start/finish loops and jumps. + m2::PointD const startPoint = mercator::FromLatLon(startLat, startLon); + m2::PointD const finishPoint = mercator::FromLatLon(finishLat, finishLon); + auto fake = [](m2::PointD const & a, m2::PointD const & b) + { + LabEdge e; + e.start = a; + e.end = b; + return e; + }; + m_path.push_back(startPoint); + m_path.push_back(startPoint); + m_routeEdges.push_back(fake(startPoint, startPoint)); + m_routeEdges.push_back(fake(startPoint, m_points.front().point)); + for (auto const & p : m_points) + m_path.push_back(p.point); + for (auto const & e : realEdges) + m_routeEdges.push_back(e); + m_routeEdges.push_back(fake(m_points.back().point, finishPoint)); + m_routeEdges.push_back(fake(finishPoint, finishPoint)); + m_path.push_back(finishPoint); + m_path.push_back(finishPoint); + + // 4. Loaded path segments + adjacent edges, then OM's annotation. + FillPathSegments(); + + if (std::getenv("JUNCTION_LAB_OMAPS_DEBUG")) + DumpPathSegments(); + + LabRoutingResult routingResult(m_path, m_adjacentEdges, m_pathSegments); + if (std::getenv("JUNCTION_LAB_OMAPS_DEBUG")) + { + // OM's smoothed turn angle (CalcTurnAngle) and one-segment angle at each joint. + routing::NumMwmIds const numMwmIds; + auto const settings = routing::GetRoutingSettings(routing::VehicleType::Car); + for (size_t i = 3; i + 2 < m_pathSegments.size(); ++i) + { + routing::turns::TurnInfo info(&m_pathSegments[i - 1], &m_pathSegments[i]); + ms::LatLon const at = mercator::ToLatLon(m_pathSegments[i].m_path.front().GetPoint()); + std::fprintf(stderr, "omaps angle into seg %zu at %.6f,%.6f: turn=%.1f one_segment=%.1f\n", i, at.m_lat, + at.m_lon, routing::turns::CalcTurnAngle(routingResult, i, numMwmIds, settings), + routing::turns::CalcOneSegmentTurnAngle(info)); + } + } + routing::MwmDataSource dataSource; + LabCarDirectionsEngine engine(dataSource); + std::vector routeSegments; + engine.MakeTurnAnnotation(routingResult, routeSegments); + CHECK_EQUAL(routeSegments.size(), m_routeEdges.size(), ()); + + // 5. Turns in route order. routeSegments[i] ends at m_path[i + 1]; the loaded path + // segment that starts there gives the junction as OM saw it. + routing::NumMwmIds const numMwmIds; + auto const settings = routing::GetRoutingSettings(routing::VehicleType::Car); + for (size_t i = 0; i < routeSegments.size(); ++i) + { + auto const & item = routeSegments[i].GetTurn(); + if (item.IsTurnNone()) + continue; + size_t const pathIndex = i + 1; + if (pathIndex < 2 || pathIndex - 2 >= m_points.size()) + continue; // OM's fake start / finish points + Turn turn; + if (!ManeuverOf(item.m_turn, turn)) + continue; + RoutePoint const & p = m_points[pathIndex - 2]; + turn.route_point = p.geometry; + turn.segment = static_cast(p.osmandSegment < 0 ? 0 : p.osmandSegment); + turn.latitude = get31LatitudeY(static_cast(p.y31)); + turn.longitude = get31LongitudeX(static_cast(p.x31)); + turn.direction = routing::turns::GetTurnString(item.m_turn); + turn.exit = item.m_exitNum; + for (auto const & lane : item.m_lanes) + { + using routing::turns::lanes::LaneWay; + navicore_osmand::ui::Lane out; + out.recommended = lane.recommendedWay != LaneWay::None; + auto const ways = lane.laneWays.GetActiveLaneWays(); + // The lane's main arrow: the one the route takes, else the first. + LaneWay const main = out.recommended ? lane.recommendedWay : ways.empty() ? LaneWay::Through : ways.front(); + out.kind = LaneKind(main); + for (auto const way : ways) + if (way != main) + { + out.also = LaneKind(way); + out.combined = true; + break; + } + turn.lanes.push_back(out); + } + if (i + 1 < routeSegments.size()) + { + auto const & next = routeSegments[i + 1].GetRoadNameInfo(); + turn.road = !next.m_name.empty() ? next.m_name : next.m_ref; + } + // The junction: OM's route angle (as GetTurnDirectionBasic compares it) and its + // turn candidates. OM's angles are positive clockwise, as ours. + for (size_t k = 1; k < m_pathSegments.size(); ++k) + { + auto const & outgoing = m_pathSegments[k]; + if (outgoing.m_path.empty() || outgoing.m_path.front().GetPoint() != m_path[pathIndex].GetPoint() || + m_pathSegments[k - 1].m_segmentRange.IsEmpty() || outgoing.m_segmentRange.IsEmpty()) + continue; + routing::turns::TurnInfo const info(&m_pathSegments[k - 1], &outgoing); + double const curve = routing::turns::CalcTurnAngle(routingResult, k, numMwmIds, settings); + double const first = routing::turns::CalcOneSegmentTurnAngle(info); + turn.route_angle = (curve >= 0) == (first >= 0) ? (std::abs(curve) > std::abs(first) ? curve : first) : curve; + size_t ingoing = 0; + routing::turns::TurnCandidates candidates; + routingResult.GetPossibleTurns(m_pathSegments[k - 1].m_segmentRange, m_path[pathIndex].GetPoint(), ingoing, + candidates); + routing::Segment routeSegment; + bool const known = outgoing.m_segmentRange.GetFirstSegment(numMwmIds, routeSegment); + for (auto const & c : candidates.candidates) + if (!known || !(c.m_segment == routeSegment)) + turn.other_roads.push_back(c.m_angle); + // OM's tie-break between two almost straight roads: its own angle says "go + // straight" and CorrectRightmostAndLeftmost / CorrectGoStraight made it a slight + // turn because the route is the leftmost (rightmost) of them. That is "keep + // left/right" to a driver, not a turn (48.410077,35.086365: the road bears + // right, a ramp leaves 9 degrees further right; OM said TurnSlightLeft). + using routing::turns::CarDirection; + if (routing::turns::IntermediateDirection(turn.route_angle) == CarDirection::GoStraight) + { + if (item.m_turn == CarDirection::TurnSlightLeft) + turn.kind = ManeuverKind::KeepLeft; + else if (item.m_turn == CarDirection::TurnSlightRight) + turn.kind = ManeuverKind::KeepRight; + } + break; + } + result.turns.push_back(std::move(turn)); + } + result.ok = true; + return result; +} +} // namespace + +Result annotate(RoutingContext & context, std::vector> const & route, + double start_latitude, double start_longitude, double finish_latitude, double finish_longitude) +{ + try + { + Builder builder(context); + return builder.Run(route, start_latitude, start_longitude, finish_latitude, finish_longitude); + } + // OM's CHECK failures (shim/base/assert.hpp) by their own type: a catch of + // std::exception would put a relocation against libstdc++'s typeinfo into the + // read-only exception table, which the plugin's -z text link rejects. + catch (omaps_shim::CheckFailed const & e) + { + Result result; + result.error = e.what(); + return result; + } + catch (...) + { + Result result; + result.error = "exception in Organic Maps' turn generator"; + return result; + } +} +} // namespace navicore_osmand::omaps diff --git a/backends/osmand/omaps_turns.h b/backends/osmand/omaps_turns.h new file mode 100644 index 0000000..4e9a986 --- /dev/null +++ b/backends/osmand/omaps_turns.h @@ -0,0 +1,60 @@ +#pragma once + +// The turn instructions of an OsmAnd route, decided by Organic Maps' car turn +// generator (third_party/organicmaps-routing: CarDirectionsEngine::MakeTurnAnnotation +// and FixupCarTurns). OsmAnd's router finds the route; its segments become OM +// LoadedPathSegments (split at OM joints) and every junction gets OM turn +// candidates made from all roads the routing context has at that node. OM measures +// a turn over the curve of the road, not its first 10 m, announces a link that +// leaves the road, and skips a road that only continues. +// third_party/organicmaps-routing/README.md lists the OsmAnd -> OM mapping. + +#include "ui/navigation_model.h" + +#include +#include +#include +#include +#include + +struct RoutingContext; +struct RouteSegmentResult; + +namespace navicore_osmand::omaps { + +struct Turn { + // Index into the route's points: every segment's points from its start to its end + // point, consecutive duplicates once (the worker's RouteAlternative::geometry). + std::size_t route_point = 0; + std::size_t segment = 0; // the OsmAnd segment that leaves that point + double latitude = 0.0; + double longitude = 0.0; + std::string direction; // OM CarDirection name (TurnRight, ExitHighwayToLeft, ...) + ui::ManeuverKind kind = ui::ManeuverKind::Straight; + bool left_side = false; // UTurnRight (as OsmAnd's TRU) + bool roundabout = false; // Enter/Leave/StayOnRoundAbout + std::uint32_t exit = 0; + std::vector lanes; // left to right, from turn:lanes only + // Degrees from the incoming direction, positive clockwise: the route as OM + // compares it (the larger of the curve and the first-segment angle) and every + // other road a car may leave the junction by. + double route_angle = 0.0; + std::vector other_roads; + std::string road; // name (or ref) of the road after the turn +}; + +struct Result { + bool ok = false; + std::string error; + std::vector turns; // in route order; no start, no arrival +}; + +// |context| is the RoutingContext the route was computed with: its loaded tiles and +// car profile give the roads at each node (prepareResult loaded them). The start and +// finish are the requested points: OM's fake start/finish edges join them to the +// route like OM's own router does. Never throws: an OM check failure is an error. +Result annotate(RoutingContext& context, const std::vector>& route, + double start_latitude, double start_longitude, double finish_latitude, + double finish_longitude); + +} // namespace navicore_osmand::omaps diff --git a/backends/osmand/osmand_engine.cpp b/backends/osmand/osmand_engine.cpp index 7da001b..9971e38 100644 --- a/backends/osmand/osmand_engine.cpp +++ b/backends/osmand/osmand_engine.cpp @@ -1539,7 +1539,7 @@ bool OsmAndEngine::ensure_navigation_worker() navigation_worker_ = std::unique_ptr( new NavigationWorker(obfs_, navigation_wakeup_, navigation_maps_, navigation_routing_xml_, config_.search_index, - config_.ch_sidecar)); + config_.ch_sidecar, !config_.osmand_turns)); trace("worker=ready"); return true; } catch (...) { diff --git a/backends/osmand/route_maneuvers.cpp b/backends/osmand/route_maneuvers.cpp new file mode 100644 index 0000000..5322efc --- /dev/null +++ b/backends/osmand/route_maneuvers.cpp @@ -0,0 +1,180 @@ +#include "route_maneuvers.h" + +#include "junction_shape.h" + +#include +#include + +namespace navicore_osmand { + +ui::ManeuverKind maneuver_kind(int value) +{ + switch (value) { + case TurnType::TL: return ui::ManeuverKind::Left; + case TurnType::TSLL: return ui::ManeuverKind::SlightLeft; + case TurnType::TSHL: return ui::ManeuverKind::SharpLeft; + case TurnType::TR: return ui::ManeuverKind::Right; + case TurnType::TSLR: return ui::ManeuverKind::SlightRight; + case TurnType::TSHR: return ui::ManeuverKind::SharpRight; + case TurnType::KL: return ui::ManeuverKind::KeepLeft; + case TurnType::KR: return ui::ManeuverKind::KeepRight; + case TurnType::TU: + case TurnType::TRU: return ui::ManeuverKind::UTurn; + case TurnType::RNDB: + case TurnType::RNLB: return ui::ManeuverKind::Roundabout; + default: return ui::ManeuverKind::Straight; + } +} + +// OsmAnd lane value: bit 0 = the route uses the lane, bits 1-4 its main +// turn, bits 5-9 a second turn (TurnType::getPrimaryTurn/getSecondaryTurn). +std::vector lanes_of(const SHARED_PTR& turn) +{ + std::vector lanes; + if (!turn) + return lanes; + for (const int value : turn->getLanes()) { + ui::Lane lane; + const int primary = TurnType::getPrimaryTurn(value); + const int secondary = TurnType::getSecondaryTurn(value); + lane.kind = maneuver_kind(primary ? primary : TurnType::C); + lane.combined = secondary != 0; + if (lane.combined) + lane.also = maneuver_kind(secondary); + lane.recommended = (value & 1) != 0; + lanes.push_back(lane); + } + return lanes; +} + +// Bearings over the first 10 m of each road, as OsmAnd's own turn decision +// (getTurnInfo, DIST_BEARING_DETECT). +constexpr float kJunctionBearingMetres = 10.0f; + +// The junction at the start of segments[index] (where OsmAnd puts the +// turn): the route's and every other road's direction, relative to the +// incoming direction (positive clockwise). Other roads: the segment's +// attached roads at its start point (prepareResult / +// attachRoadSegments: the incoming road's continuation and each road the +// router could leave the node by; one-way roads that only enter the node +// are not attached), plus the route's own road behind the node, which +// OsmAnd does not attach (same way id). +ui::JunctionShape junction_of(Segments& segments, std::size_t index) +{ + if (index == 0 || index >= segments.size()) return {}; + const auto& previous = segments[index - 1]; + const auto& current = segments[index]; + if (!previous || !current || !previous->object || !current->object) return {}; + const double incoming = + previous->getBearingEnd(previous->getEndPointIndex(), kJunctionBearingMetres); + const int start = current->getStartPointIndex(); + const double route = current->getBearingBegin(start, kJunctionBearingMetres); + std::vector arms; + for (const auto& attached : current->getAttachedRoutes(start)) { + if (!attached || !attached->object) continue; + arms.push_back(degreesDiff(attached->getBearingBegin(), incoming)); + } + const bool forward = current->getEndPointIndex() > start; + const int points = static_cast(current->object->getPointsLength()); + if (current->object->getId() != previous->object->getId() && + (forward ? start > 0 : start < points - 1)) { + const double behind = + current->object->directionRoute(start, !forward, kJunctionBearingMetres) / M_PI * + 180.0; + arms.push_back(degreesDiff(behind, incoming)); + } + return make_junction_shape(degreesDiff(route, incoming), arms); +} + +bool maneuver_at(Segments& segments, std::size_t index, ui::Maneuver& maneuver) +{ + const auto& segment = segments[index]; + if (!segment || !segment->turnType || segment->turnType->getValue() == TurnType::C) + return false; + maneuver.kind = maneuver_kind(segment->turnType->getValue()); + maneuver.roundabout_exit = segment->turnType->getExitOut(); + maneuver.lanes = lanes_of(segment->turnType); + maneuver.left_side = segment->turnType->isLeftSide(); + maneuver.turn_angle_degrees = segment->turnType->getTurnAngle(); + if (!segment->turnType->isRoundAbout()) { + maneuver.junction = junction_of(segments, index); + summarize_lanes(maneuver.lanes, maneuver.junction); + } + return true; +} + +std::vector segment_start_points(const Segments& segments) +{ + std::vector starts(segments.size(), 0); + std::size_t points = 0; + int last_x = 0, last_y = 0; + for (std::size_t s = 0; s < segments.size(); ++s) { + const auto& segment = segments[s]; + if (!segment || !segment->object) { + starts[s] = points ? points - 1 : 0; + continue; + } + const int start = segment->getStartPointIndex(); + const int end = segment->getEndPointIndex(); + const int step = start <= end ? 1 : -1; + for (int i = start;; i += step) { + const int x = static_cast(segment->object->pointsX[i]); + const int y = static_cast(segment->object->pointsY[i]); + const bool same = points > 0 && x == last_x && y == last_y; + if (i == start) starts[s] = same ? points - 1 : points; + if (!same) { + ++points; + last_x = x; + last_y = y; + } + if (i == end) break; + } + } + return starts; +} + +ui::Maneuver maneuver_from(const omaps::Turn& turn) +{ + ui::Maneuver maneuver; + maneuver.kind = turn.kind; + maneuver.road = turn.road; + maneuver.lanes = turn.lanes; + maneuver.left_side = turn.left_side; + maneuver.turn_angle_degrees = turn.route_angle; + if (turn.kind != ui::ManeuverKind::Roundabout) { + maneuver.junction = make_junction_shape(turn.route_angle, turn.other_roads); + summarize_lanes(maneuver.lanes, maneuver.junction); + } + return maneuver; +} + +std::vector route_maneuvers(Segments& segments, const omaps::Result* turns) +{ + const std::vector starts = segment_start_points(segments); + std::vector placed; + if (turns && !turns->ok) return placed; // no silent fallback to OsmAnd's turns + const bool organic = turns != nullptr; + for (std::size_t i = 0; i < segments.size(); ++i) { + PlacedManeuver p; + if (!maneuver_at(segments, i, p.maneuver)) continue; + if (organic && p.maneuver.kind != ui::ManeuverKind::Roundabout) continue; + p.segment = i; + p.route_point = starts[i]; + placed.push_back(std::move(p)); + } + if (!organic) return placed; + for (const auto& turn : turns->turns) { + if (turn.roundabout) continue; // OsmAnd's roundabout, above + PlacedManeuver p; + p.segment = turn.segment; + p.route_point = turn.route_point; + p.maneuver = maneuver_from(turn); + placed.push_back(std::move(p)); + } + std::stable_sort(placed.begin(), placed.end(), [](const PlacedManeuver& a, const PlacedManeuver& b) { + return a.route_point < b.route_point; + }); + return placed; +} + +} // namespace navicore_osmand diff --git a/backends/osmand/route_maneuvers.h b/backends/osmand/route_maneuvers.h new file mode 100644 index 0000000..867c656 --- /dev/null +++ b/backends/osmand/route_maneuvers.h @@ -0,0 +1,56 @@ +#pragma once + +#include "omaps_turns.h" +#include "ui/navigation_model.h" + +#include +#include +#include + +// Core and core-legacy both ship a Logging.h with the same public names but +// different include guards. The provider uses Core's logger consistently. +#include +#define _OSMAND_LOGGING_H_ +#include "routeSegmentResult.h" +#include "turnType.h" + +namespace navicore_osmand { + +// The manoeuvres of an OsmAnd route, as the navigation worker publishes +// them (and tools/junction_lab shows them on the host): turn kind, lanes and +// the junction shape the cluster picture is chosen from. +using Segments = std::vector>; + +ui::ManeuverKind maneuver_kind(int turn_type); +std::vector lanes_of(const SHARED_PTR& turn); +ui::JunctionShape junction_of(Segments& segments, std::size_t index); + +// The manoeuvre at the start of segments[index], or false when the segment +// carries none (no turn type, or OsmAnd's "continue"). Fills everything but +// the road name and the route position, which the caller knows. +bool maneuver_at(Segments& segments, std::size_t index, ui::Maneuver& maneuver); + +// A manoeuvre and where it is: the OsmAnd segment that leaves it and its index in +// the route's points (every segment's points, consecutive duplicates once: the +// worker's RouteAlternative::geometry). +struct PlacedManeuver { + std::size_t segment = 0; + std::size_t route_point = 0; + ui::Maneuver maneuver; +}; + +// The index of each segment's start point among the route's points. +std::vector segment_start_points(const Segments& segments); + +// The manoeuvre for one of Organic Maps' turns: its kind and lanes, and the junction +// shape from OM's route angle and other roads (the cluster picture). +ui::Maneuver maneuver_from(const omaps::Turn& turn); + +// The route's manoeuvres in route order, without the arrival: Organic Maps' turns +// with OsmAnd's roundabouts (OsmAnd gives the exit and its angle). |turns| null: +// Organic Maps is switched off, OsmAnd's own (maneuver_at). An OM result that +// failed gives none: no silent fallback, the route visibly has no turns (the +// worker traces the error). +std::vector route_maneuvers(Segments& segments, const omaps::Result* turns); + +} // namespace navicore_osmand diff --git a/deploy/navigation-ifs/deploy_backend.sh b/deploy/navigation-ifs/deploy_backend.sh new file mode 100755 index 0000000..6226342 --- /dev/null +++ b/deploy/navigation-ifs/deploy_backend.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# deploy_backend.sh LIBRARY [--dry-run] +# +# Installs the OsmAnd backend (build/qnx/navicore-data/navicore/libOpenNaviBackendOsmAnd.so) +# in the booted slot's data dir on the bench radio, where the slot image's +# 50-navicore.pre links it into /open-navicore at boot. The slot's 50-navicore.ifs +# (provider, its config) and the OsmAnd core stay as they are. +# +# 1. scp LIBRARY to /libOpenNaviBackendOsmAnd.so.new and check its sha256 on +# the unit +# 2. bench_rename the current one to libOpenNaviBackendOsmAnd.before-.so (kept: +# the rollback), then .new to libOpenNaviBackendOsmAnd.so; vp4r-sync +# 3. read back the active file's sha256 +# Activate with one vp4r-reboot afterwards (not done here). +# +# Environment: RADIO_HOST (192.168.2.8), RADIO_SSH_KEY ($HOME/priv_openssh), VP4R_HOME +# (/datastore/vp4r); dev-tools on the unit (/usr/bin/sha256sum, bench_rename, vp4r-sync). +set -euo pipefail + +LIBRARY=${1:?usage: deploy_backend.sh LIBRARY [--dry-run]} +DRY=${2:-} +HOST=${RADIO_HOST:-192.168.2.8} +KEY=${RADIO_SSH_KEY:-$HOME/priv_openssh} +HOME_DIR=${VP4R_HOME:-/datastore/vp4r} +NAME=libOpenNaviBackendOsmAnd.so +OPTS=(-oBatchMode=yes -oLogLevel=ERROR -oConnectTimeout=10 -oIdentitiesOnly=yes + -oHostKeyAlgorithms=+ssh-dss -oPubkeyAcceptedAlgorithms=+ssh-rsa -i "$KEY") +[ -f "$LIBRARY" ] || { echo "no library: $LIBRARY" >&2; exit 2; } +WANT=$(sha256sum "$LIBRARY" | cut -d' ' -f1) +STAMP=$(date +%Y%m%d-%H%M%S) +radio() { ssh "${OPTS[@]}" "root@$HOST" "$@" 2>&1 | grep -v '^welcome to uconnect' || true; } + +SLOT=$(radio "read S < $HOME_DIR/slot; echo \$S" | tr -d '\r') +[ -n "$SLOT" ] || { echo "cannot read the booted slot ($HOME_DIR/slot)" >&2; exit 1; } +D=$HOME_DIR/slots/$SLOT/data/navicore +BACKUP=$D/libOpenNaviBackendOsmAnd.before-$STAMP.so +echo "slot $SLOT, data dir $D" +echo "new: $NAME sha256 $WANT" +radio "/usr/bin/sha256sum $D/$NAME" | sed 's/^/current: /' +if [ "$DRY" = "--dry-run" ]; then + echo "[dry-run] scp $LIBRARY -> $D/$NAME.new; check sha256" + echo "[dry-run] bench_rename $D/$NAME $BACKUP" + echo "[dry-run] bench_rename $D/$NAME.new $D/$NAME; vp4r-sync; read back" + exit 0 +fi + +scp -O -p "${OPTS[@]}" "$LIBRARY" "root@$HOST:$D/$NAME.new" +GOT=$(radio "/usr/bin/sha256sum $D/$NAME.new" | cut -d' ' -f1) +[ "$GOT" = "$WANT" ] || { echo "uploaded copy does not match ($GOT); $D/$NAME untouched" >&2; exit 1; } +radio "/usr/bin/bench_rename $D/$NAME $BACKUP && /usr/bin/bench_rename $D/$NAME.new $D/$NAME && /usr/bin/vp4r-sync" +ACTIVE=$(radio "/usr/bin/sha256sum $D/$NAME" | cut -d' ' -f1) +if [ "$ACTIVE" = "$WANT" ]; then + echo "installed; previous kept as $BACKUP" + echo "activate: one /usr/bin/vp4r-reboot" +else + echo "active file sha256 $ACTIVE does not match: check $D by hand" >&2 + exit 1 +fi diff --git a/third_party/organicmaps-routing/LICENSE b/third_party/organicmaps-routing/LICENSE new file mode 100644 index 0000000..137069b --- /dev/null +++ b/third_party/organicmaps-routing/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/organicmaps-routing/README.md b/third_party/organicmaps-routing/README.md new file mode 100644 index 0000000..c7ce0bf --- /dev/null +++ b/third_party/organicmaps-routing/README.md @@ -0,0 +1,87 @@ +# Organic Maps car turn generator (vendored for the junction lab) + +Source: https://github.com/organicmaps/organicmaps, commit +`303ef27fbc99d238965d7ced471c8920944110e6` (2026-10-27), `libs/routing`. +License: Apache-2.0 (`LICENSE`, from the upstream `LICENSES/Apache-2.0.txt`; +the upstream files carry no per-file headers). + +`../omaps_adapter.cpp` builds OM's `IRoutingResult` from an OsmAnd route and runs +`CarDirectionsEngine::MakeTurnAnnotation` → `GetTurnDirection` → `FixupCarTurns` +→ `SelectRecommendedLanes`. Output: the `"omaps"` array of `junction_lab_tool`. +Debug: `JUNCTION_LAB_OMAPS_DEBUG=1` dumps OM's loaded segments, candidates and +turn angles to stderr; `JUNCTION_LAB_OMAPS_LOG=1` prints OM's LOG(LWARNING) sites. + +The code is C++17 (no C++20 features), so it can later build with QNX GCC 8.5. + +## Files + +Unchanged turn/lane logic: `routing/car_directions.*`, `turns.*`, +`turns_generator.*`, `turns_generator_utils.*`, `turn_candidate.hpp`, +`routing_result_graph.hpp`, `loaded_path_segment.hpp`, +`lanes/lane_info.*`, `lanes/lanes_recommendation.*`. + +Edited (no behavioural change intended): + +- `lanes/lane_way.hpp/.cpp`: `constexpr` dropped from `LaneWays` members that use + `std::bitset` operations (constexpr only in C++23); `using enum` replaced by + qualified names. +- `lanes/lanes_parser.cpp`: `std::views::split`/`filter`/`transform` replaced by a + C++17 splitter with the same semantics (every delimiter ends a part, trailing + empty part kept; ASCII spaces removed, ASCII lower-casing). +- `routing_settings.cpp`: C++20 designated initializers replaced by a helper with + the same values; include of `routing_helpers.hpp` replaced by the + `measurement_utils` shim. +- `directions_engine.hpp/.cpp`: trimmed to the interface plus `MakeTurnAnnotation` + (loop unchanged). It is public and takes the `IRoutingResult` directly; the + feature-reading parts (`Generate`, `FillPathSegmentsAndAdjacentEdgesMap`, + `GetSegmentRangeAndAdjacentEdges`, `LoadPathAttributes`) are re-implemented on + OsmAnd data in `../omaps_adapter.cpp` with the same control flow. + +Behavioural fixes (the only changes to OM's decisions; candidates to report upstream): + +- `car_directions.cpp` `CheckUTurnOnRoute`: a wide U-turn found `i` segments ahead + returned `i + 1` turns to skip, which also dropped the first turn after the U-turn + (48.487081,34.941727 → 48.489282,34.937865: the exit right onto the link at + 48.488918,34.938895). Returns `i` now: only the turns inside the U-turn. + +Shims (`shim/`): `base/assert.hpp` (ASSERT compiled out as in OM release builds; +CHECK throws instead of aborting), `base/logging.hpp`, `base/math.hpp`, +`base/stl_helpers.hpp`, `base/string_utils.hpp`, `base/internal/message.hpp`, +`geometry/*` (point, mercator, distance, angles: upstream formulas), +`indexer/feature_decl.hpp` (FeatureID = dense OsmAnd road number), +`indexer/ftypes_matcher.hpp` (HighwayClass enum only), `platform/*`, +`routing_common/num_mwm_id.hpp` (one mwm), `routing/segment.hpp` and +`routing/route.hpp` (trimmed `Segment`/`RouteSegment`; kept members copied +unchanged), `routing/vehicle_mask.hpp`. + +## OsmAnd → OM mapping (backends/osmand/omaps_turns.cpp) + +- Path points: OsmAnd 31-bit points → lat/lon → OM mercator. Layout as OM's router: + fake start loop, jump from the requested start, the route, jump to the requested + finish, fake finish loop. Route edges use the map road's point numbering (OsmAnd + routes on road copies with an inserted precise point; matched by coordinates). +- Loaded segments are split at OM joints (`IsJoint`, same logic). +- Edges at a node: every road `loadRouteSegment(x31, y31)` returns; direction per + the car profile's `isOneWay`; U-turn onto the same segment only at a joint or a + road end (`IndexGraph::IsUTurnAndRestricted`); OsmAnd turn restrictions without a + via way (no_* to the road; only_* whose target is at the node). Ingoing count = + edges that can enter the route's outgoing segment, including the reversed + outgoing one, as in OM. +- Highway class: OM's table on the OsmAnd `highway` tag; `service` + + `service=driveway|parking_aisle` → ServiceMinor (Service if OsmAnd's map has no + `service` tag); `route=ferry|shuttle_train` → Transported. Link = `*_link` of + motorway..tertiary. Roundabout = OsmAnd `roundabout()`. One-way = car profile. +- Lanes: `turn:lanes` (one-way) or `turn:lanes:forward/backward`, falling back to + `turn:lanes` (OM's fallback). Name/ref: OsmAnd default `name`/`ref`; + destination, destination:ref, junction:ref from OsmAnd's tags (display only). +- Not fed (defaults): OM's access-conditional / road-access checks (OsmAnd's car + profile already filtered the roads), via-way restrictions, altitudes (0), + mwm-border twin filtering (one map set, not needed). +- OSM data OM's maps do not have, handled before OM sees the junction: + - Overlapping ways (different ways on the same nodes, 48.516022,34.999655): at a + node one edge per next point, the route's own when it is among them. OsmAnd + does the same for the route's own road only (`attachSegments`, "if way + contains same segment (nodes) as different way (do not attach it)"). + - Route points closer than 2 m to the previous one are one junction (a 0.3 m stub + between two junction nodes there): the roads of both nodes, without the stub. + A turn keeps the index of the junction's first point in the route geometry. diff --git a/third_party/organicmaps-routing/routing/car_directions.cpp b/third_party/organicmaps-routing/routing/car_directions.cpp new file mode 100644 index 0000000..7c0b717 --- /dev/null +++ b/third_party/organicmaps-routing/routing/car_directions.cpp @@ -0,0 +1,639 @@ +#include "routing/car_directions.hpp" + +#include "routing/lanes/lanes_recommendation.hpp" +#include "routing/turns.hpp" +#include "routing/turns_generator.hpp" +#include "routing/turns_generator_utils.hpp" + +#include "geometry/angles.hpp" +#include "geometry/mercator.hpp" + +namespace routing +{ +using namespace turns; +using namespace ftypes; + +CarDirectionsEngine::CarDirectionsEngine(MwmDataSource & dataSource, std::shared_ptr numMwmIds) + : DirectionsEngine(dataSource, std::move(numMwmIds)) +{} + +void CarDirectionsEngine::FixupTurns(std::vector & routeSegments) +{ + FixupCarTurns(routeSegments); +} + +void FixupCarTurns(std::vector & routeSegments) +{ + double constexpr kMergeStayOnRoadAndTurnDistM = 15.0; + double constexpr kMergeSegregatedTurnsDistM = 20.0; + + // For turns that are not EnterRoundAbout/ExitRoundAbout exitNum is always equal to zero. + // If a turn is EnterRoundAbout exitNum is a number of turns between two junctions: + // (1) the route enters to the roundabout; + // (2) the route leaves the roundabout; + uint32_t exitNum = 0; + size_t const kInvalidEnter = std::numeric_limits::max(); + size_t enterRoundAbout = kInvalidEnter; + + auto const getDistance = [&routeSegments](size_t idx) + { + // Keep 'dist' var to debug thresholds above. + double const dist = mercator::DistanceOnEarth(routeSegments[idx - 1].GetJunction().GetPoint(), + routeSegments[idx].GetJunction().GetPoint()); + return dist; + }; + + for (size_t idx = 0; idx < routeSegments.size(); ++idx) + { + auto & t = routeSegments[idx].GetTurn(); + if (t.IsTurnNone()) + continue; + + if (enterRoundAbout != kInvalidEnter && t.m_turn != CarDirection::StayOnRoundAbout && + t.m_turn != CarDirection::LeaveRoundAbout && t.m_turn != CarDirection::ReachedYourDestination) + { + ASSERT(false, + ("Only StayOnRoundAbout, LeaveRoundAbout or ReachedYourDestination are expected after EnterRoundAbout.")); + exitNum = 0; + enterRoundAbout = kInvalidEnter; + } + else if (t.m_turn == CarDirection::EnterRoundAbout) + { + ASSERT(enterRoundAbout == kInvalidEnter, + ("It's not expected to find new EnterRoundAbout until previous EnterRoundAbout was leaved.")); + enterRoundAbout = idx; + ASSERT(exitNum == 0, ("exitNum is reset at start and after LeaveRoundAbout.")); + exitNum = t.m_exitNum; // Normally it is 0, but sometimes it can be 1. + } + else if (t.m_turn == CarDirection::StayOnRoundAbout) + { + ++exitNum; + routeSegments[idx].ClearTurn(); + continue; + } + else if (t.m_turn == CarDirection::LeaveRoundAbout) + { + // It's possible for car to be on roundabout without entering it + // if route calculation started at roundabout (e.g. if user made full turn on roundabout). + if (enterRoundAbout != kInvalidEnter) + routeSegments[enterRoundAbout].SetTurnExits(exitNum + 1); + routeSegments[idx].SetTurnExits(exitNum + 1); // For LeaveRoundAbout turn. + enterRoundAbout = kInvalidEnter; + exitNum = 0; + } + + // Merging turns which are closed to each other under some circumstance. + if (idx > 0 && IsLeftOrRightTurn(t.m_turn)) + { + auto const prevTurn = routeSegments[idx - 1].GetTurn().m_turn; + + bool removeTurn = false; + if (IsStayOnRoad(prevTurn)) + removeTurn = getDistance(idx) < kMergeStayOnRoadAndTurnDistM; + else if (IsLeftOrRightTurn(prevTurn)) + { + if (routeSegments[idx].IsSegregatedTurn(routeSegments[idx - 1])) + removeTurn = getDistance(idx) < kMergeSegregatedTurnsDistM; + } + + if (removeTurn) + { + routeSegments[idx].MergeLanes(routeSegments[idx - 1]); + routeSegments[idx - 1].ClearTurn(); + } + } + } + turns::lanes::SelectRecommendedLanes(routeSegments); +} + +void GetTurnDirectionBasic(IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, TurnItem & turn); + +size_t CarDirectionsEngine::GetTurnDirection(IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, + TurnItem & turnItem) +{ + if (outgoingSegmentIndex == result.GetSegments().size()) + { + turnItem.m_turn = CarDirection::ReachedYourDestination; + return 0; + } + + // This is for jump from initial point to start of the route. No direction is given. + /// @todo Sometimes results of GetPossibleTurns are empty, sometimes are invalid. + /// The best will be to fix GetPossibleTurns(). It will allow us to use following approach. + /// E.g. Google Maps until you reach the destination will guide you to go to the left or to the right of the first + /// road. + if (outgoingSegmentIndex == 2) // The same as turnItem.m_index == 2. + return 0; + + size_t skipTurnSegments = CheckUTurnOnRoute(result, outgoingSegmentIndex, numMwmIds, vehicleSettings, turnItem); + + if (turnItem.m_turn == CarDirection::None) + GetTurnDirectionBasic(result, outgoingSegmentIndex, numMwmIds, vehicleSettings, turnItem); + + // Lane information. + if (turnItem.m_turn != CarDirection::None) + { + auto const & loadedSegments = result.GetSegments(); + auto const & ingoingSegment = loadedSegments[outgoingSegmentIndex - 1]; + turnItem.m_lanes = ingoingSegment.m_lanes; + + // A lane may fork off just before a turn, leaving a short ingoing segment with fewer lanes. + // Guidance can appear before the fork, so use the earlier layout when it contains the current lanes. + double constexpr kShortLanesSegmentDistM = 30.0; + if (outgoingSegmentIndex >= 2 && !turnItem.m_lanes.empty() && + CalcRouteDistanceM(ingoingSegment.m_path, 0, static_cast(ingoingSegment.m_path.size())) < + kShortLanesSegmentDistM) + { + auto const & prevLanes = loadedSegments[outgoingSegmentIndex - 2].m_lanes; + if (prevLanes.size() > turnItem.m_lanes.size() && + std::search(prevLanes.begin(), prevLanes.end(), turnItem.m_lanes.begin(), turnItem.m_lanes.end()) != + prevLanes.end()) + { + turnItem.m_lanes = prevLanes; + } + } + } + + return skipTurnSegments; +} + +/*! + * \brief Calculates a turn instruction if the ingoing edge or (and) the outgoing edge belongs to a + * roundabout. + * \return Returns one of the following results: + * - TurnDirection::EnterRoundAbout if the ingoing edge does not belong to a roundabout + * and the outgoing edge belongs to a roundabout. + * - TurnDirection::StayOnRoundAbout if the ingoing edge and the outgoing edge belong to a + * roundabout + * and there is a reasonalbe way to leave the junction besides the outgoing edge. + * This function does not return TurnDirection::StayOnRoundAbout for small ways to leave the + * roundabout. + * - TurnDirection::NoTurn if the ingoing edge and the outgoing edge belong to a roundabout + * (a) and there is a single way (outgoing edge) to leave the junction. + * (b) and there is a way(s) besides outgoing edge to leave the junction (the roundabout) + * but it is (they are) relevantly small. + */ +CarDirection GetRoundaboutDirectionBasic(bool isIngoingEdgeRoundabout, bool isOutgoingEdgeRoundabout, + bool isMultiTurnJunction, bool keepTurnByHighwayClass) +{ + if (isIngoingEdgeRoundabout && isOutgoingEdgeRoundabout) + { + if (isMultiTurnJunction) + return keepTurnByHighwayClass ? CarDirection::StayOnRoundAbout : CarDirection::None; + return CarDirection::None; + } + + if (!isIngoingEdgeRoundabout && isOutgoingEdgeRoundabout) + return CarDirection::EnterRoundAbout; + + if (isIngoingEdgeRoundabout && !isOutgoingEdgeRoundabout) + return CarDirection::LeaveRoundAbout; + + ASSERT(false, ()); + return CarDirection::None; +} + +/*! + * \brief Returns false when other possible turns leads to service roads; + */ +bool KeepRoundaboutTurnByHighwayClass(TurnCandidates const & possibleTurns, TurnInfo const & turnInfo, + NumMwmIds const & numMwmIds) +{ + Segment firstOutgoingSegment; + turnInfo.m_outgoing->m_segmentRange.GetFirstSegment(numMwmIds, firstOutgoingSegment); + + for (auto const & t : possibleTurns.candidates) + { + if (t.m_segment == firstOutgoingSegment) + continue; + // For roundabouts of Tertiary and less significant class count every road. + // For more significant roundabouts - ignore service roads (driveway, parking_aisle). + if (turnInfo.m_outgoing->m_highwayClass >= HighwayClass::Tertiary || t.m_highwayClass != HighwayClass::ServiceMinor) + return true; + } + return false; +} + +CarDirection GetRoundaboutDirection(TurnInfo const & turnInfo, TurnCandidates const & nodes, + NumMwmIds const & numMwmIds) +{ + bool const keepTurnByHighwayClass = KeepRoundaboutTurnByHighwayClass(nodes, turnInfo, numMwmIds); + return GetRoundaboutDirectionBasic(turnInfo.m_ingoing->m_onRoundabout, turnInfo.m_outgoing->m_onRoundabout, + nodes.candidates.size() > 1, keepTurnByHighwayClass); +} + +/// \brief Return |CarDirection::ExitHighwayToRight| or |CarDirection::ExitHighwayToLeft| +/// or return |CarDirection::None| if no exit is detected. +/// \note The function makes a decision about turn based on geometry of the route and turn +/// candidates, so it works correctly for both left and right hand traffic. +CarDirection TryToGetExitDirection(TurnCandidates const & possibleTurns, TurnInfo const & turnInfo, + Segment const & firstOutgoingSeg, CarDirection const intermediateDirection) +{ + if (!possibleTurns.isCandidatesAngleValid) + return CarDirection::None; + + if (!IsHighway(turnInfo.m_ingoing->m_highwayClass, turnInfo.m_ingoing->m_isLink)) + return CarDirection::None; + + if (!turnInfo.m_outgoing->m_isLink && + !(IsSmallRoad(turnInfo.m_outgoing->m_highwayClass) && IsGoStraightOrSlightTurn(intermediateDirection))) + return CarDirection::None; + + // At this point it is known that the route goes form a highway to a link road or to a small road + // which has a slight angle with the highway. + + // Considering cases when the route goes from a highway to a link or a small road. + // Checking all turn candidates (sorted by their angles) and looking for the road which is a + // continuation of the ingoing segment. If the continuation is on the right hand of the route + // it's an exit to the left. If the continuation is on the left hand of the route + // it's an exit to the right. + // Note. The angle which is used for sorting turn candidates in |possibleTurns.candidates| + // is a counterclockwise angle between the ingoing route edge and corresponding candidate. + // For left turns the angle is less than zero and for right ones it is more than zero. + bool isCandidateBeforeOutgoing = true; + bool isHighwayCandidateBeforeOutgoing = true; + size_t highwayCandidateNumber = 0; + + for (auto const & c : possibleTurns.candidates) + { + if (c.m_segment == firstOutgoingSeg) + { + isCandidateBeforeOutgoing = false; + continue; + } + + if (IsHighway(c.m_highwayClass, c.m_isLink)) + { + ++highwayCandidateNumber; + if (highwayCandidateNumber >= 2) + return CarDirection::None; // There are two or more highway candidates from the junction. + isHighwayCandidateBeforeOutgoing = isCandidateBeforeOutgoing; + } + } + if (highwayCandidateNumber == 1) + return isHighwayCandidateBeforeOutgoing ? CarDirection::ExitHighwayToRight : CarDirection::ExitHighwayToLeft; + return CarDirection::None; +} + +// Min difference of route and alternative turn abs angles in degrees +// to ignore alternative turn (when route direction is GoStraight). +double constexpr kMinAbsAngleDiffForStraightRoute = 25.0; + +// Min difference of route and alternative turn abs angles in degrees +// to ignore alternative turn (when route direction is bigger and GoStraight). +double constexpr kMinAbsAngleDiffForBigStraightRoute = 5; + +// Min difference of route and alternative turn abs angles in degrees +// to ignore this alternative candidate (when alternative road is the same or smaller). +double constexpr kMinAbsAngleDiffForSameOrSmallerRoad = 35.0; + +/// * \returns true when +/// * - the route leads from one big road to another one; +/// * - and the other possible turns lead to small roads or these turns too sharp. +/// * Returns false otherwise. +/// \param routeDirection is route direction. +/// \param routeAngle is route angle. +/// \param turnCandidates is all possible ways out from a junction except uturn. +/// \param turnInfo is information about ingoing and outgoing segments of the route. +bool CanDiscardTurnByHighwayClassOrAngles(CarDirection const routeDirection, double const routeAngle, + std::vector const & turnCandidates, TurnInfo const & turnInfo, + NumMwmIds const & numMwmIds) +{ + if (!IsGoStraightOrSlightTurn(routeDirection)) + return false; + + if (turnCandidates.size() < 2) + return true; + + HighwayClass outgoingRouteRoadClass = turnInfo.m_outgoing->m_highwayClass; + HighwayClass ingoingRouteRoadClass = turnInfo.m_ingoing->m_highwayClass; + + Segment firstOutgoingSegment; + turnInfo.m_outgoing->m_segmentRange.GetFirstSegment(numMwmIds, firstOutgoingSegment); + + for (auto const & t : turnCandidates) + { + // Let's consider all outgoing segments except for route outgoing segment. + if (t.m_segment == firstOutgoingSegment) + continue; + + // Min difference of route and alternative turn abs angles in degrees + // to ignore this alternative candidate (when route goes from non-link to link). + double constexpr kMinAbsAngleDiffForGoLink = 70.0; + + // If route goes from non-link to link and there is not too sharp candidate then turn can't be discarded. + if (!turnInfo.m_ingoing->m_isLink && turnInfo.m_outgoing->m_isLink && + std::abs(t.m_angle) < std::abs(routeAngle) + kMinAbsAngleDiffForGoLink) + return false; + + HighwayClass candidateRoadClass = t.m_highwayClass; + + // If outgoing route road is significantly larger than candidate, the candidate can be ignored. + if (CalcDiffRoadClasses(outgoingRouteRoadClass, candidateRoadClass) <= kMinHighwayClassDiff) + continue; + + // If outgoing route's road is significantly larger than candidate's service road, the candidate can be ignored. + if (CalcDiffRoadClasses(outgoingRouteRoadClass, candidateRoadClass) <= kMinHighwayClassDiffForService && + (candidateRoadClass == HighwayClass::Service || candidateRoadClass == HighwayClass::ServiceMinor)) + continue; + + // If igngoing and outgoing edges are not links + // and outgoing route road is the same or large than ingoing + // then candidate-link can be ignored. + if (!turnInfo.m_ingoing->m_isLink && !turnInfo.m_outgoing->m_isLink && + CalcDiffRoadClasses(outgoingRouteRoadClass, ingoingRouteRoadClass) <= 0 && t.m_isLink) + continue; + + // If alternative cadidate's road size is the same or smaller + // and it's angle is sharp enough compared to the route it can be ignored. + if (CalcDiffRoadClasses(outgoingRouteRoadClass, candidateRoadClass) <= 0 && + std::abs(t.m_angle) > std::abs(routeAngle) + kMinAbsAngleDiffForSameOrSmallerRoad) + continue; + + if (routeDirection == CarDirection::GoStraight) + { + // If alternative cadidate's road size is smaller + // and it's angle is not very close to the route's one - it can be ignored. + if (CalcDiffRoadClasses(outgoingRouteRoadClass, candidateRoadClass) < 0 && + std::abs(t.m_angle) > std::abs(routeAngle) + kMinAbsAngleDiffForBigStraightRoute) + continue; + + // If outgoing route road is the same or large than ingoing + // and candidate's angle is sharp enough compared to the route it can be ignored. + if (CalcDiffRoadClasses(outgoingRouteRoadClass, ingoingRouteRoadClass) <= 0 && + std::abs(t.m_angle) > std::abs(routeAngle) + kMinAbsAngleDiffForStraightRoute) + continue; + } + + return false; + } + return true; +} + +/*! + * \brief Corrects |turn.m_turn| if |turn.m_turn == CarDirection::GoStraight|. + * If the other way is not sharp enough, turn.m_turn is set to |turnToSet|. + */ +void CorrectGoStraight(TurnCandidate const & notRouteCandidate, double const routeAngle, CarDirection const & turnToSet, + TurnItem & turn) +{ + if (turn.m_turn != CarDirection::GoStraight) + return; + + // Correct turn if alternative cadidate's angle is not sharp enough compared to the route. + if (std::abs(notRouteCandidate.m_angle) < std::abs(routeAngle) + kMinAbsAngleDiffForStraightRoute) + { + LOG(LDEBUG, ("Turn: ", turn.m_index, " GoStraight correction.")); + turn.m_turn = turnToSet; + } +} + +// If the route goes along the rightmost or the leftmost way among available ones: +// 1. RightmostDirection or LeftmostDirection is selected +// 2. If the turn direction is |CarDirection::GoStraight| +// and there's another not sharp enough turn +// GoStraight is corrected to TurnSlightRight/TurnSlightLeft +// to avoid ambiguity for GoStraight direction: 2 or more almost straight turns. +void CorrectRightmostAndLeftmost(std::vector const & turnCandidates, Segment const & firstOutgoingSeg, + double const turnAngle, TurnItem & turn) +{ + // turnCandidates are sorted by angle from leftmost to rightmost. + // Normally no duplicates should be found. But if they are present we can't identify the leftmost/rightmost by order. + if (adjacent_find(turnCandidates.begin(), turnCandidates.end(), base::EqualsBy(&TurnCandidate::m_angle)) != + turnCandidates.end()) + { + LOG(LWARNING, ("nodes.candidates are not expected to have same m_angle.")); + return; + } + + double constexpr kMaxAbsAngleConsideredLeftOrRightMost = 90; + + // Go from left to right to findout if the route goes through the leftmost candidate and fixes can be applied. + // Other candidates which are sharper than kMaxAbsAngleConsideredLeftOrRightMost are ignored. + for (auto candidate = turnCandidates.begin(); candidate != turnCandidates.end(); ++candidate) + { + if (candidate->m_segment == firstOutgoingSeg && candidate + 1 != turnCandidates.end()) + { + // The route goes along the leftmost candidate. + turn.m_turn = LeftmostDirection(turnAngle); + if (IntermediateDirection(turnAngle) != turn.m_turn) + LOG(LDEBUG, ("Turn: ", turn.m_index, " LeftmostDirection correction.")); + // Compare with the next candidate to the right. + CorrectGoStraight(*(candidate + 1), candidate->m_angle, CarDirection::TurnSlightLeft, turn); + break; + } + // Check if this candidate is considered as leftmost as not too sharp. + // If yes - this candidate is leftmost, not route's one. + if (candidate->m_angle > -kMaxAbsAngleConsideredLeftOrRightMost) + break; + } + // Go from right to left to findout if the route goes through the rightmost candidate anf fixes can be applied. + // Other candidates which are sharper than kMaxAbsAngleConsideredLeftOrRightMost are ignored. + for (auto candidate = turnCandidates.rbegin(); candidate != turnCandidates.rend(); ++candidate) + { + if (candidate->m_segment == firstOutgoingSeg && candidate + 1 != turnCandidates.rend()) + { + // The route goes along the rightmost candidate. + turn.m_turn = RightmostDirection(turnAngle); + if (IntermediateDirection(turnAngle) != turn.m_turn) + LOG(LDEBUG, ("Turn: ", turn.m_index, " RighmostDirection correction.")); + // Compare with the next candidate to the left. + CorrectGoStraight(*(candidate + 1), candidate->m_angle, CarDirection::TurnSlightRight, turn); + break; + } + // Check if this candidate is considered as rightmost as not too sharp. + // If yes - this candidate is rightmost, not route's one. + if (candidate->m_angle < kMaxAbsAngleConsideredLeftOrRightMost) + break; + } +} + +void GetTurnDirectionBasic(IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, TurnItem & turn) +{ + TurnInfo turnInfo; + if (!GetTurnInfo(result, outgoingSegmentIndex, vehicleSettings, turnInfo)) + return; + + turn.m_turn = CarDirection::None; + + ASSERT_GREATER(turnInfo.m_ingoing->m_path.size(), 1, ()); + TurnCandidates nodes; + size_t ingoingCount; + m2::PointD const junctionPoint = turnInfo.m_ingoing->m_path.back().GetPoint(); + result.GetPossibleTurns(turnInfo.m_ingoing->m_segmentRange, junctionPoint, ingoingCount, nodes); + if (nodes.isCandidatesAngleValid) + { + ASSERT(std::is_sorted(nodes.candidates.begin(), nodes.candidates.end(), base::LessBy(&TurnCandidate::m_angle)), + ("Turn candidates should be sorted by its angle field.")); + } + + /// @todo Proper handling of isCandidatesAngleValid == False, when we don't have angles of candidates. + + if (nodes.candidates.size() == 0) + return; + + // No turns are needed on transported road. + if (turnInfo.m_ingoing->m_highwayClass == HighwayClass::Transported && + turnInfo.m_outgoing->m_highwayClass == HighwayClass::Transported) + return; + + Segment firstOutgoingSeg; + if (!turnInfo.m_outgoing->m_segmentRange.GetFirstSegment(numMwmIds, firstOutgoingSeg)) + return; + + CorrectCandidatesSegmentByOutgoing(turnInfo, firstOutgoingSeg, nodes); + + RemoveUTurnCandidate(turnInfo, numMwmIds, nodes.candidates); + auto const & turnCandidates = nodes.candidates; + + // Check for enter or exit to/from roundabout. + if (turnInfo.m_ingoing->m_onRoundabout || turnInfo.m_outgoing->m_onRoundabout) + { + turn.m_turn = GetRoundaboutDirection(turnInfo, nodes, numMwmIds); + // If there is 1 or more exits (nodes.candidates > 1) right at the enter it should be counted. Issue #3027. + if (turn.m_turn == CarDirection::EnterRoundAbout && nodes.candidates.size() > 1) + turn.m_exitNum = 1; + return; + } + + double const turnAngle = CalcTurnAngle(result, outgoingSegmentIndex, numMwmIds, vehicleSettings); + + // This angle is calculated using only 1 segment back and forward, not like turnAngle. + double const turnOneSegmentAngle = CalcOneSegmentTurnAngle(turnInfo); + + // To not discard some disputable turns let's use max by modulus from turnOneSegmentAngle and turnAngle. + // It's natural since angles of turnCandidates are calculated in IRoutingResult::GetPossibleTurns() + // according to CalcOneSegmentTurnAngle logic. And to be safe turnAngle is used too. + double turnAngleToCompare = turnAngle; + if (turnOneSegmentAngle <= 0 && turnAngle <= 0) + turnAngleToCompare = std::min(turnOneSegmentAngle, turnAngle); + else if (turnOneSegmentAngle >= 0 && turnAngle >= 0) + turnAngleToCompare = std::max(turnOneSegmentAngle, turnAngle); + else if (std::abs(turnOneSegmentAngle) > 10) + LOG(LWARNING, ("Significant angles are expected to have the same sign.")); + + CarDirection const intermediateDirection = IntermediateDirection(turnAngleToCompare); + + // Checking for exits from highways. + turn.m_turn = TryToGetExitDirection(nodes, turnInfo, firstOutgoingSeg, intermediateDirection); + if (turn.m_turn != CarDirection::None) + return; + + if (turnCandidates.size() == 1) + { + // ASSERT_EQUAL(turnCandidates.front().m_segment, firstOutgoingSeg, ()); + + if (IsGoStraightOrSlightTurn(intermediateDirection)) + return; + // IngoingCount includes ingoing segment and reversed outgoing (if it is not one-way). + // If any other one is present, turn (not straight or slight) is kept to prevent user from going to oneway + // alternative. + + /// @todo Min abs angle of ingoing ones should be considered. If it's much bigger than route angle - ignore ingoing + /// ones. Now this data is not available from IRoutingResult::GetPossibleTurns(). + if (ingoingCount <= 1 + (turnInfo.m_outgoing->m_isOneWay ? 0 : 1)) + return; + } + + if (CanDiscardTurnByHighwayClassOrAngles(intermediateDirection, turnAngleToCompare, turnCandidates, turnInfo, + numMwmIds)) + return; + + turn.m_turn = intermediateDirection; + + if (turnCandidates.size() >= 2 && nodes.isCandidatesAngleValid) + CorrectRightmostAndLeftmost(turnCandidates, firstOutgoingSeg, turnAngleToCompare, turn); +} + +size_t CheckUTurnOnRoute(IRoutingResult const & result, size_t const outgoingSegmentIndex, NumMwmIds const & numMwmIds, + RoutingSettings const & vehicleSettings, TurnItem & turn) +{ + size_t constexpr kUTurnLookAhead = 3; + double constexpr kUTurnHeadingSensitivity = math::pi / 10.0; + auto const & segments = result.GetSegments(); + + // In this function we process the turn between the previous and the current + // segments. So we need a shift to get the previous segment. + ASSERT_GREATER(segments.size(), 1, ()); + ASSERT_GREATER(outgoingSegmentIndex, 0, ()); + ASSERT_GREATER(segments.size(), outgoingSegmentIndex, ()); + auto const & masterSegment = segments[outgoingSegmentIndex - 1]; + if (masterSegment.m_path.size() < 2) + return 0; + + // Roundabout is not the UTurn. + if (masterSegment.m_onRoundabout) + return 0; + for (size_t i = 0; i < kUTurnLookAhead && i + outgoingSegmentIndex < segments.size(); ++i) + { + auto const & checkedSegment = segments[outgoingSegmentIndex + i]; + if (checkedSegment.m_path.size() < 2) + return 0; + + if (checkedSegment.m_roadNameInfo.m_name == masterSegment.m_roadNameInfo.m_name && + checkedSegment.m_highwayClass == masterSegment.m_highwayClass && + checkedSegment.m_isLink == masterSegment.m_isLink && !checkedSegment.m_onRoundabout) + { + auto const & path = masterSegment.m_path; + auto const & pointBeforeTurn = path[path.size() - 2]; + auto const & turnPoint = path[path.size() - 1]; + auto const & pointAfterTurn = checkedSegment.m_path[1]; + // Same segment UTurn case. + if (i == 0) + { + // TODO Fix direction calculation. + // Warning! We can not determine UTurn direction in single edge case. So we use UTurnLeft. + // We decided to add driving rules (left-right sided driving) to mwm header. + if (pointBeforeTurn == pointAfterTurn && turnPoint != pointBeforeTurn) + { + turn.m_turn = CarDirection::UTurnLeft; + return 1; + } + // Wide UTurn must have link in it's middle. + return 0; + } + + // Avoid the UTurn on unnamed roads inside the rectangle based distinct. + if (checkedSegment.m_roadNameInfo.m_name.empty()) + return 0; + + // Avoid returning to the same edge after uturn somewere else. + if (pointBeforeTurn == pointAfterTurn) + return 0; + + m2::PointD const v1 = turnPoint.GetPoint() - pointBeforeTurn.GetPoint(); + m2::PointD const v2 = pointAfterTurn.GetPoint() - checkedSegment.m_path[0].GetPoint(); + + auto angle = ang::TwoVectorsAngle(m2::PointD::Zero(), v1, v2); + + if (!AlmostEqualAbs(angle, math::pi, kUTurnHeadingSensitivity)) + return 0; + + // Determine turn direction. + m2::PointD const junctionPoint = masterSegment.m_path.back().GetPoint(); + + m2::PointD const ingoingPoint = + GetPointForTurn(result, outgoingSegmentIndex, numMwmIds, vehicleSettings.m_maxIngoingPointsCount, + vehicleSettings.m_minIngoingDistMeters, false /* forward */); + m2::PointD const outgoingPoint = + GetPointForTurn(result, outgoingSegmentIndex, numMwmIds, vehicleSettings.m_maxOutgoingPointsCount, + vehicleSettings.m_minOutgoingDistMeters, true /* forward */); + + if (PiMinusTwoVectorsAngle(junctionPoint, ingoingPoint, outgoingPoint) < 0) + turn.m_turn = CarDirection::UTurnLeft; + else + turn.m_turn = CarDirection::UTurnRight; + // junction lab: upstream returns i + 1, which also skips the turn at the end of + // segments[outgoingSegmentIndex + i] (the road back), after the U-turn is done + // (48.489072,34.942352: the exit right 250 m later was lost). The turns inside + // the U-turn are the i into segments[outgoingSegmentIndex + 1 .. + i]. + return i; + } + } + + return 0; +} +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/car_directions.hpp b/third_party/organicmaps-routing/routing/car_directions.hpp new file mode 100644 index 0000000..f743076 --- /dev/null +++ b/third_party/organicmaps-routing/routing/car_directions.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "routing/directions_engine.hpp" + +#include "routing/route.hpp" +#include "routing_common/num_mwm_id.hpp" + +#include +#include + +namespace routing +{ + +class CarDirectionsEngine : public DirectionsEngine +{ +public: + CarDirectionsEngine(MwmDataSource & dataSource, std::shared_ptr numMwmIds); + +protected: + virtual size_t GetTurnDirection(turns::IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, + turns::TurnItem & turn); + virtual void FixupTurns(std::vector & routeSegments); +}; + +void FixupCarTurns(std::vector & routeSegments); + +/*! + * \brief Finds an U-turn that starts from master segment and returns how many segments it lasts. + * \returns an index in |segments| that has the opposite direction with master segment + * (|segments[currentSegment - 1]|) and 0 if there is no UTurn. + * \warning |currentSegment| must be greater than 0. + */ +size_t CheckUTurnOnRoute(turns::IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, turns::TurnItem & turn); + +/*! + * \brief Calculates a turn instruction if the ingoing edge or (and) the outgoing edge belongs to a + * roundabout. + * \return Returns one of the following results: + * - TurnDirection::EnterRoundAbout if the ingoing edge does not belong to a roundabout + * and the outgoing edge belongs to a roundabout. + * - TurnDirection::StayOnRoundAbout if the ingoing edge and the outgoing edge belong to a + * roundabout + * and there is a reasonalbe way to leave the junction besides the outgoing edge. + * This function does not return TurnDirection::StayOnRoundAbout for small ways to leave the + * roundabout. + * - TurnDirection::NoTurn if the ingoing edge and the outgoing edge belong to a roundabout + * (a) and there is a single way (outgoing edge) to leave the junction. + * (b) and there is a way(s) besides outgoing edge to leave the junction (the roundabout) + * but it is (they are) relevantly small. + */ +turns::CarDirection GetRoundaboutDirectionBasic(bool isIngoingEdgeRoundabout, bool isOutgoingEdgeRoundabout, + bool isMultiTurnJunction, bool keepTurnByHighwayClass); + +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/directions_engine.cpp b/third_party/organicmaps-routing/routing/directions_engine.cpp new file mode 100644 index 0000000..d4ab42b --- /dev/null +++ b/third_party/organicmaps-routing/routing/directions_engine.cpp @@ -0,0 +1,92 @@ +#include "routing/directions_engine.hpp" + +// junction lab: trimmed Organic Maps routing/directions_engine.cpp, see the header. +// MakeTurnAnnotation is the upstream loop unchanged except that it takes the +// IRoutingResult instead of building one from route edges, and the size CHECKs on +// route edges are expressed on the loaded segments. + +#include "routing/turns.hpp" + +namespace routing +{ +using namespace routing::turns; + +DirectionsEngine::DirectionsEngine(MwmDataSource & dataSource, std::shared_ptr numMwmIds) + : m_dataSource(dataSource) + , m_numMwmIds(numMwmIds) +{ + CHECK(m_numMwmIds, ()); +} + +// Normally loadedSegments structure is: +// - Start point. Fake loop LoadedPathSegment with 1 segment of zero length. +// - Straight jump from start point to the beginning of real route. LoadedPathSegment with 1 segment. +// - Real route. N LoadedPathSegments, each with arbitrary amount of segments. N >= 1. +// - Straight jump from the end of real route to finish point. LoadedPathSegment with 1 segment. +// - Finish point. Fake loop LoadedPathSegment with 1 segment of zero length. +// So minimal amount of segments is 5. + +// Resulting structure of turnsDir: +// No Turn for 0th segment (no ingoing). m_index == 0. +// No Turn for 1st segment (ingoing fake loop) - at start point. m_index == 1. +// No Turn for 2nd (ingoing == jump) - at beginning of real route. m_index == 2. +// Possible turn for next N-1 segments. m_index >= 3. +// No Turn for (2 + N + 1)th segment (outgoing jump) - at finish point. m_index = 3 + M. +// No Turn for (2 + N + 2)th segment (outgoing fake loop) - at finish point. m_index == 4 + M. +// Added ReachedYourDestination - at finish point. m_index == 4 + M. +// Where M - total amount of all segments from all LoadedPathSegments (size of |segments|). +// So minimum m_index of ReachedYourDestination is 5 (real route with single segment), +// and minimal |turnsDir| is - single ReachedYourDestination with m_index == 5. + +void DirectionsEngine::MakeTurnAnnotation(IRoutingResult const & result, std::vector & routeSegments) +{ + CHECK_GREATER_OR_EQUAL(result.GetSegments().size(), 2, ()); + + RoutingSettings const vehicleSettings = GetRoutingSettings(m_vehicleType); + + auto const & loadedSegments = result.GetSegments(); // the same as m_pathSegments + + // First point of first loadedSegment is ignored. This is the reason for: + // ASSERT_EQUAL(loadedSegments.front().m_path.back(), loadedSegments.front().m_path.front(), ()); + + size_t skipTurnSegments = 0; + for (size_t idxLoadedSegment = 0; idxLoadedSegment < loadedSegments.size(); ++idxLoadedSegment) + { + auto const & loadedSegment = loadedSegments[idxLoadedSegment]; + + CHECK(loadedSegment.IsValid(), ()); + CHECK_GREATER_OR_EQUAL(loadedSegment.m_segments.size(), 1, ()); + CHECK_EQUAL(loadedSegment.m_segments.size() + 1, loadedSegment.m_path.size(), ()); + + auto rni = loadedSegment.m_roadNameInfo; + ASSERT_EQUAL(rni.m_isLink, loadedSegment.m_isLink, ()); + + for (size_t i = 0; i < loadedSegment.m_segments.size() - 1; ++i) + { + auto const & junction = loadedSegment.m_path[i + 1]; + routeSegments.emplace_back(loadedSegment.m_segments[i], TurnItem(), junction, rni); + if (i == 0) + rni.ClearUselessStringsForTailSegments(); + } + + // For the last segment of current loadedSegment put info about turn + // from current loadedSegment to the next one. + TurnItem turnItem; + if (skipTurnSegments == 0) + { + turnItem.m_index = static_cast(routeSegments.size() + 1); + skipTurnSegments = GetTurnDirection(result, idxLoadedSegment + 1, *m_numMwmIds, vehicleSettings, turnItem); + } + else + --skipTurnSegments; + + routeSegments.emplace_back(loadedSegment.m_segments.back(), turnItem, loadedSegment.m_path.back(), rni); + } + + // ASSERT_EQUAL(routeSegments.front().GetJunction(), result.GetStartPoint(), ()); + // ASSERT_EQUAL(routeSegments.back().GetJunction(), result.GetEndPoint(), ()); + + FixupTurns(routeSegments); +} + +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/directions_engine.hpp b/third_party/organicmaps-routing/routing/directions_engine.hpp new file mode 100644 index 0000000..7fdca5b --- /dev/null +++ b/third_party/organicmaps-routing/routing/directions_engine.hpp @@ -0,0 +1,61 @@ +#pragma once + +// junction lab: trimmed Organic Maps routing/directions_engine.hpp. +// Kept: the DirectionsEngine interface CarDirectionsEngine derives from and +// MakeTurnAnnotation. Removed: Generate(), FillPathSegmentsAndAdjacentEdgesMap(), +// GetSegmentRangeAndAdjacentEdges() and LoadPathAttributes(), which read OM's +// IndexRoadGraph and mwm features; tools/junction_lab/omaps_adapter.cpp builds the +// same LoadedPathSegments and turn candidates from OsmAnd's route instead. +// MakeTurnAnnotation is public and takes the IRoutingResult directly. + +#include "routing/loaded_path_segment.hpp" +#include "routing/route.hpp" +#include "routing/routing_result_graph.hpp" +#include "routing/routing_settings.hpp" +#include "routing/vehicle_mask.hpp" + +#include "routing_common/num_mwm_id.hpp" + +#include +#include + +namespace routing +{ +namespace turns +{ +class IRoutingResult; +struct TurnItem; +} // namespace turns + +// junction lab: no mwm data source; features come from the adapter. +class MwmDataSource +{ +}; + +class DirectionsEngine +{ +public: + DirectionsEngine(MwmDataSource & dataSource, std::shared_ptr numMwmIds); + virtual ~DirectionsEngine() = default; + + void SetVehicleType(VehicleType const & vehicleType) { m_vehicleType = vehicleType; } + + /// junction lab: upstream is private and builds RoutingEngineResult from route edges. + void MakeTurnAnnotation(turns::IRoutingResult const & result, std::vector & routeSegments); + +protected: + /*! + * \brief GetTurnDirection makes a primary decision about turns on the route. + * \param outgoingSegmentIndex index of an outgoing segments in vector result.GetSegments(). + * \param turn is used for keeping the result of turn calculation. + */ + virtual size_t GetTurnDirection(turns::IRoutingResult const & result, size_t const outgoingSegmentIndex, + NumMwmIds const & numMwmIds, RoutingSettings const & vehicleSettings, + turns::TurnItem & turn) = 0; + virtual void FixupTurns(std::vector & routeSegments) = 0; + + MwmDataSource & m_dataSource; + std::shared_ptr m_numMwmIds; + VehicleType m_vehicleType = VehicleType::Count; +}; +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/lanes/lane_info.cpp b/third_party/organicmaps-routing/routing/lanes/lane_info.cpp new file mode 100644 index 0000000..d3232a5 --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lane_info.cpp @@ -0,0 +1,24 @@ +#include "lane_info.hpp" + +#include + +namespace routing::turns::lanes +{ +std::string DebugPrint(LaneInfo const & laneInfo) +{ + std::stringstream out; + out << "LaneInfo{" << DebugPrint(laneInfo.laneWays) << ", recommendedWay: " << DebugPrint(laneInfo.recommendedWay) + << "}"; + return out.str(); +} + +std::string DebugPrint(LanesInfo const & lanesInfo) +{ + std::stringstream out; + out << "LanesInfo["; + for (auto const & laneInfo : lanesInfo) + out << DebugPrint(laneInfo) << ", "; + out << "]"; + return out.str(); +} +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lane_info.hpp b/third_party/organicmaps-routing/routing/lanes/lane_info.hpp new file mode 100644 index 0000000..afcc6de --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lane_info.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include "routing/lanes/lane_way.hpp" + +#include + +namespace routing::turns::lanes +{ +struct LaneInfo +{ + LaneWays laneWays; + LaneWay recommendedWay = LaneWay::None; + + bool operator==(LaneInfo const & rhs) const + { + return laneWays == rhs.laneWays && recommendedWay == rhs.recommendedWay; + } +}; +using LanesInfo = std::vector; + +std::string DebugPrint(LaneInfo const & laneInfo); +std::string DebugPrint(LanesInfo const & lanesInfo); +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lane_way.cpp b/third_party/organicmaps-routing/routing/lanes/lane_way.cpp new file mode 100644 index 0000000..43c50bb --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lane_way.cpp @@ -0,0 +1,52 @@ +#include "lane_way.hpp" + +#include "base/assert.hpp" + +#include + +namespace routing::turns::lanes +{ +std::string DebugPrint(LaneWay const laneWay) +{ + // junction lab: C++17 port, `using enum LaneWay` replaced by qualified names. + switch (laneWay) + { + case LaneWay::None: return "None"; + case LaneWay::ReverseLeft: return "ReverseLeft"; + case LaneWay::SharpLeft: return "SharpLeft"; + case LaneWay::Left: return "Left"; + case LaneWay::MergeToLeft: return "MergeToLeft"; + case LaneWay::SlightLeft: return "SlightLeft"; + case LaneWay::Through: return "Through"; + case LaneWay::SlightRight: return "SlightRight"; + case LaneWay::MergeToRight: return "MergeToRight"; + case LaneWay::Right: return "Right"; + case LaneWay::SharpRight: return "SharpRight"; + case LaneWay::ReverseRight: return "ReverseRight"; + case LaneWay::Count: return "Count"; + default: + ASSERT_FAIL("Unsupported value: " + std::to_string(static_cast(laneWay))); + return "Unsupported"; + } +} + +std::string DebugPrint(LaneWays const & laneWays) +{ + std::stringstream out; + out << "LaneWays: ["; + std::uint8_t const waysCount = laneWays.m_laneWays.count(); + std::uint8_t waysPrinted = 0; + for (std::size_t i = 0; i < laneWays.m_laneWays.size(); ++i) + { + if (laneWays.m_laneWays.test(i)) + { + out << DebugPrint(static_cast(i)); + if (waysPrinted < waysCount - 1) + out << ", "; + waysPrinted++; + } + } + out << "]"; + return out.str(); +} +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lane_way.hpp b/third_party/organicmaps-routing/routing/lanes/lane_way.hpp new file mode 100644 index 0000000..8047f8b --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lane_way.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include "base/assert.hpp" + +#include +#include +#include +#include + +namespace routing::turns::lanes +{ +enum class LaneWay : std::uint8_t +{ + None = 0, + ReverseLeft, + SharpLeft, + Left, + MergeToLeft, + SlightLeft, + Through, + SlightRight, + MergeToRight, + Right, + SharpRight, + ReverseRight, + + Count +}; + +class LaneWays +{ + using LaneWaysT = std::bitset(LaneWay::Count)>; + + friend std::string DebugPrint(LaneWays const & laneWays); + +public: + constexpr LaneWays() = default; + // junction lab: C++17 port, constexpr dropped from members that use std::bitset + // operations which are constexpr only since C++23. + LaneWays(std::initializer_list const laneWays) + { + for (auto const & laneWay : laneWays) + Add(laneWay); + } + + bool operator==(LaneWays const & rhs) const { return m_laneWays == rhs.m_laneWays; } + + void Add(LaneWay laneWay) + { + ASSERT_LESS(laneWay, LaneWay::Count, ()); + m_laneWays.set(static_cast(laneWay)); + } + + void Remove(LaneWay laneWay) + { + ASSERT_LESS(laneWay, LaneWay::Count, ()); + m_laneWays.reset(static_cast(laneWay)); + } + + bool Contains(LaneWay laneWay) const + { + ASSERT_LESS(laneWay, LaneWay::Count, ()); + return m_laneWays.test(static_cast(laneWay)); + } + + /// An unrestricted lane is a lane that has no restrictions, i.e., it contains no lane ways. + bool IsUnrestricted() const + { + return m_laneWays.none() || (m_laneWays.count() == 1 && Contains(LaneWay::None)); + } + + [[nodiscard]] std::vector GetActiveLaneWays() const + { + std::vector result; + for (std::size_t i = 0; i < m_laneWays.size(); ++i) + if (m_laneWays.test(i)) + result.emplace_back(static_cast(i)); + return result; + } + +private: + LaneWaysT m_laneWays; +}; + +std::string DebugPrint(LaneWay laneWay); +std::string DebugPrint(LaneWays const & laneWays); +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lanes_parser.cpp b/third_party/organicmaps-routing/routing/lanes/lanes_parser.cpp new file mode 100644 index 0000000..4f69ef2 --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lanes_parser.cpp @@ -0,0 +1,114 @@ +#include "lanes_parser.hpp" + +#include "base/string_utils.hpp" + +#include +#include +#include +#include +#include +#include + +namespace routing::turns::lanes +{ +namespace +{ +std::uint8_t constexpr kLaneWayNamesCount = static_cast(LaneWay::Count) + 4; + +/** + * The order is important. Starting with the most frequent tokens according to + * taginfo.openstreetmap.org we minimize the number of the comparisons in ParseSingleLane(). + * + * A `none` lane can be represented either as "none" or as "". That means both "none" and "" + * should be considered names, even though they refer to the same thing. As a result, + * `LaneWay::None` appears twice in this array, which is one longer than the number of + * enum values. + */ +std::array, kLaneWayNamesCount> constexpr g_laneWayNames{{ + {LaneWay::None, ""}, + {LaneWay::Through, "through"}, + {LaneWay::Left, "left"}, + {LaneWay::Right, "right"}, + {LaneWay::None, "none"}, + {LaneWay::SharpLeft, "sharp_left"}, + {LaneWay::SlightLeft, "slight_left"}, + {LaneWay::MergeToRight, "merge_to_right"}, + {LaneWay::MergeToLeft, "merge_to_left"}, + {LaneWay::SlightRight, "slight_right"}, + {LaneWay::SharpRight, "sharp_right"}, + {LaneWay::ReverseLeft, "reverse"}, + {LaneWay::Right, + "next_right"}, // "next_right" means "turn right, not in the first intersection but the one after that". + {LaneWay::Through, "slide_left"}, // "slide_left" means "move a bit left within the lane". + {LaneWay::Through, "slide_right"} // "slide_right" means "move a bit right within the lane". +}}; + +// junction lab: C++17 port. Upstream takes a ranges view; here the token is a +// std::string that the caller already stripped of ASCII spaces and lower-cased. +bool ParseSingleLane(std::string const & laneWayRange, LaneWay & laneWay) +{ + auto const it = std::find_if(g_laneWayNames.begin(), g_laneWayNames.end(), + [&laneWayRange](auto const & pair) { return laneWayRange == pair.second; }); + if (it != g_laneWayNames.end()) + { + laneWay = it->first; + return true; + } + return false; +} + +// junction lab: C++17 stand-in for `text | std::views::split(delimiter)`: every +// delimiter ends a part, so "a|" gives {"a", ""} and "" gives {""}. +std::vector Split(std::string_view text, char delimiter) +{ + std::vector parts; + std::size_t start = 0; + while (true) + { + std::size_t const end = text.find(delimiter, start); + if (end == std::string_view::npos) + { + parts.push_back(text.substr(start)); + return parts; + } + parts.push_back(text.substr(start, end - start)); + start = end + 1; + } +} + +} // namespace + +LanesInfo ParseLanes(std::string_view lanesString) +{ + if (lanesString.empty()) + return {}; + + LanesInfo lanes; + for (std::string_view const laneInfo : Split(lanesString, '|')) + { + LaneInfo lane; + if (laneInfo.empty()) + lane.laneWays.Add(LaneWay::None); + else + { + for (std::string_view const laneWay : Split(laneInfo, ';')) + { + auto way = LaneWay::None; + // Not : its functions have undefined behavior for the non-ASCII bytes of UTF-8 text. + std::string laneWayProcessed; + for (char const c : laneWay) + if (!strings::IsASCIISpace(c)) + laneWayProcessed.push_back(strings::AsciiToLower(c)); + if (!ParseSingleLane(laneWayProcessed, way)) + return {}; + lane.laneWays.Add(way); + if (way == LaneWay::ReverseLeft) + lane.laneWays.Add(LaneWay::ReverseRight); + } + } + + lanes.push_back(lane); + } + return lanes; +} +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lanes_parser.hpp b/third_party/organicmaps-routing/routing/lanes/lanes_parser.hpp new file mode 100644 index 0000000..3beeda0 --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lanes_parser.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "routing/lanes/lane_info.hpp" + +#include +#include + +namespace routing::turns::lanes +{ +/** + * Parse lane information which comes from lanesString + * @param lanesString lane information. Example through|through|through|through;right + * @return LanesInfo. @see LanesInfo + * @note if lanesString is empty, returns empty LanesInfo. + */ +LanesInfo ParseLanes(std::string_view lanesString); +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.cpp b/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.cpp new file mode 100644 index 0000000..25bc774 --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.cpp @@ -0,0 +1,129 @@ +#include "lanes_recommendation.hpp" + +#include "routing/route.hpp" + +namespace routing::turns::lanes +{ +namespace +{ +void FixRecommendedReverseLane(LaneWays & ways, LaneWay const recommendedWay) +{ + if (recommendedWay == LaneWay::ReverseLeft) + ways.Remove(LaneWay::ReverseRight); + else if (recommendedWay == LaneWay::ReverseRight) + ways.Remove(LaneWay::ReverseLeft); +} +} // namespace + +void SelectRecommendedLanes(std::vector & routeSegments) +{ + for (auto & segment : routeSegments) + { + auto & t = segment.GetTurn(); + if (t.IsTurnNone() || t.m_lanes.empty()) + continue; + auto & lanesInfo = segment.GetTurnLanes(); + // Check if there are elements in lanesInfo that correspond with the turn exactly. + // If so, fix up all the elements in lanesInfo that correspond with the turn. + if (impl::SetRecommendedLaneWays(t.m_turn, lanesInfo)) + continue; + // If not, check if there are elements in lanesInfo that correspond with the turn + // approximately. If so, fix up all those elements. + if (impl::SetRecommendedLaneWaysApproximately(t.m_turn, lanesInfo)) + continue; + // If not, check if there is an unrestricted lane that could correspond to the + // turn. If so, fix up that lane. + if (impl::SetUnrestrictedLaneAsRecommended(t.m_turn, lanesInfo)) + continue; + // Otherwise, we don't have lane recommendations for the user, so we don't + // want to send the lane data any further. + segment.ClearTurnLanes(); + } +} + +bool impl::SetRecommendedLaneWays(CarDirection const carDirection, LanesInfo & lanesInfo) +{ + LaneWay laneWay; + switch (carDirection) + { + case CarDirection::GoStraight: laneWay = LaneWay::Through; break; + case CarDirection::TurnRight: laneWay = LaneWay::Right; break; + case CarDirection::TurnSharpRight: laneWay = LaneWay::SharpRight; break; + case CarDirection::TurnSlightRight: [[fallthrough]]; + case CarDirection::ExitHighwayToRight: laneWay = LaneWay::SlightRight; break; + case CarDirection::TurnLeft: laneWay = LaneWay::Left; break; + case CarDirection::TurnSharpLeft: laneWay = LaneWay::SharpLeft; break; + case CarDirection::TurnSlightLeft: [[fallthrough]]; + case CarDirection::ExitHighwayToLeft: laneWay = LaneWay::SlightLeft; break; + case CarDirection::UTurnLeft: laneWay = LaneWay::ReverseLeft; break; + case CarDirection::UTurnRight: laneWay = LaneWay::ReverseRight; break; + default: return false; + } + + bool isLaneConformed = false; + for (auto & [laneWays, recommendedWay] : lanesInfo) + { + if (laneWays.Contains(laneWay)) + { + recommendedWay = laneWay; + isLaneConformed = true; + } + FixRecommendedReverseLane(laneWays, recommendedWay); + } + return isLaneConformed; +} + +bool impl::SetRecommendedLaneWaysApproximately(CarDirection const carDirection, LanesInfo & lanesInfo) +{ + std::vector approximateLaneWays; + switch (carDirection) + { + case CarDirection::UTurnLeft: approximateLaneWays = {LaneWay::SharpLeft}; break; + case CarDirection::TurnSharpLeft: approximateLaneWays = {LaneWay::Left}; break; + case CarDirection::TurnLeft: approximateLaneWays = {LaneWay::SlightLeft, LaneWay::SharpLeft}; break; + case CarDirection::TurnSlightLeft: [[fallthrough]]; + case CarDirection::ExitHighwayToLeft: approximateLaneWays = {LaneWay::Left}; break; + case CarDirection::GoStraight: approximateLaneWays = {LaneWay::SlightRight, LaneWay::SlightLeft}; break; + case CarDirection::ExitHighwayToRight: [[fallthrough]]; + case CarDirection::TurnSlightRight: approximateLaneWays = {LaneWay::Right}; break; + case CarDirection::TurnRight: approximateLaneWays = {LaneWay::SlightRight, LaneWay::SharpRight}; break; + case CarDirection::TurnSharpRight: approximateLaneWays = {LaneWay::Right}; break; + case CarDirection::UTurnRight: approximateLaneWays = {LaneWay::SharpRight}; break; + default: return false; + } + + bool isLaneConformed = false; + for (auto & [laneWays, recommendedWay] : lanesInfo) + { + for (auto const & laneWay : approximateLaneWays) + { + if (laneWays.Contains(laneWay)) + { + recommendedWay = laneWay; + isLaneConformed = true; + break; + } + } + } + + return isLaneConformed; +} + +bool impl::SetUnrestrictedLaneAsRecommended(CarDirection const carDirection, LanesInfo & lanesInfo) +{ + static auto constexpr setFirstUnrestrictedLane = [](LaneWay const laneWay, auto beginIt, auto endIt) + { + auto it = std::find_if(beginIt, endIt, [](auto const & laneInfo) { return laneInfo.laneWays.IsUnrestricted(); }); + if (it == endIt) + return false; + it->recommendedWay = laneWay; + return true; + }; + + if (IsTurnMadeFromLeft(carDirection)) + return setFirstUnrestrictedLane(LaneWay::Left, lanesInfo.begin(), lanesInfo.end()); + if (IsTurnMadeFromRight(carDirection)) + return setFirstUnrestrictedLane(LaneWay::Right, lanesInfo.rbegin(), lanesInfo.rend()); + return false; +} +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.hpp b/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.hpp new file mode 100644 index 0000000..24d2dd0 --- /dev/null +++ b/third_party/organicmaps-routing/routing/lanes/lanes_recommendation.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include "routing/lanes/lane_info.hpp" + +#include + +namespace routing +{ +class RouteSegment; + +namespace turns +{ +enum class CarDirection; +} // namespace turns +} // namespace routing + +namespace routing::turns::lanes +{ +/// Selects lanes which are recommended for an end user. +void SelectRecommendedLanes(std::vector & routeSegments); + +// Keep signatures in the header for testing purposes +namespace impl +{ +bool SetRecommendedLaneWays(CarDirection carDirection, LanesInfo & lanesInfo); + +bool SetRecommendedLaneWaysApproximately(CarDirection carDirection, LanesInfo & lanesInfo); + +bool SetUnrestrictedLaneAsRecommended(CarDirection carDirection, LanesInfo & lanesInfo); +} // namespace impl +} // namespace routing::turns::lanes diff --git a/third_party/organicmaps-routing/routing/loaded_path_segment.hpp b/third_party/organicmaps-routing/routing/loaded_path_segment.hpp new file mode 100644 index 0000000..ac797c6 --- /dev/null +++ b/third_party/organicmaps-routing/routing/loaded_path_segment.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include "routing/lanes/lane_info.hpp" +#include "routing/route.hpp" +#include "routing/segment.hpp" +#include "routing/turns.hpp" + +#include "indexer/ftypes_matcher.hpp" + +#include + +namespace routing +{ +/*! + * \brief The LoadedPathSegment struct is a representation of a single node path. + * It unpacks and stores information about path and road type flags. + * Postprocessing must read information from the structure and does not initiate disk readings. + */ +struct LoadedPathSegment +{ + RouteJunctions m_path; + turns::lanes::LanesInfo m_lanes; + RouteSegment::RoadNameInfo m_roadNameInfo; + // double m_weight = 0.0; /*!< Time in seconds to pass the segment. */ + SegmentRange m_segmentRange; + std::vector m_segments; /*!< Traffic segments for |m_path|. */ + ftypes::HighwayClass m_highwayClass = ftypes::HighwayClass::Undefined; + bool m_onRoundabout = false; + bool m_isLink = false; + bool m_isOneWay = false; + + bool IsValid() const { return m_path.size() > 1; } +}; + +using TUnpackedPathSegments = std::vector; +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/routing_result_graph.hpp b/third_party/organicmaps-routing/routing/routing_result_graph.hpp new file mode 100644 index 0000000..b9af724 --- /dev/null +++ b/third_party/organicmaps-routing/routing/routing_result_graph.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include "routing/loaded_path_segment.hpp" +#include "routing/turn_candidate.hpp" + +#include "geometry/point_with_altitude.hpp" + +namespace routing +{ +namespace turns +{ +/*! + * \brief The IRoutingResult interface for the routing result. Uncouple router from the + * annotation code that describes turns. See routers for detail implementations. + */ +class IRoutingResult +{ +public: + /// \returns information about all route segments. + virtual TUnpackedPathSegments const & GetSegments() const = 0; + /// \brief For a |segmentRange|, |junctionPoint| and |ingoingPoint| (point before the |junctionPoint|) + /// this method computes number of ingoing ways to |junctionPoint| and fills |outgoingTurns|. + /// \note This method should not be called for |segmentRange| of fake edges. + /// So method |segmentRange.IsClear()| should return false. + virtual void GetPossibleTurns(SegmentRange const & segmentRange, m2::PointD const & junctionPoint, + size_t & ingoingCount, TurnCandidates & outgoingTurns) const = 0; + virtual double GetPathLength() const = 0; + virtual geometry::PointWithAltitude GetStartPoint() const = 0; + virtual geometry::PointWithAltitude GetEndPoint() const = 0; + + virtual ~IRoutingResult() = default; +}; +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/routing_settings.cpp b/third_party/organicmaps-routing/routing/routing_settings.cpp new file mode 100644 index 0000000..63b387e --- /dev/null +++ b/third_party/organicmaps-routing/routing/routing_settings.cpp @@ -0,0 +1,50 @@ +#include "routing/routing_settings.hpp" + +#include "platform/measurement_utils.hpp" // junction lab: was routing/routing_helpers.hpp + +#include "base/assert.hpp" + +namespace routing +{ +namespace +{ +// junction lab: C++17 port. Upstream returns C++20 designated initializers; this +// helper takes the same values in the same (declaration) order. +RoutingSettings MakeSettings(bool useDirectionForRouteBuilding, bool matchRoute, bool soundDirection, + double matchingThresholdM, bool showTurnAfterNext, double minSpeedForRouteRebuildMpS, + double finishToleranceM, size_t maxOutgoingPointsCount, double minOutgoingDistMeters, + size_t maxIngoingPointsCount, double minIngoingDistMeters) +{ + RoutingSettings s; + s.m_useDirectionForRouteBuilding = useDirectionForRouteBuilding; + s.m_matchRoute = matchRoute; + s.m_soundDirection = soundDirection; + s.m_matchingThresholdM = matchingThresholdM; + s.m_showTurnAfterNext = showTurnAfterNext; + s.m_minSpeedForRouteRebuildMpS = minSpeedForRouteRebuildMpS; + s.m_finishToleranceM = finishToleranceM; + s.m_maxOutgoingPointsCount = maxOutgoingPointsCount; + s.m_minOutgoingDistMeters = minOutgoingDistMeters; + s.m_maxIngoingPointsCount = maxIngoingPointsCount; + s.m_minIngoingDistMeters = minIngoingDistMeters; + return s; +} +} // namespace + +RoutingSettings GetRoutingSettings(VehicleType vehicleType) +{ + switch (vehicleType) + { + case VehicleType::Pedestrian: + return MakeSettings(false, false, true, 20.0, false, -1, 15.0, 6, 5.0, 2, 4.0); + case VehicleType::Transit: + return MakeSettings(false, true, false, 40.0, false, -1, 15.0, 6, 5.0, 2, 4.0); + case VehicleType::Bicycle: + return MakeSettings(false, true, true, 30.0, false, -1, 15.0, 9, 10.0, 2, 10.0); + case VehicleType::Car: + return MakeSettings(true, true, true, 50.0, true, measurement_utils::KmphToMps(3.0), 20.0, 9, 120.0, 2, 100.0); + case VehicleType::Count: CHECK(false, ("Can't create GetRoutingSettings for", vehicleType)); + } + UNREACHABLE(); +} +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/routing_settings.hpp b/third_party/organicmaps-routing/routing/routing_settings.hpp new file mode 100644 index 0000000..93ec60d --- /dev/null +++ b/third_party/organicmaps-routing/routing/routing_settings.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include "routing/vehicle_mask.hpp" + +#include + +namespace routing +{ +/// \brief The RoutingSettings struct is intended to collect all the settings of +/// following along the route. +/// For example, route matching properties, rerouting properties and so on. +struct RoutingSettings +{ + /// \brief We accumulate several positions to calculate current direction. + /// So we can use this direction for car for ex. or don't for pedestrian for ex. + bool m_useDirectionForRouteBuilding; + /// \brief if m_matchRoute is equal to true the bearing follows the + /// route direction if the current position is matched to the route. + /// If m_matchRoute is equal to false GPS bearing is used while + /// the current position is matched to the route. + bool m_matchRoute; + /// \brief if m_soundDirection is equal to true an end user gets sound notification + /// before directions. + bool m_soundDirection; + + /// \brief m_matchingThresholdM is half width of the passage around the route + /// for route matching in meters. That means if a real current position is closer than + /// m_matchingThresholdM to the route than the current position is moved to + /// the closest point to the route. + double m_matchingThresholdM; + + /// \brief if m_showTurnAfterNext is equal to true end users see a notification + /// about the turn after the next in some cases. + bool m_showTurnAfterNext; + + /// \brief If the speed in gps info is less than |m_minSpeedForRouteRebuildMpS| + /// info we will penalize less than if it's would be. + /// Penalty uses for route rebuilding during routing. + double m_minSpeedForRouteRebuildMpS; + + /// \brief The distance to the route finish point at which the route should be completed. + double m_finishToleranceM; + + // These 4 parameters are used during turns generation to calculate the turn angle. Based on these + // parameters, the point before the turn and the point after the turn are determined, and the + // angle between them is calculated. + size_t m_maxOutgoingPointsCount; + double m_minOutgoingDistMeters; + size_t m_maxIngoingPointsCount; + double m_minIngoingDistMeters; +}; + +RoutingSettings GetRoutingSettings(VehicleType vehicleType); +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turn_candidate.hpp b/third_party/organicmaps-routing/routing/turn_candidate.hpp new file mode 100644 index 0000000..6025b58 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turn_candidate.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "routing/segment.hpp" +#include "routing/turns.hpp" + +#include "base/math.hpp" + +#include + +namespace ftypes +{ +enum class HighwayClass; +} + +namespace routing +{ +namespace turns +{ +/// \brief The TurnCandidate struct contains information about possible ways from a junction. +struct TurnCandidate +{ + /// |m_angle| is the angle of the turn in degrees. It means the angle is 180 minus + /// the angle between the current edge and the edge of the candidate. A counterclockwise rotation. + /// The current edge is an edge which belongs to the route and is located before the junction. + /// |m_angle| belongs to the range [-180; 180]; + double m_angle; + + /// |m_segment| is the first segment of a possible way from the junction. + Segment m_segment; + + /// \brief |highwayClass| field for the road class caching. Because feature reading is + /// a time-consuming function. + ftypes::HighwayClass m_highwayClass; + + /// If |isLink| is true then the turn candidate is a link. + bool m_isLink; + + TurnCandidate(double angle, Segment const & segment, ftypes::HighwayClass c, bool isLink) + : m_angle(angle) + , m_segment(segment) + , m_highwayClass(c) + , m_isLink(isLink) + {} + + bool IsAlmostEqual(TurnCandidate const & rhs) const + { + double constexpr kEpsilon = 0.01; + return AlmostEqualAbs(m_angle, rhs.m_angle, kEpsilon) && m_segment == rhs.m_segment && + m_highwayClass == rhs.m_highwayClass && m_isLink == rhs.m_isLink; + } +}; + +inline bool IsAlmostEqual(std::vector const & lhs, std::vector const & rhs) +{ + if (lhs.size() != rhs.size()) + return false; + + for (size_t i = 0; i < lhs.size(); ++i) + if (!lhs[i].IsAlmostEqual(rhs[i])) + return false; + return true; +} + +struct TurnCandidates +{ + std::vector candidates; + bool isCandidatesAngleValid; + + explicit TurnCandidates(bool angleValid = true) : isCandidatesAngleValid(angleValid) {} + + bool IsAlmostEqual(TurnCandidates const & rhs) const + { + return turns::IsAlmostEqual(candidates, rhs.candidates) && isCandidatesAngleValid == rhs.isCandidatesAngleValid; + } +}; +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns.cpp b/third_party/organicmaps-routing/routing/turns.cpp new file mode 100644 index 0000000..ecfaa28 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns.cpp @@ -0,0 +1,233 @@ +#include "routing/turns.hpp" + +#include "geometry/angles.hpp" + +#include "platform/country_file.hpp" + +#include "base/internal/message.hpp" + +#include +#include +#include +#include +#include + +namespace routing +{ +using namespace routing::turns; +namespace +{ +std::array, static_cast(CarDirection::Count)> const g_turnNames = { + {{CarDirection::None, "None"}, + {CarDirection::GoStraight, "GoStraight"}, + {CarDirection::TurnRight, "TurnRight"}, + {CarDirection::TurnSharpRight, "TurnSharpRight"}, + {CarDirection::TurnSlightRight, "TurnSlightRight"}, + {CarDirection::TurnLeft, "TurnLeft"}, + {CarDirection::TurnSharpLeft, "TurnSharpLeft"}, + {CarDirection::TurnSlightLeft, "TurnSlightLeft"}, + {CarDirection::UTurnLeft, "UTurnLeft"}, + {CarDirection::UTurnRight, "UTurnRight"}, + {CarDirection::EnterRoundAbout, "EnterRoundAbout"}, + {CarDirection::LeaveRoundAbout, "LeaveRoundAbout"}, + {CarDirection::StayOnRoundAbout, "StayOnRoundAbout"}, + {CarDirection::StartAtEndOfStreet, "StartAtEndOfStreet"}, + {CarDirection::ReachedYourDestination, "ReachedYourDestination"}, + {CarDirection::ExitHighwayToLeft, "ExitHighwayToLeft"}, + {CarDirection::ExitHighwayToRight, "ExitHighwayToRight"}}}; +static_assert(g_turnNames.size() == static_cast(CarDirection::Count), "Check the size of g_turnNames"); +} // namespace + +// SegmentRange ----------------------------------------------------------------------------------- +SegmentRange::SegmentRange(FeatureID const & featureId, uint32_t startSegId, uint32_t endSegId, bool forward, + m2::PointD const & start, m2::PointD const & end) + : m_featureId(featureId) + , m_startSegId(startSegId) + , m_endSegId(endSegId) + , m_forward(forward) + , m_start(start) + , m_end(end) +{ + if (m_startSegId != m_endSegId) + CHECK_EQUAL(m_forward, m_startSegId < m_endSegId, (*this)); +} + +bool SegmentRange::operator==(SegmentRange const & rhs) const +{ + return m_featureId == rhs.m_featureId && m_startSegId == rhs.m_startSegId && m_endSegId == rhs.m_endSegId && + m_forward == rhs.m_forward && m_start == rhs.m_start && m_end == rhs.m_end; +} + +bool SegmentRange::operator<(SegmentRange const & rhs) const +{ + if (m_featureId != rhs.m_featureId) + return m_featureId < rhs.m_featureId; + + if (m_startSegId != rhs.m_startSegId) + return m_startSegId < rhs.m_startSegId; + + if (m_endSegId != rhs.m_endSegId) + return m_endSegId < rhs.m_endSegId; + + if (m_forward != rhs.m_forward) + return m_forward < rhs.m_forward; + + if (m_start != rhs.m_start) + return m_start < rhs.m_start; + + return m_end < rhs.m_end; +} + +void SegmentRange::Clear() +{ + m_featureId = FeatureID(); + m_startSegId = 0; + m_endSegId = 0; + m_forward = true; + m_start = m2::PointD::Zero(); + m_end = m2::PointD::Zero(); +} + +bool SegmentRange::IsEmpty() const +{ + return !m_featureId.IsValid() && m_startSegId == 0 && m_endSegId == 0 && m_forward && m_start == m2::PointD::Zero() && + m_end == m2::PointD::Zero(); +} + +FeatureID const & SegmentRange::GetFeature() const +{ + return m_featureId; +} + +bool SegmentRange::IsCorrect() const +{ + return (m_forward && m_startSegId <= m_endSegId) || (!m_forward && m_endSegId <= m_startSegId); +} + +bool SegmentRange::GetFirstSegment(NumMwmIds const & numMwmIds, Segment & segment) const +{ + return GetSegmentBySegId(m_startSegId, numMwmIds, segment); +} + +bool SegmentRange::GetLastSegment(NumMwmIds const & numMwmIds, Segment & segment) const +{ + return GetSegmentBySegId(m_endSegId, numMwmIds, segment); +} + +bool SegmentRange::GetSegmentBySegId(uint32_t segId, NumMwmIds const & numMwmIds, Segment & segment) const +{ + if (!m_featureId.IsValid()) + return false; + + segment = + Segment(numMwmIds.GetId(platform::CountryFile(m_featureId.GetMwmName())), m_featureId.m_index, segId, m_forward); + return true; +} + +std::string DebugPrint(SegmentRange const & segmentRange) +{ + std::stringstream out; + out << "SegmentRange " + << "{ m_featureId = " << DebugPrint(segmentRange.m_featureId) << ", m_startSegId = " << segmentRange.m_startSegId + << ", m_endSegId = " << segmentRange.m_endSegId << ", m_forward = " << segmentRange.m_forward + << ", m_start = " << DebugPrint(segmentRange.m_start) << ", m_end = " << DebugPrint(segmentRange.m_end) << " }"; + return out.str(); +} + +namespace turns +{ +std::string DebugPrint(TurnItem const & turnItem) +{ + std::stringstream out; + out << "TurnItem " + << "{ m_index = " << turnItem.m_index << ", m_turn = " << DebugPrint(turnItem.m_turn) + << ", m_lanes = " << ::DebugPrint(turnItem.m_lanes) << ", m_exitNum = " << turnItem.m_exitNum + << ", m_pedestrianDir = " << DebugPrint(turnItem.m_pedestrianTurn) << " }"; + return out.str(); +} + +std::string DebugPrint(TurnItemDist const & turnItemDist) +{ + std::stringstream out; + out << "TurnItemDist " + << "{ m_turnItem = " << DebugPrint(turnItemDist.m_turnItem) << ", m_distMeters = " << turnItemDist.m_distMeters + << " }"; + return out.str(); +} + +std::string GetTurnString(CarDirection turn) +{ + for (auto const & p : g_turnNames) + if (p.first == turn) + return p.second; + + ASSERT(false, (static_cast(turn))); + return "unknown CarDirection"; +} + +bool IsLeftTurn(CarDirection t) +{ + return (t >= CarDirection::TurnLeft && t <= CarDirection::TurnSlightLeft); +} + +bool IsRightTurn(CarDirection t) +{ + return (t >= CarDirection::TurnRight && t <= CarDirection::TurnSlightRight); +} + +bool IsLeftOrRightTurn(CarDirection t) +{ + return IsLeftTurn(t) || IsRightTurn(t); +} + +bool IsTurnMadeFromLeft(CarDirection t) +{ + return IsLeftTurn(t) || t == CarDirection::UTurnLeft || t == CarDirection::ExitHighwayToLeft; +} + +bool IsTurnMadeFromRight(CarDirection t) +{ + return IsRightTurn(t) || t == CarDirection::UTurnRight || t == CarDirection::ExitHighwayToRight; +} + +bool IsStayOnRoad(CarDirection t) +{ + return (t == CarDirection::GoStraight || t == CarDirection::StayOnRoundAbout); +} + +bool IsGoStraightOrSlightTurn(CarDirection t) +{ + return (t == CarDirection::GoStraight || t == CarDirection::TurnSlightLeft || t == CarDirection::TurnSlightRight); +} + +std::string DebugPrint(CarDirection const turn) +{ + return GetTurnString(turn); +} + +std::string DebugPrint(PedestrianDirection const l) +{ + switch (l) + { + case PedestrianDirection::None: return "None"; + case PedestrianDirection::GoStraight: return "GoStraight"; + case PedestrianDirection::TurnRight: return "TurnRight"; + case PedestrianDirection::TurnLeft: return "TurnLeft"; + case PedestrianDirection::ReachedYourDestination: return "ReachedYourDestination"; + case PedestrianDirection::Count: + // PedestrianDirection::Count should be never used in the code, print it as unknown value + // (it is added to cases list to suppress compiler warning). + break; + } + + ASSERT(false, (static_cast(l))); + return "unknown PedestrianDirection"; +} + +double PiMinusTwoVectorsAngle(m2::PointD const & junctionPoint, m2::PointD const & ingoingPoint, + m2::PointD const & outgoingPoint) +{ + return math::pi - ang::TwoVectorsAngle(junctionPoint, ingoingPoint, outgoingPoint); +} +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns.hpp b/third_party/organicmaps-routing/routing/turns.hpp new file mode 100644 index 0000000..c1847c1 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns.hpp @@ -0,0 +1,200 @@ +#pragma once + +#include "routing/lanes/lane_info.hpp" +#include "routing/segment.hpp" + +#include "routing_common/num_mwm_id.hpp" + +#include "indexer/feature_decl.hpp" + +#include "geometry/point2d.hpp" + +#include +#include +#include + +namespace routing +{ +/// \brief Unique identification for a road edge between two junctions (joints). The identifier +/// is represented by an mwm id, a feature id, a range of segment ids [|m_startSegId|, |m_endSegId|], +/// a direction and type. +struct SegmentRange +{ + friend std::string DebugPrint(SegmentRange const & segmentRange); + + SegmentRange() = default; + SegmentRange(FeatureID const & featureId, uint32_t startSegId, uint32_t endSegId, bool forward, + m2::PointD const & start, m2::PointD const & end); + bool operator==(SegmentRange const & rh) const; + bool operator<(SegmentRange const & rh) const; + void Clear(); + bool IsEmpty() const; + FeatureID const & GetFeature() const; + /// \returns true if the instance of SegmentRange is correct. + bool IsCorrect() const; + /// \brief Fills |segment| with the first segment of this SegmentRange. + /// \returns true if |segment| is filled and false otherwise. + bool GetFirstSegment(NumMwmIds const & numMwmIds, Segment & segment) const; + bool GetLastSegment(NumMwmIds const & numMwmIds, Segment & segment) const; + +private: + bool GetSegmentBySegId(uint32_t segId, NumMwmIds const & numMwmIds, Segment & segment) const; + + FeatureID m_featureId; + // Note. If SegmentRange represents two directional feature |m_endSegId| is greater + // than |m_startSegId| if |m_forward| == true. + uint32_t m_startSegId = 0; // The first segment index of SegmentRange. + uint32_t m_endSegId = 0; // The last segment index of SegmentRange. + bool m_forward = true; // Segment direction in |m_featureId|. + // Note. According to current implementation SegmentRange is filled based on instances of + // Edge class in DirectionsEngine::GetSegmentRangeAndAdjacentEdges() method. In Edge class + // to identify fake edges (part of real and completely fake) is used coordinates of beginning + // and ending of the edge. To keep SegmentRange instances unique for unique edges + // in case of fake edges it's necessary to have |m_start| and |m_end| fields below. + // @TODO(bykoianko) It's necessary to get rid of |m_start| and |m_end|. + // Fake edges in IndexGraph is identified by instances of Segment + // with Segment::m_mwmId == kFakeNumMwmId. So instead of |m_featureId| field in this class + // number mwm id field and feature id (uint32_t) should be used and |m_start| and |m_end| + // should be removed. To do that classes IndexRoadGraph, CarDirectionsEngine, + // PedestrianDirectionsEngine and other should be significant refactored. + m2::PointD m_start; // Coordinates of start of last Edge in SegmentRange. + m2::PointD m_end; // Coordinates of end of SegmentRange. +}; + +namespace turns +{ +double constexpr kFeaturesNearTurnMeters = 3.0; + +/*! + * \warning The order of values below shall not be changed. + * TurnRight(TurnLeft) must have a minimal value and + * TurnSlightRight(TurnSlightLeft) must have a maximum value + * \warning The values of TurnDirection shall be synchronized with values of TurnDirection enum in + * java. + */ +enum class CarDirection +{ + None = 0, + GoStraight, + + TurnRight, + TurnSharpRight, + TurnSlightRight, + + TurnLeft, + TurnSharpLeft, + TurnSlightLeft, + + UTurnLeft, + UTurnRight, + + EnterRoundAbout, + LeaveRoundAbout, + StayOnRoundAbout, + + // TODO: This value is never assigned. Consider removing it. + StartAtEndOfStreet, + ReachedYourDestination, + + ExitHighwayToLeft, + ExitHighwayToRight, + + Count /**< This value is used for internals only. */ +}; + +std::string DebugPrint(CarDirection const l); + +/*! + * \warning The values of PedestrianDirectionType shall be synchronized with values in java + */ +enum class PedestrianDirection +{ + None = 0, + GoStraight, + TurnRight, + TurnLeft, + ReachedYourDestination, + Count /**< This value is used for internals only. */ +}; + +std::string DebugPrint(PedestrianDirection const l); + +struct TurnItem +{ + TurnItem() + : m_index(std::numeric_limits::max()) + , m_turn(CarDirection::None) + , m_exitNum(0) + , m_pedestrianTurn(PedestrianDirection::None) + {} + + TurnItem(uint32_t idx, CarDirection t, uint32_t exitNum = 0) + : m_index(idx) + , m_turn(t) + , m_exitNum(exitNum) + , m_pedestrianTurn(PedestrianDirection::None) + {} + + TurnItem(uint32_t idx, PedestrianDirection p) + : m_index(idx) + , m_turn(CarDirection::None) + , m_exitNum(0) + , m_pedestrianTurn(p) + {} + + bool operator==(TurnItem const & rhs) const + { + return m_index == rhs.m_index && m_turn == rhs.m_turn && m_lanes == rhs.m_lanes && m_exitNum == rhs.m_exitNum && + m_pedestrianTurn == rhs.m_pedestrianTurn; + } + + bool IsTurnReachedYourDestination() const + { + return m_turn == CarDirection::ReachedYourDestination || + m_pedestrianTurn == PedestrianDirection::ReachedYourDestination; + } + + bool IsTurnNone() const { return m_turn == CarDirection::None && m_pedestrianTurn == PedestrianDirection::None; } + + uint32_t m_index; /*!< Index of point on route polyline (Index of segment + 1). */ + CarDirection m_turn = CarDirection::None; /*!< The turn instruction of the TurnItem */ + lanes::LanesInfo m_lanes; /*!< Lane information on the edge before the turn. */ + uint32_t m_exitNum; /*!< Number of exit on roundabout. */ + /*! + * \brief m_pedestrianTurn is type of corresponding direction for a pedestrian, or None + * if there is no pedestrian specific direction + */ + PedestrianDirection m_pedestrianTurn = PedestrianDirection::None; +}; + +std::string DebugPrint(TurnItem const & turnItem); + +struct TurnItemDist +{ + TurnItemDist(TurnItem const & turnItem, double distMeters) : m_turnItem(turnItem), m_distMeters(distMeters) {} + TurnItemDist() = default; + + TurnItem m_turnItem; + double m_distMeters = 0.0; +}; + +std::string DebugPrint(TurnItemDist const & turnItemDist); + +std::string GetTurnString(CarDirection turn); + +bool IsLeftTurn(CarDirection t); +bool IsRightTurn(CarDirection t); +bool IsLeftOrRightTurn(CarDirection t); +bool IsTurnMadeFromLeft(CarDirection t); +bool IsTurnMadeFromRight(CarDirection t); +bool IsStayOnRoad(CarDirection t); +bool IsGoStraightOrSlightTurn(CarDirection t); +/*! + * \returns pi minus angle from vector [junctionPoint, ingoingPoint] + * to vector [junctionPoint, outgoingPoint]. A counterclockwise rotation. + * Angle is in range [-pi, pi]. + */ +double PiMinusTwoVectorsAngle(m2::PointD const & junctionPoint, m2::PointD const & ingoingPoint, + m2::PointD const & outgoingPoint); +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns_generator.cpp b/third_party/organicmaps-routing/routing/turns_generator.cpp new file mode 100644 index 0000000..07be470 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns_generator.cpp @@ -0,0 +1,397 @@ +#include "routing/turns_generator.hpp" + +#include "routing/turns_generator_utils.hpp" + +#include "indexer/ftypes_matcher.hpp" + +#include "geometry/mercator.hpp" + +namespace routing +{ +namespace turns +{ +using namespace ftypes; + +/// * \returns true when +/// * - the route leads from one big road to another one; +/// * - and the other possible turns lead to small roads; +/// * Returns false otherwise. +/// \param turnCandidates is all possible ways out from a junction. +/// \param turnInfo is information about ingoing and outgoing segments of the route. +bool CanDiscardTurnByHighwayClass(std::vector const & turnCandidates, TurnInfo const & turnInfo, + NumMwmIds const & numMwmIds) +{ + HighwayClass outgoingRouteRoadClass = turnInfo.m_outgoing->m_highwayClass; + HighwayClass ingoingRouteRoadClass = turnInfo.m_ingoing->m_highwayClass; + + HighwayClass maxRouteRoadClass = static_cast( + std::max(static_cast(ingoingRouteRoadClass), static_cast(outgoingRouteRoadClass))); + + // The turn should be kept if there's no any information about feature id of outgoing segment + // just to be on the safe side. It may happen in case of outgoing segment is a finish segment. + Segment firstOutgoingSegment; + if (!turnInfo.m_outgoing->m_segmentRange.GetFirstSegment(numMwmIds, firstOutgoingSegment)) + return false; + + for (auto const & t : turnCandidates) + { + // Let's consider all outgoing segments except for route outgoing segment. + if (t.m_segment == firstOutgoingSegment) + continue; + + HighwayClass candidateRoadClass = t.m_highwayClass; + + // If route's road is significantly larger than candidate's road, the candidate can be ignored. + if (CalcDiffRoadClasses(maxRouteRoadClass, candidateRoadClass) <= kMinHighwayClassDiff) + continue; + + // If route's road is significantly larger than candidate's service road, the candidate can be ignored. + if (CalcDiffRoadClasses(maxRouteRoadClass, candidateRoadClass) <= kMinHighwayClassDiffForService && + (candidateRoadClass == HighwayClass::Service || candidateRoadClass == HighwayClass::ServiceMinor)) + continue; + + return false; + } + + return true; +} + +m2::PointD GetPointForTurn(IRoutingResult const & result, size_t outgoingSegmentIndex, NumMwmIds const & numMwmIds, + size_t const maxPointsCount, double const maxDistMeters, bool const forward) +{ + auto const & segments = result.GetSegments(); + ASSERT_LESS(outgoingSegmentIndex, segments.size(), ()); + ASSERT_GREATER(outgoingSegmentIndex, 0, ()); + + RoutePointIndex index = forward ? GetFirstOutgoingPointIndex(outgoingSegmentIndex) + : GetLastIngoingPointIndex(segments, outgoingSegmentIndex); + + ASSERT_LESS(index.m_pathIndex, segments[index.m_segmentIndex].m_path.size(), ()); + ASSERT_LESS(index.m_segmentIndex, segments.size(), ()); + ASSERT(!segments[index.m_segmentIndex].m_path.empty(), ()); + + RoutePointIndex nextIndex; + ASSERT(GetNextRoutePointIndex(result, index, numMwmIds, forward, nextIndex), ()); + + // There is no need for looking too far for low-speed roads. + // So additional time limit is applied. + double constexpr kMaxTimeSeconds = 3.0; + + m2::PointD point = GetPointByIndex(segments, index); + + size_t count = 0; + double curDistanceMeters = 0.0; + double curTimeSeconds = 0.0; + + while (GetNextRoutePointIndex(result, index, numMwmIds, forward, nextIndex)) + { + m2::PointD const nextPoint = GetPointByIndex(segments, nextIndex); + + // At start and finish there are two edges with zero length. + // This function should not be called for the start (|outgoingSegmentIndex| == 0). + // So there is special processing for the finish below. + if (point == nextPoint && outgoingSegmentIndex + 1 == segments.size()) + return nextPoint; + + double const distanceMeters = mercator::DistanceOnEarth(point, nextPoint); + double const timeSeconds = + CalcEstimatedTimeToPass(distanceMeters, segments[nextIndex.m_segmentIndex].m_highwayClass); + + // If the next geometry edge overshoots the time or the distance limit, a point on this edge + // at the limit is taken. Otherwise on sparse geometry one long edge could move the result + // tens of meters past the limits, and the turn angle would get the road curvature + // accumulated far from the junction. See https://github.com/organicmaps/organicmaps/issues/13152 + if (curTimeSeconds + timeSeconds > kMaxTimeSeconds || curDistanceMeters + distanceMeters > maxDistMeters) + { + double share = 1.0; + if (timeSeconds > 0.0) + share = std::min(share, (kMaxTimeSeconds - curTimeSeconds) / timeSeconds); + if (distanceMeters > 0.0) + share = std::min(share, (maxDistMeters - curDistanceMeters) / distanceMeters); + return point + (nextPoint - point) * share; + } + + curDistanceMeters += distanceMeters; + curTimeSeconds += timeSeconds; + + if (++count >= maxPointsCount) + return nextPoint; + + point = nextPoint; + index = nextIndex; + } + + return point; +} + +/*! + * \brief Calculates |nextIndex| which is an index of next route point at result.GetSegments() + * in forward direction. + * If + * - |index| points at the last point of the turn segment: + * - and the route at this point leads from one big road to another one + * - and the other possible turns lead to small roads or there's no them + * - and the turn is GoStraight or TurnSlight* + * method returns the second point of the next segment. First point of the next segment is skipped + * because it's almost the same with the last point of this segment. + * if |index| points at the first or intermediate point in turn segment returns the next one. + * \returns true if |nextIndex| fills correctly and false otherwise. + */ +bool GetNextCrossSegmentRoutePoint(IRoutingResult const & result, RoutePointIndex const & index, + NumMwmIds const & numMwmIds, RoutePointIndex & nextIndex) +{ + auto const & segments = result.GetSegments(); + ASSERT_LESS(index.m_segmentIndex, segments.size(), ()); + ASSERT_LESS(index.m_pathIndex, segments[index.m_segmentIndex].m_path.size(), ()); + + if (index.m_pathIndex + 1 != segments[index.m_segmentIndex].m_path.size()) + { + // In segment case. + nextIndex = {index.m_segmentIndex, index.m_pathIndex + 1}; + return true; + } + + // Case when the last point of the current segment is reached. + // So probably it's necessary to cross a segment border. + if (index.m_segmentIndex + 1 == segments.size()) + return false; // The end of the route is reached. + + TurnInfo const turnInfo(&segments[index.m_segmentIndex], &segments[index.m_segmentIndex + 1]); + + double const oneSegmentTurnAngle = CalcOneSegmentTurnAngle(turnInfo); + CarDirection const oneSegmentDirection = IntermediateDirection(oneSegmentTurnAngle); + if (!IsGoStraightOrSlightTurn(oneSegmentDirection)) + return false; // Too sharp turn angle. + + size_t ingoingCount = 0; + TurnCandidates possibleTurns; + result.GetPossibleTurns(turnInfo.m_ingoing->m_segmentRange, GetPointByIndex(segments, index), ingoingCount, + possibleTurns); + + if (possibleTurns.candidates.empty()) + return false; + + // |segments| is a vector of |LoadedPathSegment|. Every |LoadedPathSegment::m_path| + // contains junctions of the segment. The first junction at a |LoadedPathSegment::m_path| + // is the same (or almost the same) with the last junction at the next |LoadedPathSegment::m_path|. + // To prevent using the same point twice it's necessary to take the first point only from the + // first item of |loadedSegments|. The beginning should be ignored for the rest |m_path|. + // Please see a comment in MakeTurnAnnotation() for more details. + if (possibleTurns.candidates.size() == 1) + { + // Taking the next point of the next segment. + nextIndex = {index.m_segmentIndex + 1, 1 /* m_pathIndex */}; + return true; + } + + if (CanDiscardTurnByHighwayClass(possibleTurns.candidates, turnInfo, numMwmIds)) + { + // Taking the next point of the next segment. + nextIndex = {index.m_segmentIndex + 1, 1 /* m_pathIndex */}; + return true; + } + // Stopping getting next route points because an important bifurcation point is reached. + return false; +} + +bool GetPrevInSegmentRoutePoint(IRoutingResult const & result, RoutePointIndex const & index, + RoutePointIndex & nextIndex) +{ + if (index.m_pathIndex == 0) + return false; + + auto const & segments = result.GetSegments(); + if (segments[index.m_segmentIndex].m_path.size() >= 3 && + index.m_pathIndex < segments[index.m_segmentIndex].m_path.size() - 1) + { + double const oneSegmentTurnAngle = CalcPathTurnAngle(segments[index.m_segmentIndex], index.m_pathIndex); + CarDirection const oneSegmentDirection = IntermediateDirection(oneSegmentTurnAngle); + if (!IsGoStraightOrSlightTurn(oneSegmentDirection)) + return false; // Too sharp turn angle. + } + + nextIndex = {index.m_segmentIndex, index.m_pathIndex - 1}; + return true; +} + +bool GetNextRoutePointIndex(IRoutingResult const & result, RoutePointIndex const & index, NumMwmIds const & numMwmIds, + bool const forward, RoutePointIndex & nextIndex) +{ + if (forward) + { + if (!GetNextCrossSegmentRoutePoint(result, index, numMwmIds, nextIndex)) + return false; + } + else + { + if (!GetPrevInSegmentRoutePoint(result, index, nextIndex)) + return false; + } + + ASSERT_LESS(nextIndex.m_segmentIndex, result.GetSegments().size(), ()); + ASSERT_LESS(nextIndex.m_pathIndex, result.GetSegments()[nextIndex.m_segmentIndex].m_path.size(), ()); + return true; +} + +void RemoveUTurnCandidate(TurnInfo const & turnInfo, NumMwmIds const & numMwmIds, + std::vector & turnCandidates) +{ + Segment lastIngoingSegment; + if (turnInfo.m_ingoing->m_segmentRange.GetLastSegment(numMwmIds, lastIngoingSegment)) + { + if (turnCandidates.front().m_segment.IsInverse(lastIngoingSegment)) + turnCandidates.erase(turnCandidates.begin()); + else if (turnCandidates.back().m_segment.IsInverse(lastIngoingSegment)) + turnCandidates.pop_back(); + } +} + +/// \returns true if there is exactly 1 turn in |turnCandidates| with angle less then +/// |kMaxForwardAngleCandidates|. +bool HasSingleForwardTurn(TurnCandidates const & turnCandidates, float maxForwardAngleCandidates) +{ + bool foundForwardTurn = false; + + for (auto const & turn : turnCandidates.candidates) + { + if (std::fabs(turn.m_angle) < maxForwardAngleCandidates) + { + if (foundForwardTurn) + return false; + + foundForwardTurn = true; + } + } + + return foundForwardTurn; +} + +double CalcTurnAngle(IRoutingResult const & result, size_t const outgoingSegmentIndex, NumMwmIds const & numMwmIds, + RoutingSettings const & vehicleSettings) +{ + bool const isStartFakeLoop = PathIsFakeLoop(result.GetSegments()[outgoingSegmentIndex - 1].m_path); + size_t const segmentIndexForIngoingPoint = isStartFakeLoop ? outgoingSegmentIndex - 1 : outgoingSegmentIndex; + + m2::PointD const ingoingPoint = + GetPointForTurn(result, segmentIndexForIngoingPoint, numMwmIds, vehicleSettings.m_maxIngoingPointsCount, + vehicleSettings.m_minIngoingDistMeters, false /* forward */); + m2::PointD const outgoingPoint = + GetPointForTurn(result, outgoingSegmentIndex, numMwmIds, vehicleSettings.m_maxOutgoingPointsCount, + vehicleSettings.m_minOutgoingDistMeters, true /* forward */); + + m2::PointD const junctionPoint = result.GetSegments()[outgoingSegmentIndex].m_path.front().GetPoint(); + return math::RadToDeg(PiMinusTwoVectorsAngle(junctionPoint, ingoingPoint, outgoingPoint)); +} + +void CorrectCandidatesSegmentByOutgoing(TurnInfo const & turnInfo, Segment const & firstOutgoingSeg, + TurnCandidates & nodes) +{ + double const turnAngle = CalcOneSegmentTurnAngle(turnInfo); + auto const IsFirstOutgoingSeg = [&firstOutgoingSeg](TurnCandidate const & turnCandidate) + { return turnCandidate.m_segment == firstOutgoingSeg; }; + auto & candidates = nodes.candidates; + auto it = std::find_if(candidates.begin(), candidates.end(), IsFirstOutgoingSeg); + if (it == candidates.end()) + { + // firstOutgoingSeg not found. Try to match by angle. + auto const DoesAngleMatch = [&turnAngle](TurnCandidate const & candidate) + { + return (AlmostEqualAbs(candidate.m_angle, turnAngle, 0.001) || + fabs(candidate.m_angle) + fabs(turnAngle) > 359.999); + }; + auto it = std::find_if(candidates.begin(), candidates.end(), DoesAngleMatch); + if (it != candidates.end()) + { + // Match by angle. Update candidate's segment. + ASSERT(it->m_segment.GetMwmId() != firstOutgoingSeg.GetMwmId(), ()); + ASSERT(it->m_segment.GetSegmentIdx() == firstOutgoingSeg.GetSegmentIdx(), ()); + ASSERT(it->m_segment.IsForward() == firstOutgoingSeg.IsForward(), ()); + it->m_segment = firstOutgoingSeg; + } + else if (nodes.isCandidatesAngleValid) + { + // Typically all candidates are from one mwm, and missed one (firstOutgoingSegment) from another. + LOG(LWARNING, ("Can't match any candidate with firstOutgoingSegment but isCandidatesAngleValid == true.")); + } + else + { + LOG(LWARNING, ("Can't match any candidate with firstOutgoingSegment and isCandidatesAngleValid == false")); + if (candidates.size() == 1) + { + auto & c = candidates.front(); + ASSERT(c.m_segment.GetMwmId() != firstOutgoingSeg.GetMwmId(), ()); + ASSERT(c.m_segment.GetSegmentIdx() == firstOutgoingSeg.GetSegmentIdx(), ()); + ASSERT(c.m_segment.IsForward() == firstOutgoingSeg.IsForward(), ()); + c.m_segment = firstOutgoingSeg; + c.m_angle = turnAngle; + nodes.isCandidatesAngleValid = true; + LOG(LWARNING, ("but since candidates.size() == 1, this was fixed.")); + } + else + LOG(LWARNING, ("and since candidates.size() > 1, this can't be fixed.")); + } + } + else // firstOutgoingSeg is found. + if (nodes.isCandidatesAngleValid) + { +#ifdef DEBUG + double constexpr eps = 0.001; + double const diff = fabs(it->m_angle - turnAngle); + ASSERT(diff < eps || fabs(diff - 360) < eps, (it->m_angle, turnAngle)); +#endif + } + else + { + it->m_angle = turnAngle; + if (candidates.size() == 1) + nodes.isCandidatesAngleValid = true; + else + LOG(LWARNING, ("isCandidatesAngleValid == false, and this can't be fixed.")); + } +} + +bool GetTurnInfo(IRoutingResult const & result, size_t const outgoingSegmentIndex, + RoutingSettings const & vehicleSettings, TurnInfo & turnInfo) +{ + auto const & segments = result.GetSegments(); + CHECK_LESS(outgoingSegmentIndex, segments.size(), ()); + CHECK_GREATER(outgoingSegmentIndex, 0, ()); + + if (PathIsFakeLoop(segments[outgoingSegmentIndex].m_path)) + return false; + + bool const isStartFakeLoop = PathIsFakeLoop(segments[outgoingSegmentIndex - 1].m_path); + + if (isStartFakeLoop && outgoingSegmentIndex < 2) + return false; + + size_t const prevIndex = isStartFakeLoop ? outgoingSegmentIndex - 2 : outgoingSegmentIndex - 1; + turnInfo = TurnInfo(&segments[prevIndex], &segments[outgoingSegmentIndex]); + + if (!turnInfo.IsSegmentsValid() || turnInfo.m_ingoing->m_segmentRange.IsEmpty()) + return false; + + if (isStartFakeLoop) + { + if (mercator::DistanceOnEarth(turnInfo.m_ingoing->m_path.front().GetPoint(), + turnInfo.m_ingoing->m_path.back().GetPoint()) < + vehicleSettings.m_minIngoingDistMeters || + mercator::DistanceOnEarth(turnInfo.m_outgoing->m_path.front().GetPoint(), + turnInfo.m_outgoing->m_path.back().GetPoint()) < + vehicleSettings.m_minOutgoingDistMeters) + { + return false; + } + } + + ASSERT(!turnInfo.m_ingoing->m_path.empty(), ()); + ASSERT(!turnInfo.m_outgoing->m_path.empty(), ()); + ASSERT_LESS(mercator::DistanceOnEarth(turnInfo.m_ingoing->m_path.back().GetPoint(), + turnInfo.m_outgoing->m_path.front().GetPoint()), + kFeaturesNearTurnMeters, ()); + + return true; +} + +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns_generator.hpp b/third_party/organicmaps-routing/routing/turns_generator.hpp new file mode 100644 index 0000000..10ae377 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns_generator.hpp @@ -0,0 +1,102 @@ +#pragma once + +#include "routing/routing_result_graph.hpp" +#include "routing/routing_settings.hpp" +#include "routing/turn_candidate.hpp" +#include "routing/turns.hpp" + +#include "routing_common/num_mwm_id.hpp" + +#include "geometry/point_with_altitude.hpp" + +#include +#include +#include +#include +#include + +struct PathData; + +namespace ftypes +{ +enum class HighwayClass; +} + +namespace routing +{ +struct RoutingMapping; + +namespace turns +{ +/*! + * \brief Returns a segment index by STL-like range [s, e) of segments indices for the passed node. + */ +using TGetIndexFunction = std::function)>; + +struct RoutePointIndex; +struct TurnInfo; + +/*! + * \brief Calculates |nextIndex| which is an index of next route point at result.GetSegments(). + * |nextIndex| may be calculated in forward and backward direction. + * \returns true if |nextIndex| is calculated and false otherwise. This method returns false + * if looking for next index should be stopped. For example in case of the point before first, + * after the last in the route and sometimes at the end of features and at feature intersections. + * \note This method is asymmetric. It means that in some cases it's possible to cross + * the border between turn segments in forward direction, but in backward direction (|forward| == false) + * it's impossible. So when turn segment border is reached in backward direction the method + * returns false. The reasons why crossing the border in backward direction is not implemented is + * it's almost not used now and it's difficult to cover it with unit and integration tests. + * As a consequence moving in backward direction it's possible to get index of the first item + * of a segment. But it's impossible moving in forward direction. + */ +bool GetNextRoutePointIndex(IRoutingResult const & result, RoutePointIndex const & index, NumMwmIds const & numMwmIds, + bool const forward, RoutePointIndex & nextIndex); + +bool GetTurnInfo(IRoutingResult const & result, size_t const outgoingSegmentIndex, + RoutingSettings const & vehicleSettings, TurnInfo & turnInfo); + +/// \returns angle, wchis is calculated using several backward and forward segments +/// from junction to consider smooth turns and remove noise. +double CalcTurnAngle(IRoutingResult const & result, size_t const outgoingSegmentIndex, NumMwmIds const & numMwmIds, + RoutingSettings const & vehicleSettings); + +void RemoveUTurnCandidate(TurnInfo const & turnInfo, NumMwmIds const & numMwmIds, + std::vector & turnCandidates); + +/// \returns true if there is exactly 1 turn in |turnCandidates| with angle less then +/// |kMaxForwardAngleCandidates|. +bool HasSingleForwardTurn(TurnCandidates const & turnCandidates, float maxForwardAngleCandidates); + +// It's possible that |firstOutgoingSeg| is not contained in |turnCandidates|. +// It may happened if |firstOutgoingSeg| and candidates in |turnCandidates| are from different mwms. +// Let's identify it in turnCandidates by angle and update according turnCandidate. +void CorrectCandidatesSegmentByOutgoing(TurnInfo const & turnInfo, Segment const & firstOutgoingSeg, + TurnCandidates & nodes); + +/*! + * \brief Returns ingoing point or outgoing point for turns. + * These points belong to the route but they often are not neighbor of junction point. + * To calculate the resulting point the function implements the following steps: + * - going from junction point along route path according to the direction which is set in GetPointIndex(). + * - until one of following conditions is fulfilled: + * - more than |maxPointsCount| points are passed (returns the maxPointsCount-th point); + * - the length of passed parts of segment exceeds maxDistMeters; + * (returns the next point after the event) + * - an important bifurcation point is reached in case of outgoing point is looked up (forward == true). + * \param result information about the route. |result.GetSegments()| is composed of LoadedPathSegment. + * Each LoadedPathSegment is composed of several Segments. The sequence of Segments belongs to + * single feature and does not split by other features. + * \param outgoingSegmentIndex index in |segments|. Junction point noticed above is the first point + * of |outgoingSegmentIndex| segment in |result.GetSegments()|. + * \param maxPointsCount maximum number between the returned point and junction point. + * \param maxDistMeters maximum distance between the returned point and junction point. + * \param forward is direction of moving along the route to calculate the returned point. + * If forward == true the direction is to route finish. If forward == false the direction is to route start. + * \return an ingoing or outgoing point for a turn calculation. + */ +m2::PointD GetPointForTurn(IRoutingResult const & result, size_t outgoingSegmentIndex, NumMwmIds const & numMwmIds, + size_t const maxPointsCount, double const maxDistMeters, bool const forward); + +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns_generator_utils.cpp b/third_party/organicmaps-routing/routing/turns_generator_utils.cpp new file mode 100644 index 0000000..ce8ff00 --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns_generator_utils.cpp @@ -0,0 +1,199 @@ +#include "routing/turns_generator_utils.hpp" +#include "routing/turns.hpp" + +#include "platform/measurement_utils.hpp" + +#include "geometry/mercator.hpp" + +namespace routing +{ +namespace turns +{ + +using namespace ftypes; + +bool IsHighway(HighwayClass hwClass, bool isLink) +{ + return (hwClass == HighwayClass::Trunk || hwClass == HighwayClass::Primary) && !isLink; +} + +bool IsSmallRoad(HighwayClass hwClass) +{ + return hwClass == HighwayClass::LivingStreet || hwClass == HighwayClass::Service || + hwClass == HighwayClass::ServiceMinor || hwClass == HighwayClass::Pedestrian; +} + +int CalcDiffRoadClasses(HighwayClass const left, HighwayClass const right) +{ + return static_cast(left) - static_cast(right); +} + +template +T FindDirectionByAngle(std::vector> const & lowerBounds, double const angle) +{ + ASSERT_GREATER_OR_EQUAL(angle, -180., (angle)); + ASSERT_LESS_OR_EQUAL(angle, 180., (angle)); + ASSERT(!lowerBounds.empty(), ()); + ASSERT(is_sorted(lowerBounds.rbegin(), lowerBounds.rend(), base::LessBy(&std::pair::first)), ()); + + for (auto const & lower : lowerBounds) + if (angle >= lower.first) + return lower.second; + + ASSERT(false, ("The angle is not covered by the table. angle = ", angle)); + return T::None; +} + +CarDirection InvertDirection(CarDirection const dir) +{ + switch (dir) + { + case CarDirection::TurnSlightRight: return CarDirection::TurnSlightLeft; + case CarDirection::TurnRight: return CarDirection::TurnLeft; + case CarDirection::TurnSharpRight: return CarDirection::TurnSharpLeft; + case CarDirection::TurnSlightLeft: return CarDirection::TurnSlightRight; + case CarDirection::TurnLeft: return CarDirection::TurnRight; + case CarDirection::TurnSharpLeft: return CarDirection::TurnSharpRight; + default: return dir; + }; +} + +CarDirection RightmostDirection(double const angle) +{ + static std::vector> const kLowerBounds = { + {145., CarDirection::TurnSharpRight}, + {50., CarDirection::TurnRight}, + {10., CarDirection::TurnSlightRight}, + // For sure it's incorrect to give directions TurnLeft or TurnSlighLeft if we need the rightmost turn. + // So GoStraight direction is given even for needed sharp left turn when other turns on the left and are more + // sharp. The reason: the rightmost turn is the most straight one here. + {-180., CarDirection::GoStraight}}; + + return FindDirectionByAngle(kLowerBounds, angle); +} + +CarDirection LeftmostDirection(double const angle) +{ + return InvertDirection(RightmostDirection(-angle)); +} + +CarDirection IntermediateDirection(double const angle) +{ + static std::vector> const kLowerBounds = { + {145., CarDirection::TurnSharpRight}, {50., CarDirection::TurnRight}, {10., CarDirection::TurnSlightRight}, + {-10., CarDirection::GoStraight}, {-50., CarDirection::TurnSlightLeft}, {-145., CarDirection::TurnLeft}, + {-180., CarDirection::TurnSharpLeft}}; + + return FindDirectionByAngle(kLowerBounds, angle); +} + +PedestrianDirection IntermediateDirectionPedestrian(double const angle) +{ + static std::vector> const kLowerBounds = { + {10.0, PedestrianDirection::TurnRight}, + {-10.0, PedestrianDirection::GoStraight}, + {-180.0, PedestrianDirection::TurnLeft}}; + + return FindDirectionByAngle(kLowerBounds, angle); +} + +double CalcEstimatedTimeToPass(double const distanceMeters, HighwayClass const highwayClass) +{ + double speedKmph = 0; + switch (highwayClass) + { + case HighwayClass::Trunk: speedKmph = 100.0; break; + case HighwayClass::Primary: speedKmph = 70.0; break; + case HighwayClass::Secondary: speedKmph = 70.0; break; + case HighwayClass::Tertiary: speedKmph = 50.0; break; + case HighwayClass::LivingStreet: speedKmph = 20.0; break; + case HighwayClass::Service: + case HighwayClass::ServiceMinor: speedKmph = 10.0; break; + case HighwayClass::Pedestrian: speedKmph = 5.0; break; + default: speedKmph = 50.0; break; + } + return distanceMeters / measurement_utils::KmphToMps(speedKmph); +} + +bool PathIsFakeLoop(RouteJunctions const & path) +{ + return path.size() == 2 && path[0] == path[1]; +} + +double CalcRouteDistanceM(RouteJunctions const & junctions, uint32_t start, uint32_t end) +{ + double res = 0.0; + + for (uint32_t i = start + 1; i < end; ++i) + res += mercator::DistanceOnEarth(junctions[i - 1].GetPoint(), junctions[i].GetPoint()); + + return res; +} + +// TurnInfo ---------------------------------------------------------------------------------------- +bool TurnInfo::IsSegmentsValid() const +{ + if (m_ingoing->m_path.empty() || m_outgoing->m_path.empty()) + { + LOG(LWARNING, ("Some turns can't load the geometry.")); + return false; + } + return true; +} + +// RoutePointIndex --------------------------------------------------------------------------------- +bool RoutePointIndex::operator==(RoutePointIndex const & index) const +{ + return m_segmentIndex == index.m_segmentIndex && m_pathIndex == index.m_pathIndex; +} + +std::string DebugPrint(RoutePointIndex const & index) +{ + std::stringstream out; + out << "RoutePointIndex [ m_segmentIndex == " << index.m_segmentIndex << ", m_pathIndex == " << index.m_pathIndex + << " ]" << std::endl; + return out.str(); +} + +RoutePointIndex GetFirstOutgoingPointIndex(size_t outgoingSegmentIndex) +{ + return RoutePointIndex({outgoingSegmentIndex, 0 /* m_pathIndex */}); +} + +RoutePointIndex GetLastIngoingPointIndex(TUnpackedPathSegments const & segments, size_t const outgoingSegmentIndex) +{ + ASSERT_GREATER(outgoingSegmentIndex, 0, ()); + ASSERT(segments[outgoingSegmentIndex - 1].IsValid(), ()); + return RoutePointIndex( + {outgoingSegmentIndex - 1, segments[outgoingSegmentIndex - 1].m_path.size() - 1 /* m_pathIndex */}); +} + +m2::PointD GetPointByIndex(TUnpackedPathSegments const & segments, RoutePointIndex const & index) +{ + return segments[index.m_segmentIndex].m_path[index.m_pathIndex].GetPoint(); +} + +double CalcOneSegmentTurnAngle(TurnInfo const & turnInfo) +{ + ASSERT_GREATER_OR_EQUAL(turnInfo.m_ingoing->m_path.size(), 2, ()); + ASSERT_GREATER_OR_EQUAL(turnInfo.m_outgoing->m_path.size(), 2, ()); + + return math::RadToDeg( + PiMinusTwoVectorsAngle(turnInfo.m_ingoing->m_path.back().GetPoint(), + turnInfo.m_ingoing->m_path[turnInfo.m_ingoing->m_path.size() - 2].GetPoint(), + turnInfo.m_outgoing->m_path[1].GetPoint())); +} + +double CalcPathTurnAngle(LoadedPathSegment const & segment, size_t const pathIndex) +{ + ASSERT_GREATER_OR_EQUAL(segment.m_path.size(), 3, ()); + ASSERT_GREATER(pathIndex, 0, ()); + ASSERT_LESS(pathIndex, segment.m_path.size() - 1, ()); + + return math::RadToDeg(PiMinusTwoVectorsAngle(segment.m_path[pathIndex].GetPoint(), + segment.m_path[pathIndex - 1].GetPoint(), + segment.m_path[pathIndex + 1].GetPoint())); +} + +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/routing/turns_generator_utils.hpp b/third_party/organicmaps-routing/routing/turns_generator_utils.hpp new file mode 100644 index 0000000..72d797d --- /dev/null +++ b/third_party/organicmaps-routing/routing/turns_generator_utils.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "geometry/point_with_altitude.hpp" +#include "indexer/ftypes_matcher.hpp" +#include "routing/loaded_path_segment.hpp" + +namespace routing +{ +namespace turns +{ +enum class CarDirection; +enum class PedestrianDirection; +/*! + * \brief The TurnInfo structure is a representation of a junction. + * It has ingoing and outgoing edges and method to check if these edges are valid. + */ +struct TurnInfo +{ + LoadedPathSegment const * m_ingoing; + LoadedPathSegment const * m_outgoing; + + TurnInfo() : m_ingoing(nullptr), m_outgoing(nullptr) {} + + TurnInfo(LoadedPathSegment const * ingoingSegment, LoadedPathSegment const * outgoingSegment) + : m_ingoing(ingoingSegment) + , m_outgoing(outgoingSegment) + {} + + bool IsSegmentsValid() const; +}; + +bool IsHighway(ftypes::HighwayClass hwClass, bool isLink); +bool IsSmallRoad(ftypes::HighwayClass hwClass); + +// Min difference between HighwayClasses of the route segment and alternative turn segment +// to ignore this alternative candidate. +int constexpr kMinHighwayClassDiff = -2; + +// Min difference between HighwayClasses of the route segment and alternative turn segment +// to ignore this alternative candidate (when alternative road is service). +int constexpr kMinHighwayClassDiffForService = -1; + +/// * \returns difference between highway classes. +/// * It should be considered that bigger roads have smaller road class. +int CalcDiffRoadClasses(ftypes::HighwayClass const left, ftypes::HighwayClass const right); + +/*! + * \brief Converts a turn angle into a turn direction. + * \note lowerBounds is a table of pairs: an angle and a direction. + * lowerBounds shall be sorted by the first parameter (angle) from big angles to small angles. + * These angles should be measured in degrees and should belong to the range [-180; 180]. + * The second paramer (angle) shall belong to the range [-180; 180] and is measured in degrees. + */ +template +T FindDirectionByAngle(std::vector> const & lowerBounds, double const angle); + +CarDirection InvertDirection(CarDirection const dir); + +/*! + * \param angle is an angle of a turn. It belongs to a range [-180, 180]. + * \return correct direction if the route follows along the rightmost possible way. + */ +CarDirection RightmostDirection(double const angle); +CarDirection LeftmostDirection(double const angle); + +/*! + * \param angle is an angle of a turn. It belongs to a range [-180, 180]. + * \return correct direction if the route follows not along one of two outermost ways + * or if there is only one possible way. + */ +CarDirection IntermediateDirection(double const angle); + +PedestrianDirection IntermediateDirectionPedestrian(double const angle); + +double CalcEstimatedTimeToPass(double const distanceMeters, ftypes::HighwayClass const highwayClass); + +/// \returns true if |path| is loop connected to the PartOfReal segments. +bool PathIsFakeLoop(RouteJunctions const & path); + +// Returns distance in meters between |junctions[start]| and |junctions[end]|. +double CalcRouteDistanceM(RouteJunctions const & junctions, uint32_t start, uint32_t end); + +/*! + * \brief Index of point in TUnpackedPathSegments. |m_segmentIndex| is a zero based index in vector + * TUnpackedPathSegments. |m_pathIndex| in a zero based index in LoadedPathSegment::m_path. + */ +struct RoutePointIndex +{ + std::size_t m_segmentIndex = 0; + std::size_t m_pathIndex = 0; + + bool operator==(RoutePointIndex const & index) const; +}; + +std::string DebugPrint(RoutePointIndex const & index); + +RoutePointIndex GetFirstOutgoingPointIndex(size_t const outgoingSegmentIndex); + +RoutePointIndex GetLastIngoingPointIndex(TUnpackedPathSegments const & segments, size_t const outgoingSegmentIndex); + +double CalcOneSegmentTurnAngle(TurnInfo const & turnInfo); +double CalcPathTurnAngle(LoadedPathSegment const & segment, size_t const pathIndex); + +m2::PointD GetPointByIndex(TUnpackedPathSegments const & segments, RoutePointIndex const & index); + +} // namespace turns +} // namespace routing diff --git a/third_party/organicmaps-routing/shim/base/assert.hpp b/third_party/organicmaps-routing/shim/base/assert.hpp new file mode 100644 index 0000000..f06d8e6 --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/assert.hpp @@ -0,0 +1,48 @@ +// Shim for Organic Maps base/assert.hpp (junction lab host build). +// ASSERT* follow OM release builds: compiled out, arguments not evaluated. +// CHECK* stay active but throw omaps_shim::CheckFailed instead of aborting, +// so one bad route does not kill the lab tool. +#pragma once + +#include +#include +#include + +namespace omaps_shim +{ +struct CheckFailed : std::runtime_error +{ + using std::runtime_error::runtime_error; +}; + +[[noreturn]] inline void FailCheck(char const * file, int line, char const * what) +{ + std::ostringstream out; + out << "CHECK failed " << file << ":" << line << ": " << what; + throw CheckFailed(out.str()); +} +} // namespace omaps_shim + +#define ASSERT(X, msg) ((void)0) +#define ASSERT_EQUAL(X, Y, msg) ((void)0) +#define ASSERT_NOT_EQUAL(X, Y, msg) ((void)0) +#define ASSERT_LESS(X, Y, msg) ((void)0) +#define ASSERT_LESS_OR_EQUAL(X, Y, msg) ((void)0) +#define ASSERT_GREATER(X, Y, msg) ((void)0) +#define ASSERT_GREATER_OR_EQUAL(X, Y, msg) ((void)0) +#define ASSERT_FAIL(msg) ((void)0) + +#define CHECK(X, msg) \ + do \ + { \ + if (!(X)) \ + ::omaps_shim::FailCheck(__FILE__, __LINE__, #X); \ + } \ + while (false) +#define CHECK_EQUAL(X, Y, msg) CHECK((X) == (Y), msg) +#define CHECK_NOT_EQUAL(X, Y, msg) CHECK((X) != (Y), msg) +#define CHECK_LESS(X, Y, msg) CHECK((X) < (Y), msg) +#define CHECK_LESS_OR_EQUAL(X, Y, msg) CHECK((X) <= (Y), msg) +#define CHECK_GREATER(X, Y, msg) CHECK((X) > (Y), msg) +#define CHECK_GREATER_OR_EQUAL(X, Y, msg) CHECK((X) >= (Y), msg) +#define UNREACHABLE() ::omaps_shim::FailCheck(__FILE__, __LINE__, "unreachable") diff --git a/third_party/organicmaps-routing/shim/base/internal/message.hpp b/third_party/organicmaps-routing/shim/base/internal/message.hpp new file mode 100644 index 0000000..576137e --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/internal/message.hpp @@ -0,0 +1,17 @@ +// Shim for Organic Maps base/internal/message.hpp: DebugPrint for std::vector. +#pragma once + +#include +#include +#include + +template +std::string DebugPrint(std::vector const & v) +{ + std::ostringstream out; + out << "["; + for (size_t i = 0; i < v.size(); ++i) + out << (i ? ", " : "") << DebugPrint(v[i]); + out << "]"; + return out.str(); +} diff --git a/third_party/organicmaps-routing/shim/base/logging.hpp b/third_party/organicmaps-routing/shim/base/logging.hpp new file mode 100644 index 0000000..c0a36e3 --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/logging.hpp @@ -0,0 +1,34 @@ +// Shim for Organic Maps base/logging.hpp. LOG(LWARNING/LERROR, (...)) prints only the +// source location to stderr, and only when JUNCTION_LAB_OMAPS_LOG is set; the message +// arguments are not evaluated. LDEBUG/LINFO are dropped. +#pragma once + +#include +#include + +namespace omaps_shim +{ +enum LogLevel +{ + LDEBUG, + LINFO, + LWARNING, + LERROR, + LCRITICAL +}; + +inline void Log(LogLevel level, char const * file, int line) +{ + static bool const enabled = std::getenv("JUNCTION_LAB_OMAPS_LOG") != nullptr; + if (enabled && level >= LWARNING) + std::fprintf(stderr, "omaps %s %s:%d\n", level == LWARNING ? "warning" : "error", file, line); +} +} // namespace omaps_shim + +using omaps_shim::LCRITICAL; +using omaps_shim::LDEBUG; +using omaps_shim::LERROR; +using omaps_shim::LINFO; +using omaps_shim::LWARNING; + +#define LOG(level, msg) ::omaps_shim::Log(level, __FILE__, __LINE__) diff --git a/third_party/organicmaps-routing/shim/base/math.hpp b/third_party/organicmaps-routing/shim/base/math.hpp new file mode 100644 index 0000000..401130f --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/math.hpp @@ -0,0 +1,53 @@ +// Shim for the parts of Organic Maps base/math.hpp the turn generator uses +// (same formulas as upstream). +#pragma once + +#include "base/assert.hpp" +#include "base/logging.hpp" +#include "base/stl_helpers.hpp" + +#include +#include + +namespace math +{ +double constexpr pi = 3.14159265358979323846; +double constexpr pi2 = pi / 2.0; +double constexpr pi4 = pi / 4.0; + +template +T DegToRad(T deg) +{ + return deg * pi / 180.0; +} + +template +T RadToDeg(T rad) +{ + return rad * 180.0 / pi; +} + +template +T Clamp(T x, T xmin, T xmax) +{ + return std::min(std::max(x, xmin), xmax); +} + +template +bool Between(T a, T b, T x) +{ + return a <= x && x <= b; +} + +template +T Pow2(T x) +{ + return x * x; +} +} // namespace math + +template +bool AlmostEqualAbs(Float x, Float y, Float eps) +{ + return std::fabs(x - y) < eps; +} diff --git a/third_party/organicmaps-routing/shim/base/stl_helpers.hpp b/third_party/organicmaps-routing/shim/base/stl_helpers.hpp new file mode 100644 index 0000000..f79d5c5 --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/stl_helpers.hpp @@ -0,0 +1,31 @@ +// Shim for base::LessBy / base::EqualsBy (Organic Maps base/stl_helpers.hpp). +#pragma once + +namespace base +{ +template +struct LessByField +{ + T C::*m_field; + bool operator()(C const & l, C const & r) const { return l.*m_field < r.*m_field; } +}; + +template +struct EqualsByField +{ + T C::*m_field; + bool operator()(C const & l, C const & r) const { return l.*m_field == r.*m_field; } +}; + +template +LessByField LessBy(T C::*p) +{ + return {p}; +} + +template +EqualsByField EqualsBy(T C::*p) +{ + return {p}; +} +} // namespace base diff --git a/third_party/organicmaps-routing/shim/base/string_utils.hpp b/third_party/organicmaps-routing/shim/base/string_utils.hpp new file mode 100644 index 0000000..5789bf2 --- /dev/null +++ b/third_party/organicmaps-routing/shim/base/string_utils.hpp @@ -0,0 +1,15 @@ +// Shim for the two helpers lanes_parser.cpp uses from Organic Maps base/string_utils.hpp. +#pragma once + +namespace strings +{ +inline bool IsASCIISpace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; +} + +inline char AsciiToLower(char c) +{ + return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; +} +} // namespace strings diff --git a/third_party/organicmaps-routing/shim/geometry/angles.hpp b/third_party/organicmaps-routing/shim/geometry/angles.hpp new file mode 100644 index 0000000..eb8c761 --- /dev/null +++ b/third_party/organicmaps-routing/shim/geometry/angles.hpp @@ -0,0 +1,28 @@ +// Shim for Organic Maps geometry/angles.hpp: AngleTo and TwoVectorsAngle (upstream code). +#pragma once + +#include "base/math.hpp" +#include "geometry/point2d.hpp" + +#include + +namespace ang +{ +template +T AngleTo(m2::Point const & p1, m2::Point const & p2) +{ + return std::atan2(p2.y - p1.y, p2.x - p1.x); +} + +/// Returns an angle from vector [p, p1] to vector [p, p2]. A counterclockwise rotation. +/// Angle is in range [0, 2 * pi] +template +T TwoVectorsAngle(m2::Point const & p, m2::Point const & p1, m2::Point const & p2) +{ + // Each finite AngleTo() result is in [-pi, pi], so one period normalizes a negative difference. + T a = ang::AngleTo(p, p2) - ang::AngleTo(p, p1); + if (a < 0) + a += 2.0 * math::pi; + return a; +} +} // namespace ang diff --git a/third_party/organicmaps-routing/shim/geometry/mercator.hpp b/third_party/organicmaps-routing/shim/geometry/mercator.hpp new file mode 100644 index 0000000..283b78f --- /dev/null +++ b/third_party/organicmaps-routing/shim/geometry/mercator.hpp @@ -0,0 +1,71 @@ +// Shim for Organic Maps geometry/mercator.hpp + distance_on_sphere: FromLatLon, +// ToLatLon and DistanceOnEarth with the upstream formulas (X = lon in degrees, +// Y = mercator latitude in degrees, Earth radius 6378000 m). +#pragma once + +#include "base/math.hpp" +#include "geometry/point2d.hpp" + +#include +#include + +namespace ms +{ +double constexpr kEarthRadiusMeters = 6378000.0; + +struct LatLon +{ + double m_lat = 0.0; + double m_lon = 0.0; +}; + +inline double DistanceOnSphere(double lat1Deg, double lon1Deg, double lat2Deg, double lon2Deg) +{ + double const lat1 = math::DegToRad(lat1Deg); + double const lat2 = math::DegToRad(lat2Deg); + double const dlat = std::sin((lat2 - lat1) * 0.5); + double const dlon = std::sin((math::DegToRad(lon2Deg) - math::DegToRad(lon1Deg)) * 0.5); + double const y = dlat * dlat + dlon * dlon * std::cos(lat1) * std::cos(lat2); + return 2.0 * std::atan2(std::sqrt(y), std::sqrt(std::max(0.0, 1.0 - y))); +} + +inline double DistanceOnEarth(LatLon const & ll1, LatLon const & ll2) +{ + return kEarthRadiusMeters * DistanceOnSphere(ll1.m_lat, ll1.m_lon, ll2.m_lat, ll2.m_lon); +} +} // namespace ms + +namespace mercator +{ +inline double ClampY(double d) +{ + return math::Clamp(d, -180.0, 180.0); +} + +inline double YToLat(double y) +{ + return math::RadToDeg(2.0 * std::atan(std::tanh(0.5 * math::DegToRad(y)))); +} + +inline double LatToY(double lat) +{ + double const sinx = std::sin(math::DegToRad(math::Clamp(lat, -86.0, 86.0))); + double const res = math::RadToDeg(0.5 * std::log((1.0 + sinx) / (1.0 - sinx))); + return ClampY(res); +} + +inline m2::PointD FromLatLon(double lat, double lon) +{ + return m2::PointD(lon, LatToY(lat)); +} + +inline ms::LatLon ToLatLon(m2::PointD const & point) +{ + return {YToLat(point.y), point.x}; +} + +inline double DistanceOnEarth(m2::PointD const & p1, m2::PointD const & p2) +{ + return ms::DistanceOnEarth(ToLatLon(p1), ToLatLon(p2)); +} +} // namespace mercator diff --git a/third_party/organicmaps-routing/shim/geometry/point2d.hpp b/third_party/organicmaps-routing/shim/geometry/point2d.hpp new file mode 100644 index 0000000..4c02970 --- /dev/null +++ b/third_party/organicmaps-routing/shim/geometry/point2d.hpp @@ -0,0 +1,55 @@ +// Shim for Organic Maps geometry/point2d.hpp: the subset of m2::Point the turn +// generator uses (same operators and comparisons as upstream). +#pragma once + +#include +#include +#include + +namespace m2 +{ +template +class Point +{ +public: + using value_type = T; + + T x, y; + + constexpr Point() : x(T()), y(T()) {} + constexpr Point(T x_, T y_) : x(x_), y(y_) {} + + static Point Zero() { return Point(0, 0); } + + bool EqualDxDy(Point const & p, T eps) const { return ((std::fabs(x - p.x) < eps) && (std::fabs(y - p.y) < eps)); } + T SquaredLength(Point const & p) const { return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y); } + double Length(Point const & p) const { return std::sqrt(SquaredLength(p)); } + + bool operator==(Point const & p) const { return x == p.x && y == p.y; } + bool operator!=(Point const & p) const { return !(*this == p); } + Point operator+(Point const & pt) const { return Point(x + pt.x, y + pt.y); } + Point operator-(Point const & pt) const { return Point(x - pt.x, y - pt.y); } + Point operator-() const { return Point(-x, -y); } + Point operator*(T scale) const { return Point(x * scale, y * scale); } + Point operator/(T scale) const { return Point(x / scale, y / scale); } +}; + +template +bool operator<(Point const & l, Point const & r) +{ + if (l.x != r.x) + return l.x < r.x; + return l.y < r.y; +} + +using PointD = Point; + +template +std::string DebugPrint(Point const & p) +{ + std::ostringstream out; + out.precision(20); + out << "m2::Point(" << p.x << ", " << p.y << ")"; + return out.str(); +} +} // namespace m2 diff --git a/third_party/organicmaps-routing/shim/geometry/point_with_altitude.hpp b/third_party/organicmaps-routing/shim/geometry/point_with_altitude.hpp new file mode 100644 index 0000000..3e63d0c --- /dev/null +++ b/third_party/organicmaps-routing/shim/geometry/point_with_altitude.hpp @@ -0,0 +1,47 @@ +// Shim for Organic Maps geometry/point_with_altitude.hpp (altitude is always 0 here). +#pragma once + +#include "geometry/point2d.hpp" + +#include +#include +#include + +namespace geometry +{ +using Altitude = int16_t; +Altitude constexpr kInvalidAltitude = std::numeric_limits::min(); +Altitude constexpr kDefaultAltitudeMeters = 0; + +class PointWithAltitude +{ +public: + PointWithAltitude() = default; + PointWithAltitude(m2::PointD const & point, Altitude altitude = kDefaultAltitudeMeters) + : m_point(point) + , m_altitude(altitude) + {} + operator m2::PointD() const { return m_point; } + + bool operator==(PointWithAltitude const & r) const { return m_point == r.m_point && m_altitude == r.m_altitude; } + bool operator!=(PointWithAltitude const & r) const { return !(*this == r); } + bool operator<(PointWithAltitude const & r) const + { + if (m_point != r.m_point) + return m_point < r.m_point; + return m_altitude < r.m_altitude; + } + + m2::PointD const & GetPoint() const { return m_point; } + Altitude GetAltitude() const { return m_altitude; } + +private: + m2::PointD m_point; + Altitude m_altitude = kDefaultAltitudeMeters; +}; + +inline std::string DebugPrint(PointWithAltitude const & p) +{ + return "PointWithAltitude{" + m2::DebugPrint(p.GetPoint()) + "}"; +} +} // namespace geometry diff --git a/third_party/organicmaps-routing/shim/indexer/feature_decl.hpp b/third_party/organicmaps-routing/shim/indexer/feature_decl.hpp new file mode 100644 index 0000000..743e4ba --- /dev/null +++ b/third_party/organicmaps-routing/shim/indexer/feature_decl.hpp @@ -0,0 +1,32 @@ +// Shim for Organic Maps indexer/feature_decl.hpp. m_index is the adapter's dense +// number for an OsmAnd road id; m_mwmId is 0 for real roads and -1 (invalid) for +// the fake start/finish edges. +#pragma once + +#include +#include +#include +#include + +struct FeatureID +{ + FeatureID() = default; + FeatureID(int mwmId, std::uint32_t index) : m_mwmId(mwmId), m_index(index) {} + + bool IsValid() const { return m_mwmId >= 0; } + std::string GetMwmName() const { return "osmand"; } + + bool operator==(FeatureID const & r) const { return m_mwmId == r.m_mwmId && m_index == r.m_index; } + bool operator!=(FeatureID const & r) const { return !(*this == r); } + bool operator<(FeatureID const & r) const { return std::tie(m_mwmId, m_index) < std::tie(r.m_mwmId, r.m_index); } + + int m_mwmId = -1; + std::uint32_t m_index = 0; +}; + +inline std::string DebugPrint(FeatureID const & id) +{ + std::ostringstream out; + out << "{ " << id.m_mwmId << ", " << id.m_index << " }"; + return out.str(); +} diff --git a/third_party/organicmaps-routing/shim/indexer/ftypes_matcher.hpp b/third_party/organicmaps-routing/shim/indexer/ftypes_matcher.hpp new file mode 100644 index 0000000..b26cd5c --- /dev/null +++ b/third_party/organicmaps-routing/shim/indexer/ftypes_matcher.hpp @@ -0,0 +1,33 @@ +// Shim for Organic Maps indexer/ftypes_matcher.hpp: only HighwayClass (same enum, +// same order as upstream). The adapter maps OsmAnd highway tags onto it the way +// ftypes::GetHighwayClass maps OM types (see omaps_adapter.cpp). +#pragma once + +#include + +namespace ftypes +{ +enum class HighwayClass +{ + Undefined = 0, // There has not been any attempt of calculating HighwayClass. + Trunk, + Primary, + Secondary, + Tertiary, + LivingStreet, + Service, + // OSM highway=service type is widely used even for _significant_ roads. + // Adding a new type to distinguish mapped driveway or parking_aisle. + ServiceMinor, + Pedestrian, + Transported, // Vehicles are transported by train or ferry. + Count // This value is used for internals only. +}; + +inline std::string DebugPrint(HighwayClass const cls) +{ + static char const * const names[] = {"Undefined", "Trunk", "Primary", "Secondary", "Tertiary", "LivingStreet", + "Service", "ServiceMinor", "Pedestrian", "Transported", "Count"}; + return std::string{"[ "} + names[static_cast(cls)] + " ]"; +} +} // namespace ftypes diff --git a/third_party/organicmaps-routing/shim/platform/country_file.hpp b/third_party/organicmaps-routing/shim/platform/country_file.hpp new file mode 100644 index 0000000..586ee02 --- /dev/null +++ b/third_party/organicmaps-routing/shim/platform/country_file.hpp @@ -0,0 +1,18 @@ +// Shim for platform::CountryFile: the junction lab has a single "mwm" (all OBF files). +#pragma once + +#include +#include + +namespace platform +{ +class CountryFile +{ +public: + explicit CountryFile(std::string name) : m_name(std::move(name)) {} + std::string const & GetName() const { return m_name; } + +private: + std::string m_name; +}; +} // namespace platform diff --git a/third_party/organicmaps-routing/shim/platform/measurement_utils.hpp b/third_party/organicmaps-routing/shim/platform/measurement_utils.hpp new file mode 100644 index 0000000..14c9520 --- /dev/null +++ b/third_party/organicmaps-routing/shim/platform/measurement_utils.hpp @@ -0,0 +1,10 @@ +// Shim for Organic Maps platform/measurement_utils.hpp (KmphToMps only). +#pragma once + +namespace measurement_utils +{ +inline double KmphToMps(double kmph) +{ + return kmph * 1000.0 / 3600.0; +} +} // namespace measurement_utils diff --git a/third_party/organicmaps-routing/shim/routing/route.hpp b/third_party/organicmaps-routing/shim/routing/route.hpp new file mode 100644 index 0000000..8963bf9 --- /dev/null +++ b/third_party/organicmaps-routing/shim/routing/route.hpp @@ -0,0 +1,125 @@ +// Trimmed Organic Maps routing/route.hpp + route.cpp: RouteJunctions and the parts of +// RouteSegment the turn generator touches (turn item, junction, road name info, +// IsSegregatedTurn, MergeLanes). Speed limits, traffic, transit, cameras and +// distances/times are removed. The kept member functions are copied unchanged. +#pragma once + +#include "routing/lanes/lane_info.hpp" +#include "routing/routing_settings.hpp" +#include "routing/segment.hpp" +#include "routing/turns.hpp" + +#include "indexer/feature_decl.hpp" + +#include "geometry/point_with_altitude.hpp" + +#include "base/assert.hpp" +#include "base/math.hpp" + +#include +#include +#include + +namespace routing +{ +using RouteJunctions = std::vector; + +class RouteSegment final +{ +public: + struct RoadNameInfo + { + FeatureID m_mwmId; + // This is for street/road. |m_ref| |m_name|. + std::string m_name; // E.g "Johnson Ave.". + std::string m_destination_ref; // Number of next road, e.g. "CA 85", Sometimes "CA 85 South". Usually match |m_ref| + // of next main road. + // This is for 1st segment of link after junction. Exit |junction_ref| to |m_destination_ref| for |m_destination|. + std::string m_junction_ref; // Number of junction e.g. "398B". + std::string m_destination; // E.g. "Cupertino". + std::string m_ref; // Number of street/road e.g. "CA 85". + bool m_isLink = false; + + RoadNameInfo() = default; + RoadNameInfo(std::string name) : m_name(std::move(name)) {} + + void ClearUselessStringsForTailSegments() + { + // Keep 'name' since it is used in turns comparison. + m_destination_ref.clear(); + m_junction_ref.clear(); + m_destination.clear(); + m_ref.clear(); + } + + bool HasBasicTextInfo() const { return !m_ref.empty() || !m_name.empty(); } + bool HasExitInfo() const { return m_isLink || HasExitTextInfo(); } + bool HasExitTextInfo() const + { + return !m_junction_ref.empty() || !m_destination_ref.empty() || !m_destination.empty(); + } + bool empty() const + { + return m_name.empty() && m_ref.empty() && m_junction_ref.empty() && m_destination_ref.empty() && + m_destination.empty(); + } + + bool operator==(RoadNameInfo const & rni) const + { + return m_name == rni.m_name && m_ref == rni.m_ref && m_junction_ref == rni.m_junction_ref && + m_destination_ref == rni.m_destination_ref && m_destination == rni.m_destination; + } + }; + + RouteSegment(Segment const & segment, turns::TurnItem const & turn, geometry::PointWithAltitude const & junction, + RoadNameInfo const & roadNameInfo) + : m_segment(segment) + , m_turn(turn) + , m_junction(junction) + , m_roadNameInfo(roadNameInfo) + {} + + void ClearTurn() + { + m_turn.m_turn = turns::CarDirection::None; + m_turn.m_pedestrianTurn = turns::PedestrianDirection::None; + } + + void SetTurnExits(uint32_t exitNum) { m_turn.m_exitNum = exitNum; } + + turns::lanes::LanesInfo & GetTurnLanes() { return m_turn.m_lanes; } + + Segment const & GetSegment() const { return m_segment; } + geometry::PointWithAltitude const & GetJunction() const { return m_junction; } + RoadNameInfo const & GetRoadNameInfo() const { return m_roadNameInfo; } + turns::TurnItem const & GetTurn() const { return m_turn; } + void ClearTurnLanes() { m_turn.m_lanes.clear(); } + + /// Is 'from' a segregated turn before this turn. + bool IsSegregatedTurn(RouteSegment const & from) const + { + // Treat 'from' -> this turn is segregated candidate when (distance is checked by a caller): + // - "st A" -> "st A" or + // - Any -> unnamed link + + if (!m_roadNameInfo.m_name.empty()) + return m_roadNameInfo.m_name == from.m_roadNameInfo.m_name; + else + return m_roadNameInfo.m_isLink; + } + + /// Merge lanes info from segregated 'from' into this if needed. + void MergeLanes(RouteSegment & from) + { + /// @todo Keep 'from' lanes now. Probably, can move and clear. + if (m_turn.m_lanes.empty()) + m_turn.m_lanes = from.m_turn.m_lanes; + } + +private: + Segment m_segment; + turns::TurnItem m_turn; + geometry::PointWithAltitude m_junction; + RoadNameInfo m_roadNameInfo; +}; +} // namespace routing diff --git a/third_party/organicmaps-routing/shim/routing/segment.hpp b/third_party/organicmaps-routing/shim/routing/segment.hpp new file mode 100644 index 0000000..b267bf0 --- /dev/null +++ b/third_party/organicmaps-routing/shim/routing/segment.hpp @@ -0,0 +1,76 @@ +// Trimmed Organic Maps routing/segment.hpp + segment.cpp: class Segment only +// (no RoadPoint / RouteWeight / SegmentEdge). Member functions copied unchanged. +#pragma once + +#include "routing_common/num_mwm_id.hpp" + +#include +#include +#include + +namespace routing +{ +// This is directed road segment used as vertex in index graph. +class Segment final +{ +public: + Segment() = default; + + constexpr Segment(NumMwmId mwmId, uint32_t featureId, uint32_t segmentIdx, bool forward) + : m_featureId(featureId) + , m_segmentIdx(segmentIdx) + , m_mwmId(mwmId) + , m_forward(forward) + {} + + NumMwmId GetMwmId() const { return m_mwmId; } + uint32_t GetFeatureId() const { return m_featureId; } + uint32_t GetSegmentIdx() const { return m_segmentIdx; } + bool IsForward() const { return m_forward; } + + uint32_t GetPointId(bool front) const { return m_forward == front ? m_segmentIdx + 1 : m_segmentIdx; } + uint32_t GetMinPointId() const { return m_segmentIdx; } + uint32_t GetMaxPointId() const { return m_segmentIdx + 1; } + + bool operator<(Segment const & seg) const + { + if (m_featureId != seg.m_featureId) + return m_featureId < seg.m_featureId; + if (m_segmentIdx != seg.m_segmentIdx) + return m_segmentIdx < seg.m_segmentIdx; + if (m_mwmId != seg.m_mwmId) + return m_mwmId < seg.m_mwmId; + return m_forward < seg.m_forward; + } + + bool operator==(Segment const & seg) const + { + return m_featureId == seg.m_featureId && m_segmentIdx == seg.m_segmentIdx && m_mwmId == seg.m_mwmId && + m_forward == seg.m_forward; + } + bool operator!=(Segment const & seg) const { return !(*this == seg); } + + bool IsInverse(Segment const & seg) const + { + return m_featureId == seg.m_featureId && m_segmentIdx == seg.m_segmentIdx && m_mwmId == seg.m_mwmId && + m_forward != seg.m_forward; + } + Segment GetReversed() const { return {m_mwmId, m_featureId, m_segmentIdx, !m_forward}; } + + void Next(bool forward) { forward ? ++m_segmentIdx : --m_segmentIdx; } + +private: + uint32_t m_featureId = 0; + uint32_t m_segmentIdx = 0; + NumMwmId m_mwmId = kFakeNumMwmId; + bool m_forward = false; +}; + +inline std::string DebugPrint(Segment const & segment) +{ + std::ostringstream out; + out << std::boolalpha << "Segment(" << segment.GetMwmId() << ", " << segment.GetFeatureId() << ", " + << segment.GetSegmentIdx() << ", " << segment.IsForward() << ")"; + return out.str(); +} +} // namespace routing diff --git a/third_party/organicmaps-routing/shim/routing/vehicle_mask.hpp b/third_party/organicmaps-routing/shim/routing/vehicle_mask.hpp new file mode 100644 index 0000000..ad30d1a --- /dev/null +++ b/third_party/organicmaps-routing/shim/routing/vehicle_mask.hpp @@ -0,0 +1,29 @@ +// Shim for Organic Maps routing/vehicle_mask.hpp (VehicleType only). +#pragma once + +#include + +namespace routing +{ +enum class VehicleType +{ + Pedestrian = 0, + Bicycle = 1, + Car = 2, + Transit = 3, + Count = 4 +}; + +inline std::string DebugPrint(VehicleType type) +{ + switch (type) + { + case VehicleType::Pedestrian: return "Pedestrian"; + case VehicleType::Bicycle: return "Bicycle"; + case VehicleType::Car: return "Car"; + case VehicleType::Transit: return "Transit"; + case VehicleType::Count: return "Count"; + } + return "?"; +} +} // namespace routing diff --git a/third_party/organicmaps-routing/shim/routing_common/num_mwm_id.hpp b/third_party/organicmaps-routing/shim/routing_common/num_mwm_id.hpp new file mode 100644 index 0000000..cd8fca6 --- /dev/null +++ b/third_party/organicmaps-routing/shim/routing_common/num_mwm_id.hpp @@ -0,0 +1,19 @@ +// Shim for Organic Maps routing_common/num_mwm_id.hpp. Every OsmAnd road is in mwm 0. +#pragma once + +#include "platform/country_file.hpp" + +#include +#include + +namespace routing +{ +using NumMwmId = std::uint16_t; +NumMwmId constexpr kFakeNumMwmId = std::numeric_limits::max(); + +class NumMwmIds +{ +public: + NumMwmId GetId(platform::CountryFile const &) const { return 0; } +}; +} // namespace routing diff --git a/third_party/organicmaps-routing/sources.cmake b/third_party/organicmaps-routing/sources.cmake new file mode 100644 index 0000000..a2e4e54 --- /dev/null +++ b/third_party/organicmaps-routing/sources.cmake @@ -0,0 +1,18 @@ +# Organic Maps' car turn generator (Apache-2.0, see README.md): the sources and +# include directories, for the backend (backends/osmand) and the host junction lab +# (tools/junction_lab/host_osmand). The shim directory stands in for OM's base, +# geometry, indexer and platform libraries; keep it private to the targets that +# compile these files. +set(ONC_ORGANICMAPS_ROOT ${CMAKE_CURRENT_LIST_DIR}) +set(ONC_ORGANICMAPS_SOURCES + ${ONC_ORGANICMAPS_ROOT}/routing/car_directions.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/directions_engine.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/routing_settings.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/turns.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/turns_generator.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/turns_generator_utils.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/lanes/lane_info.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/lanes/lane_way.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/lanes/lanes_parser.cpp + ${ONC_ORGANICMAPS_ROOT}/routing/lanes/lanes_recommendation.cpp) +set(ONC_ORGANICMAPS_INCLUDES ${ONC_ORGANICMAPS_ROOT} ${ONC_ORGANICMAPS_ROOT}/shim) diff --git a/tools/junction_lab/build.sh b/tools/junction_lab/build.sh new file mode 100755 index 0000000..730ebec --- /dev/null +++ b/tools/junction_lab/build.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Builds the junction lab (host OsmAnd router + junction_lab_tool + junction_probe) +# into build/junction_lab/. First build about 3 minutes. +# OSMAND_QNX_ROOT: the OsmAnd QNX build tree (its source/ is compiled for the host); +# default the directory that holds this repository, as for the radio build (set it +# from a linked worktree). +set -e +root=$(cd "$(dirname "$0")/../.." && pwd) +OSMAND_QNX_ROOT=${OSMAND_QNX_ROOT:-$(cd "$root/.." && pwd)/osmand-qnx-build} +export OSMAND_QNX_ROOT +cmake -S "$root/tools/junction_lab/host_osmand" -B "$root/build/junction_lab/host_osmand" \ + -DCMAKE_BUILD_TYPE=Release >/dev/null +cmake --build "$root/build/junction_lab/host_osmand" -j "$(nproc)" --target junction_lab_tool junction_probe +cp "$OSMAND_QNX_ROOT/source/resources/routing/routing.xml" "$root/build/junction_lab/routing.xml" diff --git a/tools/junction_lab/cases.tsv b/tools/junction_lab/cases.tsv new file mode 100644 index 0000000..b3fe30f --- /dev/null +++ b/tools/junction_lab/cases.tsv @@ -0,0 +1,8 @@ +# Junction regression cases: python3 tools/junction_lab/junction_lab.py --check tools/junction_lab/cases.tsv +# FROM TO expected turns (Organic Maps directions, route order, arrival left out) why +# The expected list is what the operator checked; a change in it needs a look in the lab. +48.487870,34.936395 48.490011,34.945010 TurnLeft TurnRight Kamianske: left onto Панаса Мирного, right onto the link that merges onto Набережна Заводська; no slight left on the embankment (OsmAnd: invented lanes) +48.487081,34.941727 48.489282,34.937865 TurnRight UTurnLeft TurnSlightRight Kamianske: the exit right onto the link after the U-turn (OM's U-turn skipped it, fixed in car_directions.cpp) +48.4647,35.0462 48.5300,34.9500 TurnRight UTurnLeft ExitHighwayToRight ExitHighwayToRight TurnSlightRight TurnRight TurnRight Dnipro: overlapping OSM ways and a 0.3 m stub at 48.516022,34.999655 give no extra go-straight / left-then-right +50.4501,30.5234 50.4547,30.5238 TurnLeft TurnSlightLeft GoStraight TurnSlightRight TurnRight TurnRight UTurnLeft TurnSlightLeft TurnRight central Kyiv +48.428973,35.065269 48.410061,35.139341 TurnRight OsmAnd:RNDB3 TurnSlightLeft/keep_left TurnRight TurnSlightLeft/keep_left TurnRight TurnLeft GoStraight TurnLeft Dnipro, Набережна Перемоги: the road bears right, a ramp (tagged primary) leaves 9 degrees further right; OM tie-break slight left is keep left (48.410077,35.086365; also 48.41268,35.104355) diff --git a/tools/junction_lab/host_osmand/CMakeLists.txt b/tools/junction_lab/host_osmand/CMakeLists.txt new file mode 100644 index 0000000..1c4aafe --- /dev/null +++ b/tools/junction_lab/host_osmand/CMakeLists.txt @@ -0,0 +1,128 @@ +# Host (x86_64 Linux) build of OsmAnd core-legacy's routing subset: the real router and +# route preparation (turn types, attached roads) on local OBF maps. Debugging aid only. +# +# cmake -S tools/junction_lab/host_osmand -B build/junction_lab/host_osmand -DCMAKE_BUILD_TYPE=Release +# cmake --build build/junction_lab/host_osmand -j +# +# Outputs (in the build dir): libosmand_routing_host.a, libprotobuf_host.a, libexpat_host.a, +# route_bench_host (deploy/bench/route_bench.cpp + backends/osmand/ch_planner.cpp, unchanged). +cmake_minimum_required(VERSION 3.16) +project(osmand_routing_host C CXX) + +get_filename_component(ONC_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../.. ABSOLUTE) +# The OsmAnd source tree (read-only), as cmake/qnx-armv7.cmake finds the OsmAnd QNX +# build: $OSMAND_QNX_ROOT, else the directory that holds this repository (set it +# from a linked worktree). +if(DEFINED ENV{OSMAND_QNX_ROOT}) + set(_osmand_qnx_root $ENV{OSMAND_QNX_ROOT}) +else() + get_filename_component(_osmand_qnx_root ${ONC_ROOT}/../osmand-qnx-build ABSOLUTE) +endif() +set(OSMAND_SOURCE_ROOT ${_osmand_qnx_root}/source CACHE PATH "OsmAnd source tree (read-only)") + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +set(_legacy ${OSMAND_SOURCE_ROOT}/core-legacy/native) +set(_ext ${OSMAND_SOURCE_ROOT}/core/externals) +set(_pb ${_ext}/protobuf/upstream.patched/src/google/protobuf) + +# ---- protobuf 2.5 (same file list as core/externals/protobuf) ---------------------------- +add_library(protobuf_host STATIC + ${_pb}/descriptor.cc ${_pb}/descriptor_database.cc ${_pb}/descriptor.pb.cc + ${_pb}/dynamic_message.cc ${_pb}/extension_set.cc ${_pb}/extension_set_heavy.cc + ${_pb}/generated_message_reflection.cc ${_pb}/generated_message_util.cc ${_pb}/message.cc + ${_pb}/message_lite.cc ${_pb}/reflection_ops.cc ${_pb}/repeated_field.cc ${_pb}/service.cc + ${_pb}/text_format.cc ${_pb}/unknown_field_set.cc ${_pb}/wire_format.cc + ${_pb}/wire_format_lite.cc ${_pb}/io/coded_stream.cc ${_pb}/stubs/common.cc + ${_pb}/stubs/once.cc ${_pb}/stubs/atomicops_internals_x86_gcc.cc ${_pb}/stubs/stringprintf.cc + ${_pb}/stubs/structurally_valid.cc ${_pb}/stubs/strutil.cc ${_pb}/stubs/substitute.cc + ${_pb}/io/zero_copy_stream_impl.cc ${_pb}/io/printer.cc ${_pb}/io/tokenizer.cc + ${_pb}/io/zero_copy_stream_impl_lite.cc ${_pb}/io/zero_copy_stream.cc) +target_include_directories(protobuf_host PUBLIC ${_ext}/protobuf/upstream.patched/src + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/config) +target_compile_definitions(protobuf_host PRIVATE __OSMAND_DUMMY__) +target_compile_options(protobuf_host PRIVATE -w -O2) +set_target_properties(protobuf_host PROPERTIES CXX_STANDARD 11) + +# ---- expat ----------------------------------------------------------------------------- +add_library(expat_host STATIC + ${_ext}/expat/upstream.patched/lib/xmlparse.c ${_ext}/expat/upstream.patched/lib/xmlrole.c + ${_ext}/expat/upstream.patched/lib/xmltok.c) +target_include_directories(expat_host PUBLIC ${_ext}/expat/upstream.patched/lib + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/config) +target_compile_definitions(expat_host PRIVATE HAVE_EXPAT_CONFIG_H PUBLIC XML_STATIC) +target_compile_options(expat_host PRIVATE -w -O2) + +# ---- core-legacy routing --------------------------------------------------------------- +set(_s ${_legacy}/src) +add_library(osmand_routing_host STATIC + ${_s}/proto/OBF.pb.cc ${_s}/proto/osmand_index.pb.cc + ${_s}/openingHoursParser.cpp ${_s}/multipolygons.cpp ${_s}/common.cpp ${_s}/ElapsedTimer.cpp + ${_s}/routeTypeRule.cpp ${_s}/binaryRead.cpp ${_s}/binaryRoutePlanner.cpp + ${_s}/generalRouter.cpp ${_s}/turnType.cpp ${_s}/routeResultPreparation.cpp + ${_s}/routeSegmentResult.cpp ${_s}/routingConfiguration.cpp + ${_s}/precalculatedRouteDirection.cpp ${_s}/routePlannerFrontEnd.cpp ${_s}/routingContext.cpp + ${_s}/routeDataBundle.cpp ${_s}/routeDataResources.cpp ${_s}/routeCalculationProgress.cpp + ${_s}/renderRules.cpp ${_s}/hhRouteDataStructure.cpp ${_s}/hhRoutePlanner.cpp + ${_s}/NetworkDBPointRouteInfo.cpp ${_s}/roundaboutTurn.cpp + ${_s}/gpxRouteApproximation.cpp ${_s}/gpxMultiSegmentsApproximation.cpp + ${_s}/gpxSimplePointsMatchApproximation.cpp + ${_s}/transportRoutePlanner.cpp ${_s}/transportRoutingConfiguration.cpp + ${_s}/transportRouteResult.cpp ${_s}/transportRouteResultSegment.cpp + ${_s}/transportRouteSegment.cpp ${_s}/transportRoutingContext.cpp + ${_s}/transportRoutingObjects.cpp ${_s}/transportRouteStopsReader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/logging_stub.cpp ${CMAKE_CURRENT_SOURCE_DIR}/skia_stub.cpp) + +# What a consumer needs (shim first: replaces the Qt-based ). +set(OSMAND_HOST_INCLUDES + ${CMAKE_CURRENT_SOURCE_DIR}/shim + ${_legacy}/include ${_legacy}/src + ${_ext}/protobuf/upstream.patched/src + ${_ext}/boost/upstream.patched + ${_ext}/skia/upstream.patched ${_ext}/skia/upstream.patched/include/core + ${_ext}/skia/upstream.patched/include/effects ${_ext}/skia/upstream.patched/src/core + ${_ext}/expat/upstream.patched/lib + ${_ext}/harfbuzz/upstream.patched/src ${_ext}/freetype/upstream.patched/include) +set(OSMAND_HOST_DEFINES _HAS_C9X=1 _NO_CPP_INLINES=1 _HAS_GENERIC_TEMPLATES=0 + OSMAND_COMPILER_FAMILY_gcc OSMAND_TARGET_OS_linux OSMAND_TARGET_CPU_ARCH_x64 + OSMAND_TARGET_CPU_ARCH_FAMILY_x86 SK_SUPPORT_LEGACY_DRAWLOOPER SK_RELEASE) +target_include_directories(osmand_routing_host PUBLIC ${OSMAND_HOST_INCLUDES}) +target_compile_definitions(osmand_routing_host PUBLIC ${OSMAND_HOST_DEFINES}) +target_compile_options(osmand_routing_host PRIVATE -w -O2 -g) +find_package(Threads REQUIRED) +target_link_libraries(osmand_routing_host PUBLIC protobuf_host expat_host Threads::Threads) + +# ---- route_bench on the host ------------------------------------------------------------- +add_executable(route_bench_host ${ONC_ROOT}/deploy/bench/route_bench.cpp + ${ONC_ROOT}/backends/osmand/ch_planner.cpp ${CMAKE_CURRENT_SOURCE_DIR}/route_bench_host_main.cpp) +target_compile_options(route_bench_host PRIVATE -w -O2 -g) +target_link_libraries(route_bench_host PRIVATE osmand_routing_host ${CMAKE_DL_LIBS} m) + +# ---- junction lab (tools/junction_lab) --------------------------------------------------- +# The backend's manoeuvre and cluster code on top of the host router. +set(_backend ${ONC_ROOT}/backends/osmand) +# Organic Maps' car turn generator (third_party/organicmaps-routing, Apache-2.0) on the +# OsmAnd route, through the backend's own omaps_turns.cpp, as on the radio. +include(${ONC_ROOT}/third_party/organicmaps-routing/sources.cmake) +add_library(organicmaps_turns STATIC ${_backend}/omaps_turns.cpp ${ONC_ORGANICMAPS_SOURCES}) +target_include_directories(organicmaps_turns PRIVATE ${ONC_ORGANICMAPS_INCLUDES} ${_backend}) +target_compile_options(organicmaps_turns PRIVATE -O2 -g -w) +target_link_libraries(organicmaps_turns PRIVATE osmand_routing_host) + +add_executable(junction_lab_tool ${ONC_ROOT}/tools/junction_lab/junction_lab_tool.cpp + ${_backend}/route_maneuvers.cpp ${_backend}/junction_shape.cpp ${_backend}/cluster_payload.cpp) +target_include_directories(junction_lab_tool PRIVATE ${_backend} ${ONC_ROOT}/include) +target_compile_options(junction_lab_tool PRIVATE -O2 -g) +target_link_libraries(junction_lab_tool PRIVATE organicmaps_turns osmand_routing_host m) +set_target_properties(junction_lab_tool PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ONC_ROOT}/build/junction_lab) + +# The classifier alone, for edited angles (no router). +add_executable(junction_probe ${ONC_ROOT}/tools/junction_lab/junction_probe.cpp + ${_backend}/junction_shape.cpp ${_backend}/cluster_payload.cpp) +target_include_directories(junction_probe PRIVATE ${_backend} ${ONC_ROOT}/include) +set_target_properties(junction_probe PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ONC_ROOT}/build/junction_lab) diff --git a/tools/junction_lab/host_osmand/config/config.h b/tools/junction_lab/host_osmand/config/config.h new file mode 100644 index 0000000..a57e3d6 --- /dev/null +++ b/tools/junction_lab/host_osmand/config/config.h @@ -0,0 +1,28 @@ +/* protobuf 2.5 config for x86_64 Linux / glibc (hand-written, host only) */ +#define HASH_MAP_CLASS unordered_map +#define HASH_MAP_H +#define HASH_NAMESPACE std +#define HASH_SET_CLASS unordered_set +#define HASH_SET_H +#define HAVE_DLFCN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FTRUNCATE 1 +#define HAVE_HASH_MAP 1 +#define HAVE_HASH_SET 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_MEMSET 1 +#define HAVE_MKDIR 1 +#define HAVE_PTHREAD 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRCHR 1 +#define HAVE_STRERROR 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRTOL 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_UNISTD_H 1 +#define STDC_HEADERS 1 diff --git a/tools/junction_lab/host_osmand/config/expat_config.h b/tools/junction_lab/host_osmand/config/expat_config.h new file mode 100644 index 0000000..bb510c2 --- /dev/null +++ b/tools/junction_lab/host_osmand/config/expat_config.h @@ -0,0 +1,22 @@ +/* expat config for x86_64 Linux / glibc (hand-written, host only) */ +#define BYTEORDER 1234 +#define HAVE_BCOPY 1 +#define HAVE_DLFCN_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_GETPAGESIZE 1 +#define HAVE_GETRANDOM 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMORY_H 1 +#define HAVE_MMAP 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_UNISTD_H 1 +#define STDC_HEADERS 1 +#define XML_CONTEXT_BYTES 1024 +#define XML_DTD 1 +#define XML_NS 1 diff --git a/tools/junction_lab/host_osmand/logging_stub.cpp b/tools/junction_lab/host_osmand/logging_stub.cpp new file mode 100644 index 0000000..fa87e0d --- /dev/null +++ b/tools/junction_lab/host_osmand/logging_stub.cpp @@ -0,0 +1,29 @@ +// Host stub for OsmAnd::LogPrintf (core-legacy Logging.h). Errors always go to stderr; +// OSMAND_HOST_LOG=1 adds warnings, OSMAND_HOST_LOG=debug adds Info/Debug too. +#include "Logging.h" + +#include +#include +#include +#include + +namespace OsmAnd { +void LogPrintf(LogSeverityLevel level, const char* format, ...) +{ + static const char* env = std::getenv("OSMAND_HOST_LOG"); + const bool verbose = env && std::strcmp(env, "debug") == 0; + if (level != LogSeverityLevel::Error) { + if (!env) return; + if (level != LogSeverityLevel::Warning && !verbose) return; + } + const char* tag = level == LogSeverityLevel::Error ? "E" + : level == LogSeverityLevel::Warning ? "W" + : level == LogSeverityLevel::Info ? "I" : "D"; + std::fprintf(stderr, "[osmand %s] ", tag); + va_list args; + va_start(args, format); + std::vfprintf(stderr, format, args); + va_end(args); + std::fputc('\n', stderr); +} +} // namespace OsmAnd diff --git a/tools/junction_lab/host_osmand/route_bench_host_main.cpp b/tools/junction_lab/host_osmand/route_bench_host_main.cpp new file mode 100644 index 0000000..8507e0d --- /dev/null +++ b/tools/junction_lab/host_osmand/route_bench_host_main.cpp @@ -0,0 +1,7 @@ +// Host entry for deploy/bench/route_bench.cpp (on the radio route_bench_run dlopens it). +extern "C" int route_bench_main(int argc, char** argv); + +int main(int argc, char** argv) +{ + return route_bench_main(argc, argv); +} diff --git a/tools/junction_lab/host_osmand/shim/OsmAndCore/Logging.h b/tools/junction_lab/host_osmand/shim/OsmAndCore/Logging.h new file mode 100644 index 0000000..a02c58e --- /dev/null +++ b/tools/junction_lab/host_osmand/shim/OsmAndCore/Logging.h @@ -0,0 +1,5 @@ +// Host shim: Core's OsmAndCore/Logging.h needs Qt. Routing code only uses OsmAnd::LogPrintf and +// LogSeverityLevel, which core-legacy's Logging.h provides (implemented in logging_stub.cpp). +// Angle brackets so the include-path search finds core-legacy/native/include/Logging.h, not us. +#pragma once +#include diff --git a/tools/junction_lab/host_osmand/skia_stub.cpp b/tools/junction_lab/host_osmand/skia_stub.cpp new file mode 100644 index 0000000..d642217 --- /dev/null +++ b/tools/junction_lab/host_osmand/skia_stub.cpp @@ -0,0 +1,15 @@ +// Host stand-ins for the few out-of-line Skia functions the routing code reaches through +// SkRect.h inlines (quad_tree in commonOsmAndCore.h). Bodies copied from +// core/externals/skia/upstream.patched/src/core/SkRect.cpp, so behaviour is identical. +#include "SkRect.h" + +#include + +bool SkIRect::intersect(const SkIRect& a, const SkIRect& b) +{ + SkIRect tmp = {std::max(a.fLeft, b.fLeft), std::max(a.fTop, b.fTop), + std::min(a.fRight, b.fRight), std::min(a.fBottom, b.fBottom)}; + if (tmp.isEmpty()) return false; + *this = tmp; + return true; +} diff --git a/tools/junction_lab/index.html b/tools/junction_lab/index.html new file mode 100644 index 0000000..67b3ba9 --- /dev/null +++ b/tools/junction_lab/index.html @@ -0,0 +1,632 @@ + + + + + +Junction lab + + + + + +
+
+ +
+ + + diff --git a/tools/junction_lab/junction_lab.py b/tools/junction_lab/junction_lab.py new file mode 100755 index 0000000..ac3819a --- /dev/null +++ b/tools/junction_lab/junction_lab.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Junction lab: what the radio's cluster shows for a junction, on the host. + + python3 tools/junction_lab/junction_lab.py # http://localhost:8765 + python3 tools/junction_lab/junction_lab.py --route 50.4501,30.5234 50.4547,30.5238 + +Routes FROM -> TO with OsmAnd's router (host build, junction_lab_tool) and +shows each manoeuvre's cluster symbol, computed by the backend's own code. +Put FROM on the street you come from and TO on the street you leave by, a +little past the junction. The page also re-runs a manoeuvre's junction with +edited angles (junction_probe), to try the classifier without a route. + +Build first: tools/junction_lab/build.sh +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +BUILD = ROOT / "build" / "junction_lab" +# $OPEN_NAVICORE_MAPS, else osmand-maps/ukraine next to this repository. +DEFAULT_MAPS = Path(os.environ.get("OPEN_NAVICORE_MAPS", ROOT.parent / "osmand-maps" / "ukraine")) + +KINDS = {"straight", "left", "slight_left", "sharp_left", "right", "slight_right", + "sharp_right", "keep_left", "keep_right", "uturn", "roundabout", "arrive"} + + +class Router: + """One junction_lab_tool process (the maps stay open between routes).""" + + def __init__(self, tool: Path, maps: Path, routing_xml: Path): + self.process = subprocess.Popen( + [str(tool), str(maps), str(routing_xml)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True, encoding="utf-8", bufsize=1) + ready = self.process.stdout.readline() + if not ready: + raise SystemExit("junction_lab_tool exited (see its message above)") + self.lock = threading.Lock() + + def route(self, a: tuple[float, float], b: tuple[float, float]) -> dict: + with self.lock: + self.process.stdin.write(f"{a[0]} {a[1]} {b[0]} {b[1]}\n") + self.process.stdin.flush() + line = self.process.stdout.readline() + if not line: + return {"ok": False, "error": "junction_lab_tool exited"} + return json.loads(line) + + +def probe(params: dict[str, str]) -> dict: + kind = params.get("kind", "") + if kind not in KINDS: + return {"error": f"unknown kind {kind!r}"} + args = [str(BUILD / "junction_probe"), "--kind", kind, + "--route", str(float(params.get("route", "0"))), + "--arms=" + ",".join(str(float(a)) for a in params.get("arms", "").split(",") if a.strip()), + "--turn-angle", str(float(params.get("turn_angle", "0")))] + if params.get("lanes"): + args += ["--lanes", "".join(c for c in params["lanes"] if c in ".*")] + if params.get("left_side") == "1": + args.append("--left-side") + result = subprocess.run(args, capture_output=True, text=True, timeout=10) + if result.returncode != 0: + return {"error": result.stderr.strip()} + return json.loads(result.stdout) + + +def parse_point(text: str) -> tuple[float, float]: + lat, lon = (float(v) for v in text.replace(" ", "").split(",")) + return lat, lon + + +def make_handler(router: Router): + page = (HERE / "index.html").read_bytes() + + class Handler(BaseHTTPRequestHandler): + def send(self, code: int, body: bytes, kind: str) -> None: + self.send_response(code) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + url = urlparse(self.path) + params = {k: v[0] for k, v in parse_qs(url.query).items()} + try: + if url.path in ("/", "/index.html"): + self.send(200, page, "text/html; charset=utf-8") + return + if url.path == "/api/route": + result = router.route(parse_point(params["from"]), parse_point(params["to"])) + elif url.path == "/api/probe": + result = probe(params) + else: + self.send(404, b"not found", "text/plain") + return + except (KeyError, ValueError) as error: + result = {"ok": False, "error": f"bad request: {error}"} + self.send(200, json.dumps(result, ensure_ascii=False).encode(), "application/json") + + def log_message(self, *args) -> None: + pass + + return Handler + + +def describe(result: dict) -> str: + """The radio's manoeuvres (Organic Maps' turns) with their cluster symbols.""" + if not result.get("ok"): + return f"no route: {result.get('error')}" + if result.get("omaps_error"): + return f"Organic Maps failed (the radio shows no turns): {result['omaps_error']}" + lines = [] + for m in result.get("omaps", []): + j = m["junction"] + arms = ",".join(f"{a:.0f}" for a in j["branches"]) + lines.append( + f"{m['lat']:.6f},{m['lon']:.6f} {m['turn']:<20} kind={m['kind']} " + f"route={j['route_angle']:.0f} arms={arms or '-'}{'+' if j['truncated'] else ''} " + f"-> junction={m['junction_symbol']} turn_type={m['turn_type_symbol']} SYMBOL={m['symbol']}" + f" road={m['road']!r}") + return "\n".join(lines) or "route has no manoeuvres" + + +def check(router: Router, path: Path) -> int: + """Runs every case of a cases.tsv; returns the number that differ.""" + failed = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip() or line.startswith("#"): + continue + start, finish, expected, why = (line.split("\t") + ["", ""])[:4] + result = router.route(parse_point(start), parse_point(finish)) + # A token is OM's direction, or DIRECTION/kind to also pin the backend's + # manoeuvre kind (e.g. TurnSlightLeft/keep_left). + tokens = expected.split() + turns = result.get("omaps", []) if result.get("ok") else [] + got_tokens = [m["turn"] + ("/" + m["kind"] if i < len(tokens) and "/" in tokens[i] else "") + for i, m in enumerate(turns)] + got = " ".join(got_tokens) if result.get("ok") else "no route" + if result.get("omaps_error"): + got = "omaps_error: " + result["omaps_error"] + ok = got == " ".join(tokens) + failed += not ok + print(f"{'ok ' if ok else 'FAIL'} {start} {finish} {why}") + if not ok: + print(f" expected: {expected.strip()}\n got: {got}") + print(f"{failed} case(s) differ" if failed else "all cases match") + return failed + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--maps", type=Path, default=DEFAULT_MAPS, help="an .obf or a directory of them") + parser.add_argument("--routing-xml", type=Path, default=BUILD / "routing.xml") + parser.add_argument("--port", type=int, default=8765) + parser.add_argument("--route", nargs=2, metavar=("FROM", "TO"), help="print the manoeuvres and exit") + parser.add_argument("--check", type=Path, metavar="CASES", help="run a cases.tsv and exit (1 if any differ)") + args = parser.parse_args() + tool = BUILD / "junction_lab_tool" + if not tool.exists(): + print(f"{tool} missing: run tools/junction_lab/build.sh", file=sys.stderr) + return 1 + print(f"opening maps in {args.maps} ...", file=sys.stderr) + router = Router(tool, args.maps, args.routing_xml) + if args.route: + print(describe(router.route(parse_point(args.route[0]), parse_point(args.route[1])))) + return 0 + if args.check: + return 1 if check(router, args.check) else 0 + server = ThreadingHTTPServer(("127.0.0.1", args.port), make_handler(router)) + print(f"junction lab: http://localhost:{args.port}/", file=sys.stderr) + server.serve_forever() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/junction_lab/junction_lab_tool.cpp b/tools/junction_lab/junction_lab_tool.cpp new file mode 100644 index 0000000..98223dd --- /dev/null +++ b/tools/junction_lab/junction_lab_tool.cpp @@ -0,0 +1,376 @@ +// junction_lab_tool: routes with OsmAnd's router on the host and prints each +// manoeuvre as the radio would send it to the cluster. The manoeuvres come +// from the backend's own code (route_maneuvers.cpp, junction_shape.cpp, +// cluster_payload.cpp); only the router build differs (host, not QNX). +// +// junction_lab_tool MAPS ROUTING_XML +// +// MAPS is one .obf or a directory of them. Then one request per stdin line, +// "LAT1 LON1 LAT2 LON2", one JSON object per line on stdout. Plain A*: the +// worker's router for short routes; every router ends in the same +// prepareResult, which decides the turns. + +#include "cluster_payload.h" +#include "junction_shape.h" +#include "route_maneuvers.h" + +#include "binaryRead.h" +#include "routePlannerFrontEnd.h" +#include "routingConfiguration.h" +#include "routingContext.h" + +#include "omaps_turns.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace nav = navicore_osmand; +using nav::ui::ManeuverKind; + +const char* kind_name(ManeuverKind kind) +{ + switch (kind) { + case ManeuverKind::Straight: return "straight"; + case ManeuverKind::Left: return "left"; + case ManeuverKind::SlightLeft: return "slight_left"; + case ManeuverKind::SharpLeft: return "sharp_left"; + case ManeuverKind::Right: return "right"; + case ManeuverKind::SlightRight: return "slight_right"; + case ManeuverKind::SharpRight: return "sharp_right"; + case ManeuverKind::KeepLeft: return "keep_left"; + case ManeuverKind::KeepRight: return "keep_right"; + case ManeuverKind::UTurn: return "uturn"; + case ManeuverKind::Roundabout: return "roundabout"; + case ManeuverKind::Arrive: return "arrive"; + } + return "?"; +} + +// A lane arrow as OsmAnd's turn name (the page draws those). +const char* lane_turn_name(ManeuverKind kind) +{ + switch (kind) { + case ManeuverKind::Left: return "TL"; + case ManeuverKind::SlightLeft: return "TSLL"; + case ManeuverKind::SharpLeft: return "TSHL"; + case ManeuverKind::Right: return "TR"; + case ManeuverKind::SlightRight: return "TSLR"; + case ManeuverKind::SharpRight: return "TSHR"; + case ManeuverKind::KeepLeft: return "KL"; + case ManeuverKind::KeepRight: return "KR"; + case ManeuverKind::UTurn: return "TU"; + default: return "C"; + } +} + +std::string quoted(const std::string& text) +{ + std::string out = "\""; + for (const unsigned char c : text) { + if (c == '"' || c == '\\') { + out += '\\'; + out += static_cast(c); + } else if (c < 0x20) { + char escape[8]; + std::snprintf(escape, sizeof(escape), "\\u%04x", c); + out += escape; + } else { + out += static_cast(c); + } + } + return out + "\""; +} + +std::vector map_files(const std::string& path) +{ + std::vector files; + struct stat info {}; + if (::stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode)) { + if (DIR* dir = ::opendir(path.c_str())) { + while (const dirent* entry = ::readdir(dir)) { + const std::string name = entry->d_name; + if (name.size() > 4 && name[0] != '.' && + name.compare(name.size() - 4, 4, ".obf") == 0) + files.push_back(path + "/" + name); + } + ::closedir(dir); + } + } else { + files.push_back(path); + } + return files; +} + +// TurnType values 1..11 by name (turnType.h). +const char* turn_name(int value) +{ + static const char* const names[] = {"", "C", "TL", "TSLL", "TSHL", "TR", "TSLR", "TSHR", + "KL", "KR", "TU", "TRU"}; + return value >= 0 && value <= 11 ? names[value] : "?"; +} + +// The incoming road's turn:lanes as OsmAnd reads it (getTurnLanesString in +// routeResultPreparation.cpp, not exported). Empty: the lanes OsmAnd shows +// are its own, made from the lanes count and the junction. +std::string turn_lanes_tag(const SHARED_PTR& segment) +{ + if (segment->object->getOneway() != 0) return segment->object->getValue("turn:lanes"); + return segment->object->getValue(segment->isForwardDirection() ? "turn:lanes:forward" + : "turn:lanes:backward"); +} + +void print_maneuver(std::ostringstream& out, nav::Segments& segments, std::size_t index, + const nav::ui::Maneuver& m) +{ + const auto& segment = segments[index]; + const ::LatLon at = segment->getPoint(segment->getStartPointIndex()); + // The incoming direction, for drawing the junction's arms on the map + // (junction_of measures them relative to it). + double incoming = NAN; + if (index > 0 && segments[index - 1]) + incoming = segments[index - 1]->getBearingEnd(segments[index - 1]->getEndPointIndex(), 10.0f); + nav::ui::Maneuver without_junction = m; + without_junction.junction = {}; + const auto& j = m.junction; + const std::string lanes = segment->turnType->getLanes().empty() + ? "" : TurnType::toString(segment->turnType->getLanes()); + out << "{\"segment\":" << index << ",\"lat\":" << at.lat << ",\"lon\":" << at.lon + << ",\"turn\":" << quoted(segment->turnType->toString()) + << ",\"kind\":\"" << kind_name(m.kind) << "\"" + << ",\"turn_angle\":" << m.turn_angle_degrees + << ",\"left_side\":" << (m.left_side ? "true" : "false") + << ",\"exit\":" << m.roundabout_exit + << ",\"lanes\":" << quoted(lanes) << ",\"lane_values\":["; + const auto& values = segment->turnType->getLanes(); + for (std::size_t k = 0; k < values.size(); ++k) { + out << (k ? "," : "") << "{\"active\":" << ((values[k] & 1) ? "true" : "false") << ",\"turns\":["; + const int turns[] = {TurnType::getPrimaryTurn(values[k]), TurnType::getSecondaryTurn(values[k]), + TurnType::getTertiaryTurn(values[k])}; + bool first_turn = true; + for (const int t : turns) { + if (!t) continue; + out << (first_turn ? "" : ",") << "\"" << turn_name(t) << "\""; + first_turn = false; + } + out << "]}"; + } + out << "]"; + if (index > 0 && segments[index - 1] && segments[index - 1]->object) { + const auto& previous = segments[index - 1]; + out << ",\"incoming_turn_lanes\":" << quoted(turn_lanes_tag(previous)) + << ",\"incoming_lanes\":" << previous->object->getLanes(); + } + out << ",\"road\":" << quoted(segment->getStreetName("", false, segments, static_cast(index))) + << ",\"incoming_bearing\":" << (std::isfinite(incoming) ? incoming : 0.0) + << ",\"junction\":{\"valid\":" << (j.valid ? "true" : "false") + << ",\"route_angle\":" << j.route_angle << ",\"branches\":["; + for (std::size_t i = 0; i < j.branch_count; ++i) + out << (i ? "," : "") << j.branches[i]; + out << "],\"truncated\":" << (j.truncated ? "true" : "false") + << ",\"through_road\":" << (j.through_road ? "true" : "false") + << ",\"lane_count\":" << unsigned(j.lane_count) + << ",\"recommended_lanes\":" << unsigned(j.recommended_lanes) + << ",\"lane_change\":" << int(j.lane_change) << "}" + << ",\"junction_symbol\":" << unsigned(nav::junction_symbol(m)) + << ",\"turn_type_symbol\":" << unsigned(nav::maneuver_symbol(without_junction)) + << ",\"symbol\":" << unsigned(nav::maneuver_symbol(m)) << "}"; +} + +std::string route(RoutePlannerFrontEnd& front_end, const SHARED_PTR& config, + double lat1, double lon1, double lat2, double lon2) +{ + const auto started = std::chrono::steady_clock::now(); + const auto ms_since = [](std::chrono::steady_clock::time_point t) { + return std::chrono::duration(std::chrono::steady_clock::now() - t).count(); + }; + auto context = front_end.buildRoutingContext(config); + std::vector ix, iy; + nav::Segments segments = front_end.searchRoute( + context, get31TileNumberX(lon1), get31TileNumberY(lat1), get31TileNumberX(lon2), + get31TileNumberY(lat2), ix, iy, nullptr); + if (segments.empty()) + return "{\"ok\":false,\"error\":\"no route\"}"; + // JUNCTION_LAB_ROADS=1: every road the map has at each segment start + // (stderr), including those the router does not attach (one-way roads + // that only enter the node). + if (std::getenv("JUNCTION_LAB_ROADS")) { + for (std::size_t i = 1; i < segments.size(); ++i) { + const auto& s = segments[i]; + if (!s || !s->object) continue; + const int start = s->getStartPointIndex(); + const ::LatLon p = s->getPoint(start); + std::fprintf(stderr, "node %.6f,%.6f route road=%lld turn=%s\n", p.lat, p.lon, + (long long)s->object->getId(), + s->turnType ? s->turnType->toString().c_str() : "-"); + for (auto& rs : context->loadRouteSegment(s->object->pointsX[start], s->object->pointsY[start])) { + const auto& road = rs->getRoad(); + const int at = rs->getSegmentStart(); + const int n = static_cast(road->getPointsLength()); + std::fprintf(stderr, " road=%lld \"%s\" %s oneway=%d lanes=%d turn:lanes=\"%s\" point=%d/%d", + (long long)road->getId(), road->getName().c_str(), road->getHighway().c_str(), + road->getOneway(), road->getLanes(), road->getValue("turn:lanes").c_str(), at, n); + // The neighbouring points: two roads with the same one share that + // stretch (OsmAnd attaches neither when it is the route's own). + if (at + 1 < n) + std::fprintf(stderr, " fwd=%.0f next=%u,%u", road->directionRoute(at, true, 10.0f) / M_PI * 180.0, + road->pointsX[at + 1], road->pointsY[at + 1]); + if (at > 0) + std::fprintf(stderr, " back=%.0f prev=%u,%u", road->directionRoute(at, false, 10.0f) / M_PI * 180.0, + road->pointsX[at - 1], road->pointsY[at - 1]); + const ::LatLon first(get31LatitudeY(road->pointsY[0]), get31LongitudeX(road->pointsX[0])); + const ::LatLon last(get31LatitudeY(road->pointsY[n - 1]), get31LongitudeX(road->pointsX[n - 1])); + std::fprintf(stderr, " ends=%.6f,%.6f..%.6f,%.6f osm_way=%lld\n", first.lat, first.lon, last.lat, + last.lon, (long long)(road->getId() >> 6)); + } + } + } + std::ostringstream out; + out.precision(8); + out << "{\"ok\":true,\"geometry\":["; + bool first_point = true; + for (const auto& segment : segments) { + if (!segment) continue; + const int start = segment->getStartPointIndex(); + const int end = segment->getEndPointIndex(); + const int step = start <= end ? 1 : -1; + for (int i = start;; i += step) { + const ::LatLon p = segment->getPoint(i); + out << (first_point ? "" : ",") << "[" << p.lat << "," << p.lon << "]"; + first_point = false; + if (i == end) break; + } + } + out << "],\"maneuvers\":["; + bool first = true; + for (std::size_t i = 0; i < segments.size(); ++i) { + nav::ui::Maneuver maneuver; + if (!nav::maneuver_at(segments, i, maneuver)) continue; + if (!first) out << ","; + first = false; + print_maneuver(out, segments, i, maneuver); + } + // Every junction on the route, also where OsmAnd gives no turn: what + // the router saw where the driver may expect a manoeuvre. + out << "],\"junctions\":["; + first = true; + for (std::size_t i = 1; i < segments.size(); ++i) { + if (!segments[i]) continue; + const auto j = nav::junction_of(segments, i); + if (!j.valid || j.branch_count == 0) continue; + const ::LatLon p = segments[i]->getPoint(segments[i]->getStartPointIndex()); + out << (first ? "" : ",") << "{\"segment\":" << i << ",\"lat\":" << p.lat << ",\"lon\":" << p.lon + << ",\"turn\":" << quoted(segments[i]->turnType ? segments[i]->turnType->toString() : "-") + << ",\"route_angle\":" << j.route_angle << ",\"branches\":["; + for (std::size_t k = 0; k < j.branch_count; ++k) + out << (k ? "," : "") << j.branches[k]; + out << "]}"; + first = false; + } + // The radio's manoeuvres: Organic Maps' turns through the backend's own code + // (omaps_turns.cpp, route_maneuvers.cpp), with their cluster pictures. + const double route_ms = ms_since(started); + const auto omaps_started = std::chrono::steady_clock::now(); + const auto omaps = nav::omaps::annotate(*context, segments, lat1, lon1, lat2, lon2); + const auto placed = nav::route_maneuvers(segments, &omaps); + if (std::getenv("JUNCTION_LAB_TIMING")) + std::fprintf(stderr, "timing: route+osmand_json=%.0fms omaps=%.0fms segments=%zu\n", route_ms, + ms_since(omaps_started), segments.size()); + out << "],\"omaps\":["; + for (std::size_t i = 0; i < placed.size(); ++i) { + const auto& p = placed[i]; + const auto& m = p.maneuver; + // OM's own direction name, or OsmAnd's for its roundabouts. + std::string direction; + double lat = 0.0, lon = 0.0; + for (const auto& turn : omaps.turns) + if (turn.route_point == p.route_point && !turn.roundabout) { + direction = turn.direction; + lat = turn.latitude; + lon = turn.longitude; + } + if (direction.empty() && p.segment < segments.size() && segments[p.segment]) { + const auto& s = segments[p.segment]; + // One word (cases.tsv tokens): OsmAnd:RNDB3 = roundabout, third exit. + direction = s->turnType ? "OsmAnd:" + s->turnType->toXmlString() : "?"; + const ::LatLon at = s->getPoint(s->getStartPointIndex()); + lat = at.lat; + lon = at.lon; + } + nav::ui::Maneuver without_junction = m; + without_junction.junction = {}; + const auto& j = m.junction; + out << (i ? "," : "") << "{\"segment\":" << p.segment << ",\"route_point\":" << p.route_point + << ",\"lat\":" << lat << ",\"lon\":" << lon << ",\"turn\":" << quoted(direction) + << ",\"kind\":\"" << kind_name(m.kind) << "\",\"exit\":" << m.roundabout_exit << ",\"lanes\":["; + for (std::size_t k = 0; k < m.lanes.size(); ++k) { + const auto& lane = m.lanes[k]; + out << (k ? "," : "") << "{\"active\":" << (lane.recommended ? "true" : "false") << ",\"turns\":[\"" + << lane_turn_name(lane.kind) << "\""; + if (lane.combined) out << ",\"" << lane_turn_name(lane.also) << "\""; + out << "]}"; + } + out << "],\"road\":" << quoted(m.road) << ",\"junction\":{\"valid\":" << (j.valid ? "true" : "false") + << ",\"route_angle\":" << j.route_angle << ",\"branches\":["; + for (std::size_t k = 0; k < j.branch_count; ++k) + out << (k ? "," : "") << j.branches[k]; + out << "],\"truncated\":" << (j.truncated ? "true" : "false") << "}" + << ",\"junction_symbol\":" << unsigned(nav::junction_symbol(m)) + << ",\"turn_type_symbol\":" << unsigned(nav::maneuver_symbol(without_junction)) + << ",\"symbol\":" << unsigned(nav::maneuver_symbol(m)) << "}"; + } + out << "]"; + if (!omaps.ok) + out << ",\"omaps_error\":" << quoted(omaps.error); + out << "}"; + return out.str(); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) { + std::fprintf(stderr, "usage: %s MAPS ROUTING_XML\n", argv[0]); + return 2; + } + auto builder = parseRoutingConfigurationFromXml(argv[2], ""); + if (!builder) { + std::fprintf(stderr, "cannot parse %s\n", argv[2]); + return 1; + } + std::size_t opened = 0; + for (const auto& path : map_files(argv[1])) { + const auto file = initBinaryMapFile(path, false, true); + if (file && !file->routingIndexes.empty()) ++opened; + } + if (opened == 0) { + std::fprintf(stderr, "no routable map in %s\n", argv[1]); + return 1; + } + std::fprintf(stderr, "junction_lab_tool: %zu maps open\n", opened); + std::cout << "{\"ready\":true,\"maps\":" << opened << "}" << std::endl; + RoutePlannerFrontEnd front_end; + std::string line; + while (std::getline(std::cin, line)) { + double lat1, lon1, lat2, lon2; + if (std::sscanf(line.c_str(), "%lf %lf %lf %lf", &lat1, &lon1, &lat2, &lon2) != 4) { + std::cout << "{\"ok\":false,\"error\":\"expected LAT1 LON1 LAT2 LON2\"}" << std::endl; + continue; + } + MAP_STR_STR parameters; + auto config = builder->build("car", 256, parameters); + std::cout << route(front_end, config, lat1, lon1, lat2, lon2) << std::endl; + } + return 0; +} diff --git a/tools/junction_lab/junction_probe.cpp b/tools/junction_lab/junction_probe.cpp new file mode 100644 index 0000000..4cf86d6 --- /dev/null +++ b/tools/junction_lab/junction_probe.cpp @@ -0,0 +1,141 @@ +// junction_probe: the cluster picture the OsmAnd backend sends for one +// junction, computed by the real backend code (junction_shape.cpp, +// cluster_payload.cpp). Used by junction_lab.py; prints one JSON object. +// +// junction_probe --kind left --route 87 --arms=-92,3,175 +// [--lanes '..*'] [--turn-angle 87] [--left-side] +// +// Angles are degrees relative to the incoming direction of travel, +// positive clockwise (as navigation_worker.cpp's junction_of() measures +// them). --lanes: one character per lane, left to right, '*' for a +// recommended lane. + +#include "cluster_payload.h" +#include "junction_shape.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +using navicore_osmand::ui::ManeuverKind; + +struct KindName { + const char* name; + ManeuverKind kind; +}; + +constexpr KindName kind_names[] = { + {"straight", ManeuverKind::Straight}, {"left", ManeuverKind::Left}, + {"slight_left", ManeuverKind::SlightLeft}, {"sharp_left", ManeuverKind::SharpLeft}, + {"right", ManeuverKind::Right}, {"slight_right", ManeuverKind::SlightRight}, + {"sharp_right", ManeuverKind::SharpRight}, {"keep_left", ManeuverKind::KeepLeft}, + {"keep_right", ManeuverKind::KeepRight}, {"uturn", ManeuverKind::UTurn}, + {"roundabout", ManeuverKind::Roundabout}, {"arrive", ManeuverKind::Arrive}, +}; + +bool parse_kind(const char* text, ManeuverKind& kind) +{ + for (const auto& entry : kind_names) + if (std::strcmp(entry.name, text) == 0) { + kind = entry.kind; + return true; + } + return false; +} + +std::vector parse_angles(const char* text) +{ + std::vector angles; + const char* cursor = text; + while (*cursor) { + char* end = nullptr; + const double value = std::strtod(cursor, &end); + if (end == cursor) break; + angles.push_back(value); + cursor = *end == ',' ? end + 1 : end; + } + return angles; +} + +int usage() +{ + std::fprintf(stderr, + "usage: junction_probe --kind KIND --route DEG [--arms=DEG,...] " + "[--lanes PATTERN] [--turn-angle DEG] [--left-side]\n"); + return 2; +} + +} // namespace + +int main(int argc, char** argv) +{ + namespace nav = navicore_osmand; + nav::ui::Maneuver maneuver; + double route_angle = NAN; + std::vector arms; + std::string lanes; + bool kind_given = false; + for (int i = 1; i < argc; ++i) { + const std::string option = argv[i]; + const bool has_value = i + 1 < argc; + if (option == "--kind" && has_value) { + if (!parse_kind(argv[++i], maneuver.kind)) return usage(); + kind_given = true; + } else if (option == "--route" && has_value) { + route_angle = std::strtod(argv[++i], nullptr); + } else if (option.rfind("--arms=", 0) == 0) { + arms = parse_angles(option.c_str() + 7); + } else if (option == "--lanes" && has_value) { + lanes = argv[++i]; + } else if (option == "--turn-angle" && has_value) { + maneuver.turn_angle_degrees = std::strtod(argv[++i], nullptr); + } else if (option == "--left-side") { + maneuver.left_side = true; + } else { + return usage(); + } + } + if (!kind_given) return usage(); + + for (const char c : lanes) { + nav::ui::Lane lane; + lane.recommended = c == '*'; + maneuver.lanes.push_back(lane); + } + // As navigation_worker.cpp: roundabouts get no junction geometry. + if (maneuver.kind != ManeuverKind::Roundabout) { + maneuver.junction = nav::make_junction_shape(route_angle, arms); + nav::summarize_lanes(maneuver.lanes, maneuver.junction); + } + nav::ui::Maneuver without_junction = maneuver; + without_junction.junction = {}; + + const auto& j = maneuver.junction; + std::printf("{\"valid\":%s,\"route_angle\":%.1f,\"branches\":[", + j.valid ? "true" : "false", static_cast(j.route_angle)); + for (std::size_t i = 0; i < j.branch_count; ++i) + std::printf("%s%.1f", i ? "," : "", static_cast(j.branches[i])); + std::printf("],\"truncated\":%s,\"through_road\":%s,\"lane_count\":%u," + "\"recommended_lanes\":%u,\"lane_change\":%d,", + j.truncated ? "true" : "false", j.through_road ? "true" : "false", + static_cast(j.lane_count), static_cast(j.recommended_lanes), + static_cast(j.lane_change)); + std::printf("\"junction_symbol\":%u,\"turn_type_symbol\":%u,\"symbol\":%u,", + static_cast(nav::junction_symbol(maneuver)), + static_cast(nav::maneuver_symbol(without_junction)), + static_cast(nav::maneuver_symbol(maneuver))); + namespace k = nav::junction; + std::printf("\"bands\":{\"through\":%g,\"diagonal_min\":%g,\"diagonal_max\":%g," + "\"perpendicular_min\":%g,\"perpendicular_max\":%g,\"behind_min\":%g," + "\"behind_max\":%g,\"route_slight_max\":%g,\"route_sharp_min\":%g," + "\"narrow_split\":%g,\"same_arm\":%g}}\n", + k::kThrough, k::kDiagonalMin, k::kDiagonalMax, k::kPerpendicularMin, + k::kPerpendicularMax, k::kBehindMin, k::kBehindMax, k::kRouteSlightMax, + k::kRouteSharpMin, k::kNarrowSplit, k::kSameArm); + return 0; +}