From 5f4c7c6ee8b5cfd1cd3c9828b588c67d79866f9a Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Mon, 30 Nov 2026 19:11:07 +0100 Subject: [PATCH] =?UTF-8?q?Navigation:=20rerouting=20off=20the=20route=20(?= =?UTF-8?q?30=20m=20for=203=20fixes,=20HDOP=20=E2=89=A4=205,=20every=2015?= =?UTF-8?q?=20s=20at=20most)=20from=20the=20position=20to=20the=20points?= =?UTF-8?q?=20not=20reached=20yet;=20lanes=20as=20SVG=20arrows,=20the=20on?= =?UTF-8?q?es=20to=20take=20bold;=20dashboard=20background=20see-through?= =?UTF-8?q?=20with=20a=20slider;=20the=20GNSS=20simulation=20starts=20at?= =?UTF-8?q?=20a=20random=20place=20in=20the=20offline=20countries,=20the?= =?UTF-8?q?=20map=20jumping=20there?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.adoc | 18 +++++++-- app.rb | 13 +++++-- lib/maptool/gnss_sim.rb | 33 ++++++++++++---- lib/maptool/routing.rb | 1 + public/css/style.css | 18 ++++++--- public/js/dashboard.js | 85 +++++++++++++++++++++++++++++++++-------- public/js/panels.js | 12 ++++++ public/js/route.js | 11 +++++- test/test_gnss_sim.rb | 20 ++++++++++ 9 files changed, 176 insertions(+), 35 deletions(-) diff --git a/TODO.adoc b/TODO.adoc index d9e68c0..3e3c4fb 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -212,17 +212,27 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho ** [ ] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable signs, `zone:maxspeed` defaults per country (Valhalla leaves untagged roads empty — show the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100) -** [ ] Rerouting when off the route (> 50 m for a while): a new route from the position to the - remaining points +** [x] Rerouting (after Ferrostar's split of deviation detection and recalculation): off the + route = over 30 m from its line for 3 fixes in a row (fixes with HDOP > 5 don't count), then + the route panel routes from the position to the points not reached yet (via points passed + by km along the route, `legs_km`), at most every 15 s and only moving +*** [ ] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it) + instead of "the first maneuver ahead by km"; arrival at 30 m ** [ ] Turn-by-turn: the next maneuver big (arrow, distance, street), voice (`speechSynthesis`), the route ahead highlighted / the driven part greyed -** [ ] Lanes as proper arrows (SVG per direction bit, not Unicode) and only the lanes Valhalla - marks for the maneuver; through-lanes guidance before motorway exits +** [x] Lanes as SVG arrows, one per direction bit, the lanes to take (Valhalla's `active`) blue + with that direction bold +*** [ ] Lane guidance before motorway exits (lanes several maneuvers ahead), bigger on the + driving screen ** [ ] Traffic signals with no route: around the position (Valhalla `locate` or the offline PBF), and only for the direction driven (`traffic_signals:direction`) ** [ ] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the browser's GNSS control), the dashboard as part of the driving-mode UI ** [ ] `locate()` scans the whole route each fix — a window around the last hit on long routes +** [ ] A native Android app on Ferrostar (rerouting, Valhalla speed limits, TTS built in) over + our Valhalla (`format: osrm`) — only if navigation is wanted on a phone outside the car; the + car's 16" display is the Pi's browser either way. Ferrostar's web components are beta: no + rerouting or annotations on the web, bundler + WASM, its own map element ** [x] GNSS simulation for trying it without the car (`lib/maptool/gnss_sim.rb`, Dashboard settings → "Simulate driving from the map center", `POST/DELETE /api/sim/gnss`): random trips over our Valhalla (2–8 km each, one after another) at 90 % of the road's limit, a fix diff --git a/app.rb b/app.rb index 9920415..ecd2b91 100644 --- a/app.rb +++ b/app.rb @@ -1259,7 +1259,8 @@ module Maptool end # The GNSS simulation: POST {"start": [lon, lat]} drives randomly from - # there, DELETE stops it, GET says whether it's on (and why it stopped). + # there, POST {} from a random place in the offline countries, DELETE + # stops it, GET says whether it's on (and why it stopped). get "/api/sim/gnss" do require_login! json running: GNSS_SIM.running?, error: GNSS_SIM.error @@ -1268,10 +1269,16 @@ module Maptool post "/api/sim/gnss" do require_login! lon, lat = JSON.parse(request.body.read)["start"] - halt 400, json(error: "start must be [lon, lat]") unless lon.is_a?(Numeric) && lat.is_a?(Numeric) + if lon.nil? + codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] } + bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) } + halt 422, json(error: "no offline countries to start in") if bboxes.empty? + elsif !lon.is_a?(Numeric) || !lat.is_a?(Numeric) + halt 400, json(error: "start must be [lon, lat]") + end CAN_STORE.override_prefix = "gnss." - GNSS_SIM.start(lon, lat) do |fix| + GNSS_SIM.start(lon, lat, bboxes: bboxes) do |fix| CAN_STORE.put(fix.transform_keys { |key| "gnss.#{key}" }) App.gnss_update(fix) end diff --git a/lib/maptool/gnss_sim.rb b/lib/maptool/gnss_sim.rb index fc53263..52b2257 100644 --- a/lib/maptool/gnss_sim.rb +++ b/lib/maptool/gnss_sim.rb @@ -29,15 +29,22 @@ module Maptool @mutex.synchronize { @thread&.alive? || false } end - # Drives from [lon, lat] until stopped; each fix to the block: + RANDOM_START_TRIES = 20 # a random point at sea / off the routing tiles: another one + + # Drives from [lon, lat] until stopped — or, with bboxes + # ([[west, south, east, north], ...], the offline countries) instead, + # from a random place in one of them; each fix to the block: # { lat:, lon:, speed: m/s, satellites:, hdop: }. - def start(lon, lat, &on_fix) + def start(lon = nil, lat = nil, bboxes: nil, &on_fix) stop @error = nil @mutex.synchronize do @thread = Thread.new do - position = [Float(lon), Float(lat)] - loop { position = drive(position, &on_fix) } + position, route = bboxes ? random_start(bboxes) : [[Float(lon), Float(lat)], nil] + loop do + position = drive(position, route, &on_fix) + route = nil + end rescue StandardError => e @error = e.message warn "gnss sim: #{e.message}" @@ -50,9 +57,21 @@ module Maptool thread&.kill&.join end - # One random trip from position; returns where it ended. - def drive(position, &on_fix) - route = random_route(position) + # A random place in one of the bboxes with a route out of it: [position, route]. + def random_start(bboxes) + RANDOM_START_TRIES.times do + west, south, east, north = bboxes.sample(random: @random) + position = [west + @random.rand * (east - west), south + @random.rand * (north - south)] + return [position, random_route(position)] + rescue Routing::RouteError + next + end + raise Routing::RouteError, "no road found at #{RANDOM_START_TRIES} random places in the offline countries" + end + + # One random trip from position (route: already planned); returns where it ended. + def drive(position, route = nil, &on_fix) + route ||= random_route(position) coords = route[:geometry][:coordinates] km = [0.0] coords.each_cons(2) { |a, b| km << km.last + self.class.meters(a, b) / 1000 } diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index 55c25c7..d5a320f 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -254,6 +254,7 @@ module Maptool properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"], time_s: data["trip"]["summary"]["time"], countries: along[:countries], speed_limits: along[:speed_limits], signals: along[:signals], + legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting # lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"], lanes: m["lanes"] }.compact } } } } rescue ArgumentError, TypeError diff --git a/public/css/style.css b/public/css/style.css index 5038394..64c42c4 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3293,10 +3293,13 @@ html.night .maplibregl-marker { z-index: 3; padding: 8px; border-radius: 12px; - background: #fff; - box-shadow: 0 1px 6px rgba(0, 0, 0, 0.25); + background: rgb(255 255 255 / var(--dash-alpha, 0.45)); + backdrop-filter: blur(2px); + box-shadow: 0 1px 6px rgb(0 0 0 / calc(var(--dash-alpha, 0.45) * 0.5)); text-align: center; pointer-events: none; + /* readable over the map whatever the background */ + text-shadow: 0 0 3px #fff, 0 0 3px #fff; } .dash-incl { @@ -3307,7 +3310,8 @@ html.night .maplibregl-marker { } .dash-incl text { text-anchor: middle; dominant-baseline: middle; fill: #222; } -.dash-face { fill: #f6f6f4; stroke: #bbb; stroke-width: 2; } +.dash-face { fill: rgb(246 246 244 / var(--dash-alpha, 0.45)); stroke: #999; stroke-width: 2; } +.dash-incl text { paint-order: stroke; stroke: #fff; stroke-width: 3px; } .dash-ring line { stroke: #555; stroke-width: 2; } .dash-ring text { font-size: 14px; font-weight: 600; } .dash-ring .dash-n { fill: #c62828; } @@ -3343,7 +3347,11 @@ html.night .maplibregl-marker { radial-gradient(circle at 50% 83%, #43a047 2.5px, transparent 3px), #222; } .dash-lanes { display: flex; gap: 3px; } -.dash-lanes span { min-width: 22px; padding: 1px 3px; border-radius: 4px; background: #eee; color: #999; text-align: center; font-size: 16px; } -.dash-lanes .dash-lane--go { background: #1d6fdc; color: #fff; } .dash-card--over { box-shadow: 0 0 0 4px #d32f2f, 0 1px 6px rgba(0, 0, 0, 0.25); } .dash-card--over .dash-speed span { color: #d32f2f; } +.dash-lanes svg.dash-lane { width: 26px; height: 34px; border-radius: 4px; background: #eee; } +.dash-lane__arrow { fill: none; stroke: #aaa; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.dash-lane--go { background: #1d6fdc !important; } +.dash-lane--go .dash-lane__arrow { stroke: #cfe0f7; } +.dash-lane--go .dash-lane__take { stroke: #fff; stroke-width: 3; } +.dash-offroute { color: #c62828; font-weight: 600; } diff --git a/public/js/dashboard.js b/public/js/dashboard.js index 75e7258..f5928b1 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -1,5 +1,5 @@ import { isLoggedIn } from "/js/auth.js"; -import { onRouteChanged } from "/js/panels.js"; +import { onRouteChanged, requestReroute } from "/js/panels.js"; // The car's dashboard over the map, off the CAN signals (GET /api/can, // names from data/can.json): one inclinometer — compass ring around a rear @@ -9,7 +9,7 @@ import { onRouteChanged } from "/js/panels.js"; // Heading: driving, the GNSS course (from consecutive fixes); standing // still, the compass (imu.heading, once the node sends it) — else the // last course stays, dimmed. -const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", lat: "gnss.lat", lon: "gnss.lon" }; +const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" }; const MOVING_MS = 1.5; // m/s: above this the GNSS course counts const COURSE_MIN_M = 5; // fixes closer than this: too noisy for a course const POLL_MS = 500; @@ -20,11 +20,19 @@ const STORE_KEY = "maptool.dashboard"; // while on it (its speed_limits / signals / maneuvers from /api/route), // else the limit of the road being driven (POST /api/road, map-matched). const OVER_KMH = 3; // over the limit by more than this: warning -const ON_ROUTE_M = 50; // farther from the route line: off it +// Off the route → rerouting, after Ferrostar's split: deviation detected +// (farther than ON_ROUTE_M for OFF_ROUTE_FIXES fixes in a row, fixes with an +// HDOP over MAX_HDOP don't count), then a new route from the position to +// the points not reached yet — at most every REROUTE_EVERY_MS, only moving. +const ON_ROUTE_M = 30; // farther from the route line: off it +const OFF_ROUTE_FIXES = 3; +const MAX_HDOP = 5; // ~ over 10 m off at the NEO-6M's few m UERE +const REROUTE_EVERY_MS = 15000; const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true }; +const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through const load = () => { try { const saved = JSON.parse(localStorage.getItem(STORE_KEY)) || {}; return { ...saved, widgets: { ...DEFAULT_WIDGETS, ...saved.widgets } }; } @@ -35,9 +43,23 @@ const RAD = Math.PI / 180; // meters between two [lon, lat] (equirectangular: fine at these distances) const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320; const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`); -// Valhalla's lane direction bits → arrows -const LANE_ARROWS = [[2, "↑"], [16, "↖"], [8, "←"], [4, "↙"], [32, "↗"], [64, "→"], [128, "↘"], [256, "↶"], [512, "⇤"], [1024, "⇥"]]; -const laneArrows = (bits) => LANE_ARROWS.filter(([bit]) => bits & bit).map(([, arrow]) => arrow).join("") || "↑"; +// Valhalla's lane direction bits → the arrow's angle (° from straight on) +const LANE_ANGLES = { 2: 0, 16: -45, 8: -90, 4: -135, 32: 45, 64: 90, 128: 135, 512: -25, 1024: 25 }; +const LANE_REVERSE = 256; +// One lane as an SVG: an arrow per direction it allows; `active` (the +// directions to take, a bitmask too) drawn bold. +function laneSvg({ directions, active = 0 }) { + const arrow = (bit) => { + const bold = active & bit ? " dash-lane__take" : ""; + if (bit === LANE_REVERSE) return ``; + const a = (LANE_ANGLES[bit] * Math.PI) / 180; + const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)]; + const head = (side) => `L${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`; + return ``; + }; + const bits = [2, 16, 8, 4, 32, 64, 128, 512, 1024, LANE_REVERSE].filter((bit) => directions & bit); + return `${(bits.length ? bits : [2]).map(arrow).join("")}`; +} // A route prepared for "where am I on it": km at every vertex, maneuvers' start km. function prepareRoute(route) { @@ -47,7 +69,9 @@ function prepareRoute(route) { for (let i = 1; i < coords.length; i++) km.push(km[i - 1] + meters(coords[i - 1], coords[i]) / 1000); let start = 0; const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; }); - return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers }; + let leg = 0; + const viaKm = (route.properties.legs_km || []).slice(0, -1).map((length) => (leg += length)); // km at each via point + return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers, viaKm }; } // Nearest point on the route: [km along it, meters off it]. @@ -105,10 +129,17 @@ export class DashboardControl { this._values = {}; this._fix = null; // last fix a course was measured from this._course = null; - this._route = prepareRoute(onRouteChanged((route) => (this._route = prepareRoute(route)))); + this._route = prepareRoute(onRouteChanged((route) => { + this._route = prepareRoute(route); + this._lastAt = 0; + this._offFixes = 0; + })); this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road this._road = null; // its last answer this._roadAt = 0; + this._lastAt = 0; // km along the route at the last fix on it + this._offFixes = 0; + this._rerouteAt = 0; } // The limit and what's ahead: from the route while on it, else the road. @@ -119,12 +150,17 @@ export class DashboardControl { if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position]; const [at, off] = this._route ? locate(this._route, position) : [0, Infinity]; - if (off <= ON_ROUTE_M) { + const fresh = position.join() !== this._lastFix; // polled faster than the fixes come + this._lastFix = position.join(); + if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++; + else if (off <= ON_ROUTE_M) this._offFixes = 0; + if (this._route && this._offFixes < OFF_ROUTE_FIXES) { const { limits, signals, maneuvers } = this._route; const current = limits.findLast(([km]) => km <= at); const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]); const signal = signals.find(([, , km]) => km > at); const maneuver = maneuvers.find((m) => m.at > at + 0.005); + if (off <= ON_ROUTE_M) this._lastAt = at; this._nav = { limit: current?.[1] ?? null, next: next && { limit: next[1], m: (next[0] - at) * 1000 }, @@ -133,7 +169,11 @@ export class DashboardControl { }; return; } - this._nav = { limit: this._road?.speed_limit ?? null }; + this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route }; + if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) { + this._rerouteAt = Date.now(); + requestReroute(position, this._route.viaKm.filter((km) => km <= this._lastAt).length); + } if ((speed ?? 0) < MOVING_MS || this._trace.length < 2 || Date.now() - this._roadAt < ROAD_EVERY_MS) return; this._roadAt = Date.now(); fetch("/api/road", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: this._trace }) }) @@ -171,7 +211,8 @@ export class DashboardControl { - + + `; this._toggle = li.querySelector(".overlays-panel__toggle"); @@ -196,6 +237,13 @@ export class DashboardControl { }); } this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable())); + const opacity = li.querySelector(".dash-opacity"); + opacity.value = this._settings.opacity ?? DEFAULT_OPACITY; + opacity.addEventListener("input", () => { + this._settings.opacity = +opacity.value; + this._save(); + this._card?.style.setProperty("--dash-alpha", opacity.value); + }); this._simButton = li.querySelector(".dash-sim"); this._simStatus = li.querySelector(".dash-sim-status"); this._simButton.addEventListener("click", () => this._simulate(!this._simRunning)); @@ -203,11 +251,12 @@ export class DashboardControl { } // GNSS simulation on the server (POST/DELETE /api/sim/gnss): random - // driving from the map center; on = true / false, null = just read the state. + // driving from a random place in the offline countries, the map jumping + // there with the first fix; on = true / false, null = just read the state. async _simulate(on) { - const { lng, lat } = this._map.getCenter(); - const options = on === true ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ start: [lng, lat] }) } + const options = on === true ? { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" } : on === false ? { method: "DELETE" } : {}; + this._jumpToFix = on === true; try { const response = await fetch("/api/sim/gnss", options); const state = await response.json(); @@ -229,6 +278,7 @@ export class DashboardControl { _enable() { this._card = document.createElement("div"); this._card.className = "dash-card"; + this._card.style.setProperty("--dash-alpha", this._settings.opacity ?? DEFAULT_OPACITY); this._card.innerHTML = `
${INCLINOMETER}
km/h
`; this._map.getContainer().appendChild(this._card); this._status.hidden = false; @@ -255,6 +305,10 @@ export class DashboardControl { // Date has 1 s resolution: +1 so a fresh value isn't "stale" return [key, s && now - s.at < STALE_S + 1 ? s.value : null]; })); + if (this._jumpToFix && this._simRunning && this._values.lat != null) { + this._jumpToFix = false; + this._map.jumpTo({ center: [this._values.lon, this._values.lat], zoom: Math.max(this._map.getZoom(), 15) }); + } this._updateCourse(this._values); this._navigate(); this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server"; @@ -310,13 +364,14 @@ export class DashboardControl { sign.className = `dash-limit${limit === "unlimited" ? " dash-limit--none" : ""}`; sign.textContent = typeof limit === "number" ? limit : ""; const rows = []; + if (n?.offRoute) rows.push(`
Off the route — rerouting
`); if (n?.next) rows.push(`
${typeof n.next.limit === "number" ? n.next.limit : n.next.limit ? "" : "?"} in ${distance(n.next.m)}
`); if (n?.signal != null) rows.push(`
${distance(n.signal)}
`); if (n?.maneuver) { const { text, m, lanes } = n.maneuver; rows.push(`
${distance(m)} · ${text.replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c])}
`); if (lanes && m <= LANES_AHEAD_M) { - rows.push(`
${lanes.map((lane) => `${laneArrows(lane.directions)}`).join("")}
`); + rows.push(`
${lanes.map(laneSvg).join("")}
`); } } nav.querySelector(".dash-ahead").innerHTML = rows.join(""); diff --git a/public/js/panels.js b/public/js/panels.js index cd18a0f..dcdf5da 100644 --- a/public/js/panels.js +++ b/public/js/panels.js @@ -123,6 +123,18 @@ export function notifyRouteChanged(route) { document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route })); } +// Off the route while navigating: the route panel routes again from `from` +// ([lon, lat]) to the points not yet reached (`passed` via points skipped). +const REROUTE_EVENT = "route-reroute"; + +export function requestReroute(from, passed) { + document.dispatchEvent(new CustomEvent(REROUTE_EVENT, { detail: { from, passed } })); +} + +export function onReroute(callback) { + document.addEventListener(REROUTE_EVENT, (event) => callback(event.detail)); +} + export function onRouteChanged(callback) { document.addEventListener(ROUTE_CHANGED_EVENT, (event) => callback(event.detail)); return currentRoute; diff --git a/public/js/route.js b/public/js/route.js index 9fe4f1f..6e9fe7a 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -1,6 +1,6 @@ import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { ROUTE_ICON, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_ICON } from "/js/icons.js"; -import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged } from "/js/panels.js"; +import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; import { wirePreview } from "/js/preview.js"; import { elevationAt } from "/js/dem.js"; @@ -41,6 +41,15 @@ export class RoutePanelControl { this._request = 0; // so a slow older response can't overwrite a newer one this._editing = null; // { key, id, name } of a saved route being edited + // Rerouting (the dashboard, off the route): the start and the via points + // already passed give way to the current position. + onReroute(({ from, passed }) => { + if (this._points.length < 2) return; + this._points.splice(0, 1 + passed).forEach((p) => p.marker.remove()); + this._addPoint(from, "My position", { quiet: true }); + this._points.unshift(this._points.pop()); + this._changed(); + }); onRoutePoint(({ lngLat, name }) => { this._setOpen(true); this._addPoint(lngLat, name); diff --git a/test/test_gnss_sim.rb b/test/test_gnss_sim.rb index cec1946..fa5077b 100644 --- a/test/test_gnss_sim.rb +++ b/test/test_gnss_sim.rb @@ -21,4 +21,24 @@ class GnssSimTest < Minitest::Test assert fixes.each_cons(2).all? { |a, b| b[:lat] >= a[:lat] } # never backwards assert_in_delta (1000 / (36 / 3.6) / 2 + 500 / (45 / 3.6)) / Maptool::GnssSim::TICK_S, fixes.size, 3 # a fix every TICK_S end + + # No road at the first random place: another one, inside the bbox. + class FirstPlaceAtSea < Maptool::GnssSim + attr_reader :tried + + def random_route(position) + (@tried ||= []) << position + raise Maptool::Routing::RouteError, "no road" if @tried.size == 1 + + { geometry: { coordinates: [position, position] }, properties: {} } + end + end + + def test_a_random_start_is_inside_an_offline_country_with_a_road + sim = FirstPlaceAtSea.new("http://valhalla", random: Random.new(3)) + position, route = sim.random_start([[17.0, 48.0, 18.0, 49.0]]) + assert_equal 2, sim.tried.size + assert position[0].between?(17.0, 18.0) && position[1].between?(48.0, 49.0) + assert_equal position, route[:geometry][:coordinates].first + end end