Compare commits
25
Commits
258d35a7a1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5998fdfe88 | ||
|
|
462303eed6 | ||
|
|
cba14300b5 | ||
|
|
f85785c61d | ||
|
|
59f64f2f97 | ||
|
|
88fa2d27a3 | ||
|
|
82a728e024 | ||
|
|
e82b2236b5 | ||
|
|
d6af65f4ef | ||
|
|
38fb06853e | ||
|
|
bf90f4cf23 | ||
|
|
87d7bd2463 | ||
|
|
5e31dfaba9 | ||
|
|
a6158f4083 | ||
|
|
ad975bcf62 | ||
|
|
f15fbef746 | ||
|
|
f981b80599 | ||
|
|
21ad6c0c21 | ||
|
|
1ee79fff66 | ||
|
|
d39e3b5edd | ||
|
|
f73badd107 | ||
|
|
285af64a65 | ||
|
|
91fa9cec41 | ||
|
|
fc8564fe3b | ||
|
|
d559f76b4a |
No files matched your search
+2
-2
@@ -81,7 +81,7 @@ GEM
|
||||
ffi (~> 1.0)
|
||||
rerun (0.14.0)
|
||||
listen (~> 3.0)
|
||||
rexml (3.4.4)
|
||||
rexml (3.4.5)
|
||||
rubyzip (3.7.1)
|
||||
sinatra (4.2.2)
|
||||
logger (>= 1.6.0)
|
||||
@@ -185,7 +185,7 @@ CHECKSUMS
|
||||
rb-fsevent (0.11.2) sha256=43900b972e7301d6570f64b850a5aa67833ee7d87b458ee92805d56b7318aefe
|
||||
rb-inotify (0.11.1) sha256=a0a700441239b0ff18eb65e3866236cd78613d6b9f78fea1f9ac47a85e47be6e
|
||||
rerun (0.14.0) sha256=996a5af2b2b34dcb30146c6c728addab9113e07c119003370daa9bf27feb88fd
|
||||
rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142
|
||||
rexml (3.4.5) sha256=65533089925a7cdfd416ba865d44f5bb1d13e106a3d7f2551de678e7bcd3be24
|
||||
rubyzip (3.7.1) sha256=483aa0f698822a290c0edf2aee6f41bc80870878cb5cd74af03b48d006c85e9e
|
||||
sinatra (4.2.2) sha256=3a0e63c600eb65d7ad6fa0d597a9533f2870d1862cc63ab7b0f7f0ad449ad42f
|
||||
sinatra-contrib (4.2.2) sha256=3d629cfb3647e363cfca6609d0dcde63aa45db664645fe947f0eeddb9cca1620
|
||||
|
||||
@@ -10,17 +10,19 @@ independence from connectivity.
|
||||
|
||||
* [x] Offline vector tiles (PMTiles/MBTiles) for Europe/world via Planetiler or MapTiler — Geofabrik per-country extracts, `osmium merge`, Planetiler's default OpenMapTiles profile straight to PMTiles (`lib/maptool/pmtiles_builder.rb`); offline now shares the exact same style/palette as online (`ONLINE_STYLE_PATCH`) instead of a separate protomaps-schema theme
|
||||
* [x] Shaded relief / DEM layer — hillshade toggle in the sidebar, sourced from public Terrarium tiles online; reads `data/terrain.pmtiles` for offline if one's been generated (see docs/development.adoc), otherwise the toggle is online-only for now
|
||||
** [ ] Terrain slope readout for parking (numeric, not just visual shading)
|
||||
* [ ] Contour lines from OSM for hikes and mountain passes
|
||||
* [x] Hiking trail overlay — Waymarked Trails raster tiles online (`public/js/hiking_trails.js`), colored per-route by the OSM `colour` tag they already render (the KST/KČT paint-blaze colors in Slovakia/Czechia, plain red elsewhere). Click queries a one-off Overpass `around` search (racing 3 public mirrors) for the route's name/colour/network/operator/distance
|
||||
** [x] Offline copy wired in for real, no custom Planetiler profile needed — `Maptool::HikingTrails` (`lib/maptool/hiking_trails.rb`) runs `osmium tags-filter r/route=hiking` + `add-locations-to-ways` + `cat -f opl` against the *same* per-country Geofabrik `.osm.pbf` already downloaded for `offline.pmtiles`, no new download. One `data/hiking_trails/<CODE>.geojson` per country (not one combined file), generated as the last step of every offline build and cached like `geofabrik_cache` (skipped once already newer than its source PBF) — a many-country selection no longer means one giant file, since `GET /api/hiking-trails` lists available countries and the Overlays panel's own checklist only fetches `GET /tiles/hiking_trails/<CODE>.geojson` for whichever ones get ticked. Offline click uses a local `queryRenderedFeatures` hit-test instead of Overpass — instant, no network. See docs/development.adoc
|
||||
* [x] Overpass/OSM scripts to extract POIs (drinking water, dump stations, LPG, public toilets, laundromats, shops, springs) — `rake overpass:pois`, see docs/development.adoc; writes a `.geojson` to drop in `data/gpx/` or upload. Also runnable from inside the app itself now, see the import plugins entry below (`plugins/overpass-pois` wraps this same query). Each category now carries a real `POI_ICONS` glyph and color (not p4n2gpx's plain red marker) plus a popup description built from opening_hours/operator/website tags
|
||||
* [x] Import plugins: a pluggable way to add more data sources (Park4Night, iOverlander, Freecampsites, ...) without their scrapers necessarily living in this (public) repo — sidebar icon (logged in only) lists whatever's under `plugins/`, "Run for this area" uses the current map viewport as the bbox, no separate area-picker needed. Contract: a `plugin.json` manifest + a script that reads `--south`/`--west`/`--north`/`--east` and prints a GeoJSON `FeatureCollection` to stdout (`lib/maptool/plugins.rb`, `GET /api/plugins`, `POST /api/plugins/:name/run`) — output saved the same way an upload would be. `plugins/overpass-pois` ships as the reference example; a private/ToS-sensitive scraper just drops its own directory in locally and is never `git add`ed
|
||||
** [x] Park4Night — private plugin (`data/plugins/p4n2gpx/`, outside this repo per the "ToS-sensitive scraper" note above); iOverlander/Freecampsites still open, same story
|
||||
** [ ] Along the planned route (2026-12-01): Park4Night and overpass-pois fetch the whole
|
||||
viewport/bbox today — a second mode for a corridor around the route (a few km either side):
|
||||
the plugin contract gains the route (a polyline / buffered boxes, not one big bbox), the
|
||||
results into the trip's folder
|
||||
** [x] Along the planned route (2026-12-01): "Along the trip's route" ± 1/2/5/10/20 km in the
|
||||
plugins panel; a plugin with `"route": true` gets `--route=<GeoJSON file> --corridor-km=N`
|
||||
(overpass-pois: Overpass' `around:` over the thinned route; p4n2gpx: circles along it,
|
||||
`lib/maptool/corridor.rb`), points further off dropped by maptool, into the recorded trip's
|
||||
folder when one runs. Plugin settings (`"settings"` in plugin.json: a login cookie) set in the
|
||||
panel, kept in `data/plugin_settings.json`, given to the command as env vars — p4n2gpx's
|
||||
`P4N_SESSION_COOKIE` (park4night's login is behind reCAPTCHA: a browser's Cookie header)
|
||||
** [x] A private plugin's own dependencies now have somewhere to live too: `data/plugins/` is under the persistent `data/` bind mount (survives a redeploy, unlike `build/`), and `docs/deployment.adoc` documents the convention
|
||||
* [x] Kiwix/ZIM offline Wikipedia linked to POI GPS coordinates — proxied through this app (`GET /kiwix/*` in app.rb) rather than a direct link to kiwix-serve — production sits behind a reverse proxy that only forwards to this app, so no address exists for a browser to reach kiwix-serve at directly; kiwix-serve runs with `--urlRootLocation=/kiwix` so its own emitted links already match. `KIWIX_URL` + `GET /api/kiwix` reachability check, same optional-integration pattern as offline.pmtiles/terrain.pmtiles; `docker-compose.yaml` now runs a `kiwix` service, ZIM not included (see docs/development.adoc for where to get one)
|
||||
** [x] Replaced the old per-popup "Nearby on Wikipedia" link (one POI at a time, easy to miss) with a standalone "Wikipedia" layer under Tracks & Points — a live `GET /api/kiwix/nearby` refetch on every pan/zoom, not a saved file. kiwix-serve's own geo search never echoes back a result's coordinates, so `Maptool::Kiwix.nearby` fetches each matching article's own page too and reads its `<meta name="geo.position">` tag — verified against the real production ZIM (~1.6s for a 30-result page; tried parallelizing those fetches with threads, no measured gain, kept sequential)
|
||||
@@ -89,18 +91,43 @@ independence from connectivity.
|
||||
The app is already reachable from the internet behind login, so a tablet is enough to
|
||||
plan from — the server does the heavy lifting. The UI is built for a mouse today.
|
||||
|
||||
* [ ] Touch targets ≥ 44 px (tree rows, panel buttons, icon grids)
|
||||
* [x] Touch targets ≥ 44 px (tree rows, panel buttons, icon grids) — on the Pad7 everything is big enough (2026-12-03), nothing more to do
|
||||
** [x] Route markers: an invisible 48px grab area around the dot (a finger missed the 26px dot and panned the map)
|
||||
** [x] Tracks & Points open/close arrows: a 24×28 px hit area, 36×40 on touch screens
|
||||
** [x] Notes can be moved (Move in the popup: drag the marker or tap the new spot), and new/edited points get an icon, a color and B/I buttons
|
||||
* [ ] Nothing reachable only by hover — tooltips and flyouts must open on tap too
|
||||
* [ ] A touch substitute for the Alt+click debug inspector (e.g. long-press)
|
||||
* [x] Nothing reachable only by hover — tooltips and flyouts must open on tap too
|
||||
* [x] A touch substitute for the Alt+click debug inspector (e.g. long-press) — the long press is a contextmenu: what's here
|
||||
* [x] Side panels as an overlay in portrait instead of a pinned column — under 640 px the pin is ignored and the panel floats over the map at full width (a pinned 300 px panel left the phone a sliver of map); a real bottom sheet still open
|
||||
* [x] Driving mode (field test in the car, 2026-11): tiny icons and lists can't be hit while driving — a separate big-button UI for the few things needed on the road (navigate/follow, night mode, zoom, layer presets) rather than enlarging every planning panel. Done: "Drive" in the topbar (`driving.js`), per device — Follow, zoom, 2D/3D, night, route overview, exit down the left side; the sidebar and panels hidden
|
||||
** [ ] Layer presets on the driving bar
|
||||
** [x] Layer presets on the driving bar (Layers: Road / Off-road / Overnight, + Keep)
|
||||
** [x] The bar after the research (docs/design.adoc, "Buttons while driving"): four buttons
|
||||
(zoom ±, view, overview), Follow and "Back to the position" one button shown only when not
|
||||
following, 76×76 px; night and exit off the bar
|
||||
** [~] The Grid of the Design canvas (docs/design.adoc, "Layout: a grid"), 2026-12-03: the page
|
||||
as 16 × 10 cells, the map 13 × 8, nothing over it; which cell shows what is the screen
|
||||
profile `public/drive/road.json` (`{area, widget, …}`, to be edited in the app later).
|
||||
Done: manoeuvre, speed, limit, altitude, time, sun, status (online, rec); next stop, km/ETA
|
||||
to it and to the end; elevation of the next 10 km; compass; keys Trip, Search, Menu (the
|
||||
whole route, leave), − + 3D Follow, day/dusk/night; a menu in the right 7 × 8, the map
|
||||
9 × 8; the dashboard polls for the grid without its overlay. Trip and Search as GridTrip /
|
||||
GridSearch: the menu area as cells (a stop a row: name over 3, ✓ ↑ ↓ ✕ one each; recording
|
||||
on top, + stop / start from the car at the foot), results a row each with their pins on the
|
||||
map (saved cyan, places amber), "← Back to the stops". Points and Layers as GridPoints /
|
||||
GridLayers (`drive_menus.js`): Points the library nearest the car (`/api/search` with no
|
||||
words and a center lists every saved feature nearest first), Ahead (within 2 km of the
|
||||
route still to drive, of those 50), Shown, or one folder at a time; an eye per row, + a
|
||||
point as a stop. Layers the On the map panel's own checkboxes and Online | Offline, the ones
|
||||
on first; presets Road / Off-road / Overnight, + Keep saves what's on into one (per
|
||||
device). Terrain as GridTerrain (⛰): roll and pitch dials (amber / red, the max held until
|
||||
Reset), heading, climb in 300 m and side slope 50 m ahead (DEM along the course), the
|
||||
route's next 2 km, Level here (can.json's levelling action, two taps), Road view; on by
|
||||
itself on an unpaved surface (`/api/road` now gives Valhalla's `surface`, off a route only)
|
||||
or roll / pitch past 10° for 10 s (not while simulated: the DEM's slope on a hillside road
|
||||
is the hill's), back after 2 km of paved road; Menu: opens and closes by itself / opens and
|
||||
stays (the inclinometer all along) / by hand; the surface in its head. The limit as a sign
|
||||
in the speed field (the next one under it), the speed red past it. Still to do: the surface while
|
||||
on a route (along the route's edges), the lanes in the manoeuvre cell, the profile served from `data/` once the editor exists
|
||||
** [x] The status pill above the car (2026-12-04, pypilot's note in the canvas' SidePanel): ● REC while the trip is recorded, estimated (a tunnel) / no fix; hidden when all is well (`gnss.js` `_showTag`)
|
||||
** [ ] Softkeys: the CAN keypad's labels on the screen edge next to its keys (G1000 style)
|
||||
** [x] The Trip menu beside the map, not over it (Android Auto's side panel, seen again in
|
||||
signalk-pypilot-newui): the map narrower, its buttons kept, its center (follow, crosshair,
|
||||
@@ -129,17 +156,30 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod
|
||||
Start / End, the line really driven (`--route-driven`). Stored crash-safe like a FIT: an
|
||||
append-only journal per trip (`data/trip_log/<started>.ndjson`, fsynced every 5 s, a torn
|
||||
last line skipped), a restart picks the running trip up from it; the library's track built
|
||||
from it every 5 min and at the end. Still to do: the pictogram, the
|
||||
planned route dashed behind, a walk from another device shown with it, visited points
|
||||
** [ ] Colors: planned vs really driven — the planned route (magenta ahead, the part behind
|
||||
from it every 5 min and at the end. Still to do: the pictogram, a walk from another device shown with it, visited points
|
||||
** [x] The recording's days and export (the canvas' GridRecording, 2026-12-03): the Trip menu's
|
||||
"Recording ▸" opens it — the running trip, else the last one: totals, the days (one log, the
|
||||
days only cuts: stood ≥ 4 h, else 03:00; ✂ Cut here and Join kept as journal lines), ⌕ a day
|
||||
on the map; Export the days ticked, a piece between draggable A–B markers or the whole trip as
|
||||
one GPX (a track per day, times per point) or a .zip of a file per day, with the stops near
|
||||
the line, the planned route, the stands (`lib/maptool/trip_days.rb`,
|
||||
`/api/trip/log/days`, `/api/trip/log/export`). Not yet: renaming the trip there, the days
|
||||
named by place (no reverse geocoding offline), moving a cut by hand
|
||||
** [x] Colors: planned vs really driven — the planned route (magenta ahead, the part behind
|
||||
thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc
|
||||
** [ ] The menu while driving: showing routes and points, editing the trip — all of it on the
|
||||
** [x] The menu while driving: showing routes and points, editing the trip — all of it on the
|
||||
road, so simple: a few big tiles (Trip, Points, Layers, Search), one level deep, rows
|
||||
≥ 76 px, a handful per screen, the action a big button (add a stop here / at a point,
|
||||
skip the next one, move one up/down, show / hide a layer) — no drag, no hover, no small
|
||||
text fields. Who: the navigator (co-driver) runs the whole UI and the trip's points on the
|
||||
16" display; the driver only looks at a finished map on Android Auto, touching the 16"
|
||||
only now and then — so it's simple for a moving car, not driver-distraction rules
|
||||
* [x] Desktop (the Design canvas' Desktop, 2026-12-03): copy the position under the cursor
|
||||
to the clipboard (a key or the right-click menu) — today only the map's center copies,
|
||||
from the status bar, so the way around it is to put the center on the point first. Done: right
|
||||
click / long press / Alt+click = what's here (the position, a click copies it; Route here, Add to
|
||||
the trip, Save a point; the features' raw properties folded), C copies the position under the mouse
|
||||
* [x] Desktop: the scale back over the map, not in the status bar
|
||||
* [x] Night mode — topbar button cycles auto (sun below the horizon at the map center) / on / off. The map has its own night palette (`NightMap` in `public/js/map_themes.js`, switched live with setPaintProperty): dark blue-gray ground, roads a step lighter, muted ochre motorways, light-gray labels on dark halos; raster overlays dimmed, our own track/point colors kept
|
||||
** [x] The rest of the UI is still one invert+dim filter — CSS color tokens and a real dark set instead
|
||||
* [x] Tracker as a top-down vehicle (car / motorbike / bicycle from its icon) rotated by the GNSS course, kept while standing still; "Navigate" (tracker card or Overlays status) follows it heading-up, tilted 60°, vehicle in the lower third — panning by hand ends it
|
||||
@@ -214,6 +254,17 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
names) or a vxcan pair moved into the container's namespace by a host script
|
||||
** [ ] The car-CAN → CANopen bridge's mapping (not decided yet) as signals in `data/can.json`;
|
||||
a dashboard panel for the `car.*` signals
|
||||
** [ ] Signals in `data/can.json`, after candinista (github.com/mikeypi/candinista, its
|
||||
`config.yaml`) — for third-party devices whose conversion we can't change:
|
||||
*** [ ] A sensor curve: `x_values` → `y_values`, linear interpolation between points (NTC
|
||||
temperature senders, pressure sensors), instead of `scale` / `offset`
|
||||
*** [ ] Multiplexed signals: one byte of the frame says which channel it carries (`mux_byte`,
|
||||
`mux_value`; e.g. Haltech TPMS, wheel 1–4 on one ID)
|
||||
*** [ ] Warning limits per signal (`low_warn`, `high_warn`): the value coloured on its tile
|
||||
** [ ] A display node on the CANopen bus (`mcu-lvgl`, ESP32-8048S043, 4.3" 800×480, LVGL) with
|
||||
its own switch screens — it only sends requests to the controller and draws the state the
|
||||
controller reports, so it works with the Pi off. The look: Garmin style, picked in the Design
|
||||
canvas (PanelGarmin: Switches, Power, Tanks, Settings; the status bar is the navigation)
|
||||
** [x] The GNSS node's PDO layout as `gnss.*` signals — `mcu-stm32-xiao-c5-2` (node 0x21,
|
||||
esphome-canopen), `data/can.json` in docs/deployment.adoc
|
||||
** [x] `/can.html` diagnostics: interfaces, nodes (heartbeat, last EMCY, what they send),
|
||||
@@ -223,7 +274,8 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
`data/can_rec/` (a power cut loses at most the last segment), the CANedge `CAN_DataFrame`
|
||||
layout — asammdf decodes it with a DBC (checked against candump: every frame, < 0.002 ms)
|
||||
*** [ ] Checked with CSS Electronics' converters (mdf2csv) too, and in CANalyzer if at hand
|
||||
*** [ ] Old recordings cleaned up (data/can_rec grows ~85 MB an hour at 1000 frames/s)
|
||||
*** [x] Old recordings cleaned up (data/can_rec grows ~85 MB an hour at 1000 frames/s): segments
|
||||
older than `CAN_REC_KEEP_HOURS` (24 by default, 0 keeps all) go — diagnostics only
|
||||
** [ ] Nodes describing themselves — no hand-written signals for our own nodes:
|
||||
*** [x] esphome-canopen nodes over SDO: on a node's first heartbeat read its TPDOs
|
||||
(`0x1800+n`:1 COB-ID, `0x1A00+n` mapping), each mapped entity's type (`0x2001`:N) and
|
||||
@@ -266,13 +318,19 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
** [ ] Off the route: the gyro's yaw rate (the IMU node) or the compass, with map matching
|
||||
** [ ] Back out of the tunnel: the first fixes taken only once consistent (HDOP, the jump from
|
||||
the estimate); the trip log keeps a straight line through the tunnel for now
|
||||
* [ ] TPMS off the car's CAN (2026-12-05): the car's own TPMS read by the car gateway and passed on
|
||||
as `car.tpms.*` signals in `data/can.json` (the 4 wheels, pressure, temperature where sent);
|
||||
warnings: low pressure, a fast drop (a puncture). Find where the Yaris Cross has it — broadcast
|
||||
on a CAN the gateway sees, or only on request (UDS from the TPMS ECU). No radio node of our own;
|
||||
sniffing the 433 MHz sensors (`rtl_433` on the uConsole's SDR) only if the car's CAN doesn't
|
||||
carry it
|
||||
|
||||
=== 3D navigation mode
|
||||
|
||||
* [x] A "follow" mode like a car navigation: camera locked to the GNSS position, rotated to the
|
||||
heading, pitched ~60°, smooth easing — the tracker's "Navigate" (see the Tablet-friendly
|
||||
section); follows the MQTT tracker, not the browser's own GNSS control yet
|
||||
** [ ] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating
|
||||
** [x] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating (the 3D mode has both)
|
||||
* [ ] Full navigation (the car's main screen while driving; everything from our own Valhalla
|
||||
tiles, no online service — Valhalla has OSM `maxspeed`, `traffic_signals` and turn lanes)
|
||||
** [x] Basics on the dashboard (`public/js/dashboard.js`): the speed limit as a sign and a red
|
||||
@@ -283,34 +341,49 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
(`turn_lanes`), from the same `trace_attributes` pass as the countries; the route's
|
||||
signals drawn on the map from z14. Off the route / with none: `POST /api/road`
|
||||
(map-matched last fixes → the road's name and limit), every 4 s while moving
|
||||
** [ ] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable
|
||||
** [x] 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)
|
||||
the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100). Done
|
||||
for the vehicle: `public/js/speed_limits.js` (14 countries, cars and over 3.5 t, from two camping
|
||||
guides — see its sources), the route's `roads` (km, road class, country), the limit shown = the
|
||||
lower of the sign and the profile's; past a border a card in drive mode (the canvas' GridBorder).
|
||||
Not yet: `maxspeed:conditional`, a car's country default where the edge has none, ES/SE/NO/BE/LU
|
||||
** [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)
|
||||
*** [x] 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. Done: progress only forward —
|
||||
the position looked for near the last one first (`locate`, 0.1 km back to 3 km ahead), so a
|
||||
route along the same road twice or crossing itself doesn't jump; the step still advances 5 m
|
||||
past the maneuver. Arrival still to do
|
||||
past the maneuver. Arrival: 30 m from the end "Arrived" (banner, drive mode), the navigation
|
||||
goes on — driven past it, the reroute turns back to it
|
||||
** [x] The navigation banner across the top (Dashboard widget, on by default): the next
|
||||
maneuver's arrow (Valhalla's maneuver type), distance and street, "then …" when the next one
|
||||
follows within 300 m, its lanes from 1 km, the street being driven; `/api/route` maneuvers
|
||||
gain `type`, `street`, `exit`
|
||||
** [x] The driving view decluttered: tilted to 3D (≥ 30°), route numbers and minor roads' /
|
||||
paths' names hidden; road labels 1.5× further apart, past z15 the same ground distance
|
||||
** [ ] Turn-by-turn voice (`speechSynthesis`), the route ahead highlighted / the driven part
|
||||
greyed
|
||||
** [x] Turn-by-turn voice (`speechSynthesis`), the route ahead highlighted / the driven part
|
||||
greyed. Voice: Valhalla's `verbal_transition_alert_instruction` ("In 400 meters, …", 25 s / ≥ 400 m
|
||||
ahead) and `verbal_pre_transition_instruction` (7 s / ≥ 60 m ahead), English; on/off in drive
|
||||
mode's Menu, off by default
|
||||
** [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
|
||||
*** [x] Lane guidance before motorway exits (lanes several maneuvers ahead), bigger on the
|
||||
driving screen. Done: the next maneuver's lanes from 1 km or 45 s at the speed driven, in drive
|
||||
mode a cell under the maneuver (`ahead` in the profile), shown only when there's something
|
||||
** [x] Traffic signals with no route: around the position (Valhalla `locate` or the offline
|
||||
PBF), and only for the direction driven (`traffic_signals:direction`). Done: `/api/road` also routes
|
||||
1.5 km straight on from the last fix (leaving in the direction driven) and gives that way's signals;
|
||||
the nearest one in front shown (dashboard, drive mode's `ahead` cell up to 1 km). The
|
||||
`:direction` tag not yet
|
||||
** [x] 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. Done: drive mode's Follow
|
||||
follows the CAN GNSS; the LTE tracker (MQTT) is a tracker layer to switch on (a second car, the car
|
||||
seen from home), Meshtastic the same with the nodes picked
|
||||
*** [x] Any point of a tracker layer can be the one the map follows — one at a time (picking
|
||||
another one, or the car's own GNSS, takes it over); today only the MQTT tracker's card has "Navigate"
|
||||
** [x] `locate()` scans the whole route each fix — a window around the last hit on long routes
|
||||
** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet
|
||||
or display in the back, phones): the co-driver adds a stop, the driver's view reroutes on the
|
||||
@@ -324,21 +397,51 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
route once for all screens, not per screen with a dashboard. Done: `TripStore#follow` on
|
||||
every fix (3 fixes > 30 m off while moving, at most every 15 s), the browser's own reroute
|
||||
only without the shared trip
|
||||
*** [ ] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg
|
||||
times), "Add to the trip" from search, the library, park4night and other sources
|
||||
*** [x] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg
|
||||
times), "Add to the trip" from search, the library, park4night and other sources. Done in the
|
||||
Route panel (the canvas' Itinerary): the trip's name, leave time, days start; per stop ☾ night
|
||||
(the day ends), stay and note; day headers with km and time; another screen's change shown
|
||||
where it happened with Undo. Not yet: the route coloured by day, each stop's source, the
|
||||
drive mode's Trip menu by days
|
||||
*** Planning (the canvas' Plan and GridToday, ideas from azedler/roadplanner), in this order:
|
||||
**** [x] A stop's type (its NPS pictogram on the marker and in the list), notes on the trip,
|
||||
the days (on a day's first point) and the stops; + on a leg inserts the next point there
|
||||
**** [x] The place and where the car stays apart: Parking in a stop's ✎, a P marker (drag it), the route goes there, the walk ×1.25 straight
|
||||
**** [x] A pasted link (Google Maps, park4night, a page with coordinates) becomes a place in the search (/api/link, logged in); + puts it on the leg it lengthens least
|
||||
**** [x] Avoids for the trip (+ ferries, unpaved) or a day (the day's ✎; routed in pieces, joined). Soft preferences (camps ≤ 40 €, lakes) not yet: for the Check / search when wanted
|
||||
**** [x] Check (a fold in the Route panel): no leave time, a day over 8 h driving, a night spot after sunset, a long walk from the parking, motorways without the vignette; each with ⌖. Not yet: a day's avoids vs its route, winter-closed roads, opening hours
|
||||
**** [x] Costs (a fold): fuel = km × the profile's consumption × the trip's fuel price, each stop's costs / paid, the budget left. Not yet: documents / receipts per stop, prices per country
|
||||
**** [x] Today in drive mode (Menu ▸ Today): the stops left with arrival, tonight, sunset, Open-Meteo weather, the day's notes and Check items, Skip next, Tomorrow ▸. Not yet: Late +30 min
|
||||
**** [ ] MCP over maptool (later)
|
||||
*** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with
|
||||
the library sync, or "send to the car")
|
||||
*** [ ] Push instead of polling (SSE) if 2 s ever feels slow
|
||||
** [ ] Android Auto: the browser can't be cast there, only a native app — a small one with
|
||||
the Car App Library's NavigationTemplate drawing its own map surface (MapLibre Native) off
|
||||
the car server's trip and position (`/api/trip`, `/api/gnss/position`); only the map and
|
||||
the next maneuver, planning stays on the web. Testable without the car: the tablet runs the
|
||||
Android Auto head unit emulation (DHU)
|
||||
** [ ] Android Auto with the Pi as the phone (2026-12-05): the Pi connects to the car's existing
|
||||
Android Auto and shows maptool's navigation to the driver on the car's screen; the display on
|
||||
the Pi / the tablet over Wi-Fi are the navigator's. No phone in the loop
|
||||
*** [ ] Over USB first: the head unit is the host, switches the "phone" into Android Open
|
||||
Accessory (AOA) mode, then the Android Auto protocol (AAP over TLS). The Pi must be a USB
|
||||
gadget — USB-OTG: the Pi 5's USB-C port (`dwc2` peripheral), on a CM5 whether its carrier
|
||||
brings out the USB 2.0 port; power from the HAT through the header, the USB-C data only
|
||||
(car VBUS not connected). Wireless (Bluetooth, then Wi-Fi) later
|
||||
*** [ ] First check the head unit accepts a foreign phone side: AARE
|
||||
(github.com/prototux/AARE, an open phone-side reimplementation, an Android app) on a phone
|
||||
in the Yaris Cross; from AARE, whether the head unit checks the phone's certificate (if it
|
||||
wants a Google-signed one, this way is closed). No open phone side for Linux was found
|
||||
*** [ ] Then a Linux phone side (the AAP messages are aasdk's protobufs, the same both ways),
|
||||
tested at home against Google's Desktop Head Unit. Video is H.264: the Pi 5 / CM5 have no
|
||||
hardware encoder, so software (x264 ultrafast) at the head unit's 800×480 or 1280×720,
|
||||
30 fps, one or two cores. Back from the car: touch and the rotary into maptool; to the car:
|
||||
navigation prompts on AA's own audio channel, the turn arrows in the cluster where supported
|
||||
*** [ ] Fallback: a native app on the phone — the Car App Library's NavigationTemplate drawing
|
||||
its own map surface (MapLibre Native) off the car server's trip and position (`/api/trip`,
|
||||
`/api/gnss/position`); only the map and the next maneuver, planning stays on the web
|
||||
*** [ ] Views by who's driving off which screen: no Android Auto connected → the 16" display
|
||||
shows the 3D follow view (heading-up, pitched) for the driver; Android Auto connected → it
|
||||
streams the 3D navigation to the driver, and the co-driver's display stays 2D (north-up
|
||||
overview, planning). Needs the app to report connected/disconnected to the server (e.g.
|
||||
next to `/api/gnss/position`) and the driving view to switch on it
|
||||
overview, planning). Needs the Android Auto link (the Pi's phone side, or the fallback app)
|
||||
to report connected/disconnected (e.g. next to `/api/gnss/position`) and the driving view
|
||||
to switch on it
|
||||
** [ ] 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
|
||||
@@ -348,11 +451,12 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
trips over our Valhalla (2–8 km each, one after another) at 90 % of the road's limit, a fix
|
||||
a second into the same `gnss.*` signals / GNSS_LATEST as the node's (ignored meanwhile)
|
||||
*** [x] The dashboard's tilt from the terrain's slope while simulating
|
||||
*** [ ] Replay a library track (GPX/FIT with times) instead, at its own speed
|
||||
*** [x] Replay a library track (GPX/FIT with times) instead, at its own speed (`/sim.html`,
|
||||
`GnssSim#replay`; stops longer than 30 s shortened to it)
|
||||
** [x] Free look while following: moving the map by hand pauses the follow, "Back to the
|
||||
position" or 15 s untouched resumes it
|
||||
* [ ] While following a planned route: the route ahead highlighted, distance to the next
|
||||
maneuver from Valhalla's directions
|
||||
* [x] While following a planned route: the route ahead highlighted, distance to the next
|
||||
maneuver from Valhalla's directions (the banner; the driven part dashed)
|
||||
|
||||
=== Design: the park brochure and the cockpit
|
||||
|
||||
@@ -395,18 +499,67 @@ Planning in the NPS look, driving in the cockpit look, joined by the Unigrid bla
|
||||
Inspired by Garmin Tread / zūmo, but open and over CANopen — the nodes' side and the options
|
||||
are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūmo"):
|
||||
|
||||
* [ ] A universal STM32C5 board v1 (2026-12-05) instead of XIAOs (~9 € + VAT + 10 € postage
|
||||
each; out of stock) and before role-specific boards — one design, one round of first-spin
|
||||
fixes, 8–10 pieces for the IO nodes, the car gateway, the Meshtastic bridge, the
|
||||
controller prototype. JLCPCB in batches, Basic parts assembled, the MCU by hand. The bare MCU
|
||||
isn't reliably in stock either (TME showed 0, ~3.6 USD) — check before ordering the PCBs
|
||||
** STM32C5A3CGT6 (LQFP48), 16 MB flash on QSPI (W25Q128, as on the XIAO, for Zephyr)
|
||||
** 2× CAN transceiver, both TCAN1043 (CAN FD, VIO for 3.3 V, wake on bus traffic or the local
|
||||
WAKE pin, INH switching the board's regulator → Silent Watch at µA); one part everywhere (one
|
||||
JLCPCB extended-part fee), ~0.4–1 USD more than a TJA1051 at LCSC. Not selective wake
|
||||
(TJA1145 / TCAN1145, SPI): any bus traffic wakes every node, fine while the bus is quiet
|
||||
** Automotive 12 V in: reverse polarity, TVS, a buck to 3.3 V; SWD; the power + CAN connector
|
||||
the same as the xt30_can_5v board (XT30 2+2)
|
||||
** Headers with every free GPIO, SPI and UART: role add-ons on top — an output board, a
|
||||
Meshtastic radio on UART (its firmware doesn't run on the C5)
|
||||
|
||||
* [ ] Hardware buttons (a CANopen keypad / a steering-wheel controller, read off `can0`):
|
||||
actions in `data/can.json` — pan, zoom ±, add a point (the position into the library or the
|
||||
trip), mark a place, switch views (navigation / overview / dashboard), mute / volume, the
|
||||
trip's next stop, night mode; a long press for a second action, the keypad's LEDs showing state
|
||||
** [x] Drive mode keys from the keyboard (profile `key`, labels in the corners, ↑ ↓ / Enter / Space / + / Esc in a menu)
|
||||
** [x] Keypads as channels and bindings, the PDMs' way (2026-12-04, `lib/maptool/keypad.rb`): can.json's `"keypads"` (a PKP by its protocol, or any signals as `inputs`) give channels `pad.K1`, `pad.E3`, `pad.E3 press`; the screen profile's `"bindings"` give each an action (a screen key, zoom, pan, rows), another in an open menu, its LED colour and the colour while on. A keypad's heartbeat labels the screen keys with its channels (back after 5 s without it), a line under them in the LED colour. Not tried on the real node yet
|
||||
*** [x] Outputs (2026-12-04, `lib/maptool/outputs.rb`): can.json's relay modules (simulated for now, no current measured), a binding's `output` with Toggle / On / Off / Hold / Pulse, Hold off when the keypad goes silent, the state re-sent every 100 ms (the module's 2 s watchdog), the key LED while on; `/sim.html` switches them by hand. Not tried on a real module
|
||||
*** [x] Positions, strobe and dimmer (2026-12-04): a key steps through outputs (a knob up and down), blinking with a period, a knob's level by a step (a dimmable module: a byte per channel); in /keypad.html and /sim.html. Nothing real behind them yet
|
||||
*** [x] Switch tiles on the screen (2026-12-04, the canvas' GridSwitches): Menu → Switches (only when `/api/outputs` answers), 3×3 tiles per page (name, On / Off / Flashing / level, the key and mode driving it, its LED colour line), a group per module, All off, More ▸; a tap toggles (`switchesMenu` in `drive_menus.js`)
|
||||
*** [ ] Interlocks and conditions (speed, ignition), long press
|
||||
*** [ ] The controller moves to the STM32C5 on the Pi's HAT (docs/design.adoc "The controller on
|
||||
the Pi's HAT", 2026-12-05): first the CANopen objects for requests (toggle / on / off / level
|
||||
from keypads, `mcu-lvgl`, maptool), the outputs' state (TPDO) and the configuration (bindings
|
||||
over SDO), used by maptool's `outputs.rb` now; then the Zephyr firmware (MCUboot's second slot,
|
||||
the black box and the bindings in the 16 MB external flash), checked against `outputs.rb`;
|
||||
maptool fetches the black box when it comes up
|
||||
**** [ ] Before more STM32C5 boards arrive (both XIAOs are in use): the controller in Zephyr as
|
||||
`native_sim` on SocketCAN (`zephyr,native-linux-can`) — on a PC against `vcan0` with
|
||||
`/sim.html` and the simulated outputs, on rpi-dev against `can0` and the real keypads; the
|
||||
external flash emulated in a file; the same inputs give the same outputs as `outputs.rb`.
|
||||
Only the chip's layer (CAN, flash, power) moves to the board later. Order more XIAO STM32C5
|
||||
** [x] CANopen TIME from maptool while no node sends it (2026-12-04, `lib/maptool/can_time.rb`); the GNSS node takes over once esphome-canopen has TIME
|
||||
*** [ ] A knob's hold (the eye), the focused row's badges in keypad mode, the knobs' LEDs (8Encoder colours over SDO)
|
||||
** [x] The key mapping in our diagnostics (2026-12-04, `/keypad.html`, the canvas' GridBinding): pick a key or knob (or press it), what it drives, mode, menu, LEDs; saved per car in `data/drive/bindings.json`. Not yet: interlocks, conditions, long press; drive mode picks a change up only on reload
|
||||
** [ ] The switch (auto / keyboard / keypad) in our diagnostics
|
||||
* [ ] A virtual switch panel for the PDM node (like Garmin's PowerSwitch: tiles with icon,
|
||||
label, state and current, groups) + rules: by speed, sun/time of day, geofence (the trip's
|
||||
camp), ignition and battery voltage
|
||||
** [ ] Blackout / camp mode: one key — keypad LEDs ~2 % dim red, screen Night at its lowest,
|
||||
auxiliary outside lights off and inhibited (door → awning light) until left; road lights untouched
|
||||
** [ ] Sleep (Silent Watch): outputs to their safe state, nodes NMT stopped / asleep, screen off;
|
||||
what wakes them (a key, ignition / wake line, CAN wake-up) — node side in home-gitops
|
||||
`docs/canopen-nodes.adoc` (TCAN1043 on every board: wake + INH, transparent until the firmware
|
||||
uses its EN / nSTB pins; the "everyone to sleep" command from the controller)
|
||||
** [ ] A node's hardware interlock (winch, inverter, heater off on a wire, MCU or bus dead or not)
|
||||
shown on its tiles as "locked out"
|
||||
* [ ] The group over LoRa (Meshtastic / MeshCore through a node on the Pi): the others' positions
|
||||
as a live layer with trails, short messages, "come here" into the trip
|
||||
* [ ] Audio: volume / mute from the keypad and the app, navigation prompts ducking the music
|
||||
|
||||
* [ ] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation
|
||||
* [x] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation (the canvas'
|
||||
GridLevel, 2026-12-03): Terrain → "Level ▸" (in place of Road view; ✕ closes it the same): the
|
||||
car from above with the cm under each wheel (lifted to the highest, never dug in), rounded to
|
||||
the profile's ramp steps or exact for jacks, the bubble, roll / pitch now and after; the
|
||||
profile's new wheelbase, track and ramps fields (guessed from length / width when unset).
|
||||
Not yet: a pitch target (the bed's head up), only the two low wheels on ramps
|
||||
* [ ] Victron/Home Assistant via MQTT or WebSocket — battery SoC, tank levels, temperatures
|
||||
* [ ] Plot GPS track with historical battery/speed data
|
||||
|
||||
@@ -417,10 +570,22 @@ server into the car (on the car's Wi-Fi, next to the MQTT broker) makes everythi
|
||||
already offline work on the road. The Pi only serves; heavy builds stay on brick.
|
||||
|
||||
* [ ] Run the existing docker-compose stack on the CM5 (arm64: our image handles it, check
|
||||
that the Valhalla and kiwix-serve images have arm64 builds); data on NVMe, not the SD card
|
||||
that the Valhalla and kiwix-serve images have arm64 builds); data on NVMe, not the SD card.
|
||||
maptool itself runs on rpi-dev (podman, data in /srv/podman/maptool/data on the NVMe);
|
||||
Valhalla and kiwix-serve there not checked
|
||||
* [ ] Build on brick, ship to the Pi: `offline.pmtiles`, `terrain.pmtiles`, Valhalla
|
||||
`tiles.tar`, `places/*.sqlite`, `hiking_trails/*.geojson`, the ZIM — an rsync (only when
|
||||
refreshed, which is rare) instead of the Pi's own build buttons; hide/disable those there
|
||||
* [ ] Powering the Pi (docs/design.adoc "What the military vehicles do"): preferred, the Pi on
|
||||
12 V only, anywhere in the car — the gateway node tells "car running" (car CAN data or its IGN
|
||||
input); a HAT with an STM32C5 turns the Pi on (car running, or a wake from the network), asks
|
||||
it to shut down cleanly and cuts power after, measures voltage / current; the HAT also has the
|
||||
Pi's CAN (SPI controller + transceiver, `can0`), the STM32C5 a node on the same bus and the Pi's
|
||||
watchdog (maptool's heartbeat — it sends none yet —, power-cycle when it hangs). The Pi 5 takes
|
||||
5 V only and wants ≥ 5 A: the HAT's buck 5.1 V / 5 A+ into the header's 5 V pins, and
|
||||
`PSU_MAX_CURRENT=5000` in the EEPROM (powered off the header it can't tell, and limits USB to
|
||||
600 mA); the 12 V side survives a cold crank or shuts down cleanly. Fallback: the Pi on
|
||||
the bus, 6-pin Deutsch DT (12 V, GND, CAN H, CAN L, IGN, spare), IGN read by the Pi
|
||||
* [x] Login without internet: Gitea OAuth can't run offline — let the car's LAN through
|
||||
without login (e.g. `TRUSTED_NETWORKS` CIDR list), or a local fallback account. Done: the
|
||||
session cookie is checked locally (90 days, no Gitea after the login), and rpi-dev has
|
||||
@@ -447,8 +612,9 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
|
||||
other version into `item_history` and flagged in the UI so it can be restored; a delete vs.
|
||||
an edit keeps the edit
|
||||
** Logged tracker positions: append-only, merged by timestamp, no conflicts
|
||||
* [ ] Hardware buttons: keyboard shortcuts in the page (zoom, Navigate, night mode, …) — the
|
||||
cheap way with any BLE/USB keypad that sends plain keys
|
||||
* [x] Hardware buttons: keyboard shortcuts in the page (zoom, Navigate, night mode, …) — the
|
||||
cheap way with any BLE/USB keypad that sends plain keys. Done in drive mode (the profile's
|
||||
`key`s, see HW integration); the desktop has none yet
|
||||
* [ ] … and the full way: a CANopen keypad (Blink Marine style) on the CAN bus wired straight
|
||||
to the Pi, read by maptool's native CAN (see "Native CAN" above; NMT start, key bitmap
|
||||
from `0x180+node` as `bit` signals, LEDs via `0x200+node` still to send) → the
|
||||
|
||||
@@ -4,6 +4,7 @@ require "oauth2"
|
||||
require "securerandom"
|
||||
require "zip"
|
||||
require "stringio"
|
||||
require "tempfile"
|
||||
require_relative "lib/maptool/gpx"
|
||||
require_relative "lib/maptool/fit"
|
||||
require_relative "lib/maptool/gpx_store"
|
||||
@@ -14,9 +15,14 @@ require_relative "lib/maptool/mqtt_client"
|
||||
require_relative "lib/maptool/can"
|
||||
require_relative "lib/maptool/can_discovery"
|
||||
require_relative "lib/maptool/can_recorder"
|
||||
require_relative "lib/maptool/keypad"
|
||||
require_relative "lib/maptool/outputs"
|
||||
require_relative "lib/maptool/can_time"
|
||||
require_relative "lib/maptool/gnss_sim"
|
||||
require_relative "lib/maptool/trip"
|
||||
require_relative "lib/maptool/trip_log"
|
||||
require_relative "lib/maptool/trip_days"
|
||||
require_relative "lib/maptool/link_place"
|
||||
require_relative "lib/maptool/updater"
|
||||
require_relative "lib/maptool/sync"
|
||||
require "ipaddr"
|
||||
@@ -25,6 +31,7 @@ require_relative "lib/maptool/livetrack_store"
|
||||
require_relative "lib/maptool/livetrack_client"
|
||||
require_relative "lib/maptool/kiwix"
|
||||
require_relative "lib/maptool/plugins"
|
||||
require_relative "lib/maptool/corridor"
|
||||
require_relative "lib/maptool/pmtiles_builder"
|
||||
require_relative "lib/maptool/search"
|
||||
|
||||
@@ -172,6 +179,7 @@ module Maptool
|
||||
# above can't. Checked after PLUGINS_DIR (see Plugins.list/run), so a
|
||||
# same-named private plugin never shadows the built-in one.
|
||||
PLUGINS_DIRS = [PLUGINS_DIR, File.join(DATA_DIR, "plugins")].freeze
|
||||
PLUGIN_SETTINGS = File.join(DATA_DIR, "plugin_settings.json")
|
||||
|
||||
# Shared secret for the Garmin LiveTrack webhook (a Google Apps Script
|
||||
# watching Gmail for LiveTrack emails, see docs/deployment.adoc) — not a
|
||||
@@ -471,6 +479,103 @@ module Maptool
|
||||
warn "can: #{CAN_CONFIG_PATH}: action #{action.inspect}: #{e.message} — skipped"
|
||||
nil
|
||||
end
|
||||
# can.json's "keypads": keys and knobs as channels for the screen
|
||||
# profile's bindings (Keypad).
|
||||
KEYPAD = begin
|
||||
k = CAN_CONFIG&.dig("keypads")
|
||||
k && !k.empty? ? Keypad.new(k) : nil
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: keypads: #{e.message} — no keypads"
|
||||
nil
|
||||
end
|
||||
CAN_DECODER.set_node(:keypad, KEYPAD.signals) if KEYPAD
|
||||
|
||||
# Frames maptool puts on the bus (LEDs, outputs, TIME): one socket on
|
||||
# the first interface, opened when first needed, again after an error.
|
||||
CAN_TX_MUTEX = Mutex.new
|
||||
def self.can_send(frame)
|
||||
CAN_TX_MUTEX.synchronize do
|
||||
@can_tx ||= Can.open(CAN_CONFIG.fetch("interfaces").first)
|
||||
@can_tx.write(frame.pack)
|
||||
rescue SocketError, SystemCallError
|
||||
@can_tx&.close
|
||||
@can_tx = nil
|
||||
raise
|
||||
end
|
||||
end
|
||||
|
||||
# can.json's "outputs": relay modules driven by the profile's bindings (Outputs).
|
||||
OUTPUTS = begin
|
||||
o = CAN_CONFIG&.dig("outputs")
|
||||
o && !o.empty? ? Outputs.new(o) { |frame| App.can_send(frame) } : nil
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: outputs: #{e.message} — no outputs"
|
||||
nil
|
||||
end
|
||||
|
||||
# CANopen TIME while nobody else sends it (can.json's "time": false: never).
|
||||
CAN_TIME = CAN_CONFIG && CAN_CONFIG.fetch("time", true) && !test? ? Can::TimeProducer.new { |f| App.can_send(f) } : nil
|
||||
|
||||
# The keypads' bindings: the ones saved in /keypad.html (data/drive/
|
||||
# bindings.json, this car's), else the screen profile's defaults; read
|
||||
# again when the file changes. The browser takes them from GET /api/keypad/bindings.
|
||||
DRIVE_PROFILE_PATH = File.join(__dir__, "public", "drive", "road.json")
|
||||
BINDINGS_PATH = File.join(DATA_DIR, "drive", "bindings.json")
|
||||
def self.bindings
|
||||
path = File.exist?(BINDINGS_PATH) ? BINDINGS_PATH : DRIVE_PROFILE_PATH
|
||||
key = [path, File.mtime(path)]
|
||||
@bindings = [key, JSON.parse(File.read(path)).fetch("bindings", [])] unless @bindings&.first == key
|
||||
@bindings.last
|
||||
rescue StandardError => e
|
||||
warn "drive bindings: #{e.message}"
|
||||
[]
|
||||
end
|
||||
|
||||
BINDING_KEYS = %w[input action menu output outputs mode pulse_s period_s step led led_on].freeze
|
||||
# A saved list's check: each an input, an action / menu or an output, known modes and colours.
|
||||
def self.check_bindings(list)
|
||||
raise ArgumentError, "bindings: a list" unless list.is_a?(Array)
|
||||
|
||||
list.map do |b|
|
||||
raise ArgumentError, "a binding: an object" unless b.is_a?(Hash)
|
||||
|
||||
b = b.slice(*BINDING_KEYS).reject { |_, v| v.nil? || v == "" }
|
||||
raise ArgumentError, "a binding without an input" unless b["input"].is_a?(String) && b["input"].include?(".")
|
||||
raise ArgumentError, "#{b['input']}: unknown mode #{b['mode']}" if b["mode"] && !Outputs::MODES.include?(b["mode"])
|
||||
%w[led led_on].each { |k| raise ArgumentError, "#{b['input']}: unknown colour #{b[k]}" if b[k] && !Keypad::COLORS.key?(b[k]) }
|
||||
if b["mode"] == "positions"
|
||||
raise ArgumentError, "#{b['input']}: positions need outputs" unless b["outputs"].is_a?(Array) && b["outputs"].any? && b["outputs"].all?(String)
|
||||
|
||||
b.delete("output")
|
||||
else
|
||||
b.delete("outputs")
|
||||
end
|
||||
%w[pulse_s period_s step].each { |k| b[k] = Float(b[k]) if b[k] }
|
||||
b
|
||||
end
|
||||
end
|
||||
|
||||
def self.keypads_present
|
||||
nodes = CAN_STORE.snapshot[:nodes]
|
||||
KEYPAD ? KEYPAD.devices.select { |d| (seen = nodes.dig(d.heartbeat_node, :heartbeat_at)) && Time.now.to_f - seen < Keypad::PRESENT_S } : []
|
||||
end
|
||||
|
||||
# A keypad's key LEDs: the screen's colours (PUT /api/keypad/leds) with
|
||||
# the keys bound to outputs on top (their "led" while on, dark off),
|
||||
# sent when they change.
|
||||
KEYPAD_SCREEN_LEDS = {}
|
||||
def self.keypad_leds_frames(device)
|
||||
on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup
|
||||
if OUTPUTS
|
||||
bindings.each do |b|
|
||||
next unless Outputs.outputs_of(b).any? && b["input"].to_s.start_with?("#{device.name}.")
|
||||
|
||||
on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.active?(b) ? b.fetch("led", "red") : nil
|
||||
end
|
||||
end
|
||||
KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink"))
|
||||
end
|
||||
|
||||
# The bus recorded on the server into MF4 files (/trace.html, can-recorder/).
|
||||
CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : [])
|
||||
at_exit { CAN_RECORDER.stop }
|
||||
@@ -487,8 +592,10 @@ module Maptool
|
||||
end
|
||||
CAN_CONFIG.fetch("interfaces", []).each do |interface|
|
||||
Thread.new do
|
||||
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values|
|
||||
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"], on_frame: ->(f) { CAN_TIME&.heard(f) }) do |values|
|
||||
App.vehicle_speed_update(values["vehicle.speed"]) if values["vehicle.speed"]
|
||||
events = KEYPAD&.update(values) || []
|
||||
events.each { |e| OUTPUTS.input(e, App.bindings) } if OUTPUTS
|
||||
gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h
|
||||
next if gnss.empty? || GNSS_SIM.running?
|
||||
|
||||
@@ -498,6 +605,41 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
# Every 100 ms: the outputs (pulses ending, their state again for the
|
||||
# modules' watchdog), a keypad gone silent letting go of what it held,
|
||||
# the keypads' LEDs when they changed; every second the TIME.
|
||||
if CAN_CONFIG && !test? && (OUTPUTS || KEYPAD || CAN_TIME)
|
||||
Thread.new do
|
||||
was_present = []
|
||||
leds_sent = {}
|
||||
time_at = 0
|
||||
loop do
|
||||
begin
|
||||
OUTPUTS&.tick
|
||||
present = App.keypads_present
|
||||
(was_present.map(&:name) - present.map(&:name)).each { |name| OUTPUTS&.keypad_lost(name) }
|
||||
leds_sent = {} if present != was_present
|
||||
was_present = present
|
||||
present.select { |d| d.protocol == "pkp" }.each do |d|
|
||||
frames = App.keypad_leds_frames(d)
|
||||
next if leds_sent[d.name] == frames.map(&:data)
|
||||
|
||||
frames.each { |f| App.can_send(f) }
|
||||
leds_sent[d.name] = frames.map(&:data)
|
||||
end
|
||||
if CAN_TIME && Time.now.to_f - time_at >= Can::TimeProducer::INTERVAL_S
|
||||
time_at = Time.now.to_f
|
||||
CAN_TIME.tick
|
||||
end
|
||||
rescue StandardError => e
|
||||
warn "can tick: #{e.message}" unless e.message == @last_tick_error
|
||||
@last_tick_error = e.message
|
||||
end
|
||||
sleep Outputs::REPEAT_S
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Live data off the home MQTT broker (MQTT_URL), polled by the frontend
|
||||
# from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays:
|
||||
# the LTE GNSS tracker's position and USB power (+ its trail, optionally
|
||||
@@ -551,6 +693,11 @@ module Maptool
|
||||
erb :can, layout: false
|
||||
end
|
||||
|
||||
# The keypads' bindings, edited (after the Design canvas' GridBinding).
|
||||
get "/keypad.html" do
|
||||
erb :keypad, layout: false
|
||||
end
|
||||
|
||||
# Every CAN frame as it came, decoded (polls GET /api/can?since=).
|
||||
get "/trace.html" do
|
||||
erb :trace, layout: false
|
||||
@@ -812,6 +959,87 @@ module Maptool
|
||||
json folder: TRIP_LOG.stop
|
||||
end
|
||||
|
||||
# The recording's days (lib/maptool/trip_days.rb) — the running trip's, or
|
||||
# the last one's: totals, the days with what cut them, and (?track=1) the
|
||||
# line as [lon, lat, t] for picking a piece on the map.
|
||||
get "/api/trip/log/days" do
|
||||
require_login!
|
||||
rec = TRIP_LOG.recording
|
||||
halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2
|
||||
|
||||
points = rec[:points]
|
||||
days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined]))
|
||||
body = { folder: rec[:folder], active: rec[:active], started_at: rec[:started_at],
|
||||
totals: TripDays.stats(points).merge(days: days.size, started_at: points.first[3], ended_at: points.last[3]),
|
||||
days: days.map { |d| d.merge(bbox: TripDays.bbox(points[d[:from]...d[:to]])) } }
|
||||
body[:track] = points.map { |lon, lat, _, t| [lon.round(6), lat.round(6), t] } if params[:track]
|
||||
json body
|
||||
end
|
||||
|
||||
# {"cut": t} or {"join": t} (epoch s; a cut with none: now).
|
||||
post "/api/trip/log/days" do
|
||||
require_login!
|
||||
body = JSON.parse(request.body.read)
|
||||
kind = body.key?("join") ? :join : :cut
|
||||
TRIP_LOG.mark(kind, Float(body[kind.to_s] || Time.now.to_f))
|
||||
json ok: true
|
||||
rescue JSON::ParserError, TypeError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
rescue ArgumentError => e
|
||||
halt 422, json(error: e.message)
|
||||
end
|
||||
|
||||
# The recording as GPX: ?days=1,2 (those days), ?from=t&to=t (a piece),
|
||||
# neither: the whole trip — a track per day (?per_day=1: a .gpx per day in
|
||||
# a .zip), with ?stops=1 the trip's stops near the line, ?plan=1 the
|
||||
# planned route, ?pauses=1 the stands as waypoints.
|
||||
get "/api/trip/log/export" do
|
||||
require_login!
|
||||
rec = TRIP_LOG.recording
|
||||
halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2
|
||||
|
||||
points = rec[:points]
|
||||
days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined]))
|
||||
name = rec[:folder].to_s.delete_prefix("Trips/")
|
||||
label = ->(d) { "#{name} · Day #{d[:index]} · #{Time.at(d[:started_at]).strftime('%Y-%m-%d')}" }
|
||||
pieces = if params[:from] && params[:to]
|
||||
from, to = [params[:from], params[:to]].map(&:to_f).sort
|
||||
piece = points.select { |p| p[3].between?(from, to) }
|
||||
[["#{name} · #{Time.at(from).strftime('%d. %m. %H:%M')} – #{Time.at(to).strftime('%H:%M')}", piece]]
|
||||
else
|
||||
picked = params[:days].to_s.split(",").map(&:to_i)
|
||||
days.select { |d| picked.empty? || picked.include?(d[:index]) }.map { |d| [label.(d), points[d[:from]...d[:to]]] }
|
||||
end
|
||||
pieces = pieces.reject { |_, piece| piece.size < 2 }
|
||||
halt 422, json(error: "nothing to export") if pieces.empty?
|
||||
|
||||
folder = rec[:folder] ? (LIBRARY.folder_features(rec[:folder]) rescue []) : []
|
||||
extras = lambda do |piece|
|
||||
line = piece.map { |p| p.first(2) }
|
||||
out = []
|
||||
out += folder.select { |f| f.dig("properties", "kind") == "route" } if params[:plan]
|
||||
if params[:stops]
|
||||
out += folder.select { |f| f.dig("geometry", "type") == "Point" && Corridor.distance_km(f["geometry"]["coordinates"], line) <= 0.3 }
|
||||
end
|
||||
out += TripDays.pauses(piece) if params[:pauses]
|
||||
out
|
||||
end
|
||||
if params[:per_day] && pieces.size > 1
|
||||
content_type "application/zip"
|
||||
attachment "#{name}.zip"
|
||||
Zip::OutputStream.write_buffer do |zip|
|
||||
pieces.each do |title, piece|
|
||||
zip.put_next_entry("#{title.tr('/', '-')}.gpx")
|
||||
zip.write(TripDays.gpx([[title, piece]], extras.(piece)))
|
||||
end
|
||||
end.string
|
||||
else
|
||||
content_type "application/gpx+xml"
|
||||
attachment "#{pieces.size == 1 ? pieces.first.first.tr('/', '-') : name}.gpx"
|
||||
TripDays.gpx(pieces, extras.(pieces.flat_map(&:last)))
|
||||
end
|
||||
end
|
||||
|
||||
get "/api/trip" do
|
||||
require_login!
|
||||
trip = TRIP_STORE.get
|
||||
@@ -825,7 +1053,9 @@ module Maptool
|
||||
body = JSON.parse(request.body.read, symbolize_names: true)
|
||||
halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) }
|
||||
|
||||
json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing]) do |locations, vehicle, avoid|
|
||||
json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing],
|
||||
name: body[:name], start: body[:start], day_start: body[:day_start], note: body[:note],
|
||||
budget: body[:budget], fuel_price: body[:fuel_price]) do |locations, vehicle, avoid|
|
||||
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
|
||||
end)
|
||||
rescue JSON::ParserError
|
||||
@@ -926,6 +1156,17 @@ module Maptool
|
||||
center: center, kiwix_url: KIWIX_URL)
|
||||
end
|
||||
|
||||
# A link pasted into the search → a place (lib/maptool/link_place.rb).
|
||||
# The server fetches the page, so only for a logged-in user.
|
||||
get "/api/link" do
|
||||
require_login!
|
||||
place = LinkPlace.resolve(params[:url].to_s)
|
||||
halt 404, json(error: "no coordinates in that link or its page") unless place
|
||||
json place
|
||||
rescue LinkPlace::Error => e
|
||||
halt 422, json(error: e.message)
|
||||
end
|
||||
|
||||
# Pinged once per page load (public/js/map.js) — url is a same-origin
|
||||
# path (not kiwix-serve's own address, which the browser can't reach
|
||||
# directly behind the reverse proxy in front of this app), proxied by
|
||||
@@ -1261,32 +1502,65 @@ module Maptool
|
||||
# for the contract) — read-only, doesn't need require_login! the way
|
||||
# actually running one does below.
|
||||
get "/api/plugins" do
|
||||
json Plugins.list(PLUGINS_DIRS)
|
||||
saved = Plugins.saved_settings(PLUGIN_SETTINGS)
|
||||
json(Plugins.list(PLUGINS_DIRS).map { |p| p.merge("set" => (saved[p["name"]] || {}).keys) })
|
||||
end
|
||||
|
||||
# A plugin's settings (its plugin.json "settings": a login cookie, a key):
|
||||
# {KEY: value}, an empty value clears it. Kept in data/, never sent back.
|
||||
put "/api/plugins/:name/settings" do
|
||||
require_login!
|
||||
json set: Plugins.save_settings(PLUGIN_SETTINGS, PLUGINS_DIRS, params[:name], JSON.parse(request.body.read))
|
||||
rescue Plugins::RunError => e
|
||||
halt 404, json(error: e.message)
|
||||
rescue JSON::ParserError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
end
|
||||
|
||||
# Runs one plugin for the given bbox (the current map viewport, from
|
||||
# the frontend's "Run for this area" button) and imports its GeoJSON
|
||||
# output into a folder of its own, named after the area's center and
|
||||
# the run's time — so one run's POIs stay apart from another's.
|
||||
#
|
||||
# route=1&corridor_km=N instead: along the shared trip's route, N km
|
||||
# either side (a plugin with "route": true covers just that; the points
|
||||
# further off are dropped either way), into the recorded trip's folder
|
||||
# when one is running.
|
||||
post "/api/plugins/:name/run" do
|
||||
require_login!
|
||||
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
||||
env = Plugins.saved_settings(PLUGIN_SETTINGS)[params[:name]] || {}
|
||||
if params[:route]
|
||||
coords = TRIP_STORE.get[:route]&.dig(:geometry, :coordinates)
|
||||
halt 422, json(error: "the trip has no route") unless coords && coords.size >= 2
|
||||
corridor = params[:corridor_km].to_f
|
||||
halt 400, json(error: "corridor_km must be 0.5 to 50") unless (0.5..50).cover?(corridor)
|
||||
|
||||
geojson = Tempfile.create(["route", ".geojson"]) do |file|
|
||||
file.write(JSON.generate(type: "LineString", coordinates: coords))
|
||||
file.flush
|
||||
Plugins.run(PLUGINS_DIRS, params[:name], Corridor.bbox(coords, corridor), route: file.path, corridor_km: corridor, env: env)
|
||||
end
|
||||
geojson["features"] = geojson["features"].select do |f|
|
||||
f.dig("geometry", "type") != "Point" || Corridor.distance_km(f["geometry"]["coordinates"], coords) <= corridor
|
||||
end
|
||||
name = "#{params[:name]} along the route #{format('%g', corridor)} km #{timestamp}"
|
||||
folder = TRIP_LOG.status[:folder] || name
|
||||
else
|
||||
bbox = %w[south west north east].map { |key| params[key].to_s }
|
||||
halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?)
|
||||
|
||||
south, west, north, east = bbox.map(&:to_f)
|
||||
begin
|
||||
geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east])
|
||||
rescue Plugins::RunError => e
|
||||
halt 502, json(error: e.message)
|
||||
end
|
||||
|
||||
geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east], env: env)
|
||||
center_lat = format("%.2f", (south + north) / 2)
|
||||
center_lon = format("%.2f", (west + east) / 2)
|
||||
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
||||
name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
|
||||
folder = name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
|
||||
end
|
||||
|
||||
keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
|
||||
json path: keys.first, tree: LIBRARY.tree
|
||||
keys = LIBRARY.import(folder: folder, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
|
||||
json path: keys.first, tree: LIBRARY.tree, count: geojson["features"].size
|
||||
rescue Plugins::RunError => e
|
||||
halt 502, json(error: e.message)
|
||||
end
|
||||
|
||||
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —
|
||||
@@ -1411,7 +1685,94 @@ module Maptool
|
||||
snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] }
|
||||
# simulated: the GNSS simulation (/sim.html) stands in for gnss.*
|
||||
actions = CAN_ACTIONS.map { |a| { name: a.name, node: a.node } }
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions)
|
||||
# time: whether maptool sends CANopen TIME (off while another node does)
|
||||
time = CAN_TIME && { sending: !CAN_TIME.others? }
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions, time: time)
|
||||
end
|
||||
|
||||
# The keypads (can.json's "keypads") for drive mode: which are on the bus
|
||||
# (their heartbeat; with LEDs or not) and the events on their channels
|
||||
# after seq :since — a long poll, answered as soon as one comes (10 s at
|
||||
# most). ponytail: holds one of Puma's threads per drive-mode screen,
|
||||
# fine for the one or two in the car.
|
||||
get "/api/keypad" do
|
||||
require_login!
|
||||
halt 404, json(error: "no keypads in data/can.json") unless KEYPAD
|
||||
since = params[:since] && Integer(params[:since], exception: false)
|
||||
present = App.keypads_present
|
||||
answer = KEYPAD.events(present.empty? ? nil : since)
|
||||
json answer.merge(present: present.map { |d| { name: d.name, leds: d.protocol == "pkp" } })
|
||||
end
|
||||
|
||||
# The screen's colours for a keypad's key LEDs: { "keypad": "pad", "on":
|
||||
# { "K1": "cyan", … }, "blink": { … } } (Keypad::COLORS); the keys bound
|
||||
# to outputs come on top, the 100 ms tick sends them (App.keypad_leds_frames).
|
||||
put "/api/keypad/leds" do
|
||||
require_login!
|
||||
halt 404, json(error: "no keypads in data/can.json") unless KEYPAD
|
||||
body = JSON.parse(request.body.read)
|
||||
begin
|
||||
KEYPAD.led_frames(body["keypad"].to_s, body["on"], body["blink"]) # checks the names and colours
|
||||
rescue ArgumentError => e
|
||||
halt 400, json(error: e.message)
|
||||
end
|
||||
KEYPAD_SCREEN_LEDS[body["keypad"].to_s] = { "on" => body["on"] || {}, "blink" => body["blink"] || {} }
|
||||
json ok: true
|
||||
end
|
||||
|
||||
# The bindings and what they can bind (/keypad.html, drive mode): the
|
||||
# keypads' channels, the outputs, the colours; saved: this car's own
|
||||
# (PUT {bindings}), else the profile's (DELETE goes back to them).
|
||||
get "/api/keypad/bindings" do
|
||||
require_login!
|
||||
keypads = (KEYPAD&.devices || []).map do |d|
|
||||
keys = d.protocol == "pkp" ? (1..d.keys).map { |k| "K#{k}" } : []
|
||||
{ name: d.name, protocol: d.protocol, node: d.node, channels: (keys + d.inputs.keys).uniq }
|
||||
end
|
||||
outputs = (OUTPUTS&.snapshot || []).flat_map { |m| m[:channels].map { |c| { output: "#{m[:name]}.#{c[:n]}", label: c[:label], dimmable: m[:dimmable] } } }
|
||||
json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs,
|
||||
modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"]
|
||||
end
|
||||
|
||||
put "/api/keypad/bindings" do
|
||||
require_login!
|
||||
begin
|
||||
list = App.check_bindings(JSON.parse(request.body.read)["bindings"])
|
||||
rescue ArgumentError, JSON::ParserError => e
|
||||
halt 400, json(error: e.message)
|
||||
end
|
||||
FileUtils.mkdir_p(File.dirname(BINDINGS_PATH))
|
||||
File.write("#{BINDINGS_PATH}.tmp", JSON.pretty_generate(bindings: list))
|
||||
File.rename("#{BINDINGS_PATH}.tmp", BINDINGS_PATH)
|
||||
json bindings: App.bindings, saved: true
|
||||
end
|
||||
|
||||
delete "/api/keypad/bindings" do
|
||||
require_login!
|
||||
FileUtils.rm_f(BINDINGS_PATH)
|
||||
json bindings: App.bindings, saved: false
|
||||
end
|
||||
|
||||
# The outputs (can.json's "outputs"): each module's channels, their
|
||||
# labels and state, which bindings drive them.
|
||||
get "/api/outputs" do
|
||||
require_login!
|
||||
halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS
|
||||
bound = App.bindings.select { |b| Outputs.outputs_of(b).any? }
|
||||
json modules: OUTPUTS.snapshot, bindings: bound
|
||||
end
|
||||
|
||||
# Switches an output by hand (a tile on the screen, /sim.html):
|
||||
# { "on": true | false }, or {} to toggle.
|
||||
post "/api/outputs/:module/:n" do
|
||||
require_login!
|
||||
halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS
|
||||
output = "#{params[:module]}.#{params[:n]}"
|
||||
halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output)
|
||||
body = request.body.read
|
||||
on = body.empty? ? nil : JSON.parse(body)["on"]
|
||||
OUTPUTS.manual(output, on.nil? ? !OUTPUTS.on?(output) : !!on)
|
||||
json on: OUTPUTS.on?(output)
|
||||
end
|
||||
|
||||
# Runs can.json's action number :n (its place in GET /api/can's actions).
|
||||
@@ -1486,7 +1847,17 @@ module Maptool
|
||||
# {"trip": true}: along the shared trip's route (to try the navigation)
|
||||
route = TRIP_STORE.get[:route] if body["trip"]
|
||||
halt 422, json(error: "the trip has no route") if body["trip"] && !route
|
||||
if route then nil
|
||||
# {"track": "item:<id>"}: a library track replayed at its own speed
|
||||
if body["track"]
|
||||
begin
|
||||
line = JSON.parse(LIBRARY.geojson(body["track"].to_s))["features"].find { |f| f.dig("geometry", "type") == "LineString" }
|
||||
rescue Library::NotFound
|
||||
halt 404, json(error: "no such track")
|
||||
end
|
||||
track = line&.dig("properties", "profile")&.filter_map { |p| [p["lon"], p["lat"], p["elapsed_secs"]] if p["elapsed_secs"] }
|
||||
halt 422, json(error: "the track has no times") if track.nil? || track.size < 2
|
||||
end
|
||||
if route || track then nil
|
||||
elsif lon.nil?
|
||||
codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] }
|
||||
bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) }
|
||||
@@ -1496,7 +1867,7 @@ module Maptool
|
||||
end
|
||||
|
||||
CAN_STORE.override_prefix = "gnss."
|
||||
GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route) do |fix|
|
||||
GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route, track: track) do |fix|
|
||||
CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" })
|
||||
App.gnss_update(fix)
|
||||
end
|
||||
|
||||
+3
-3
@@ -43,9 +43,9 @@ services:
|
||||
# as the other optional secrets here. P4N_USER/P4N_PASSWORD alone
|
||||
# don't actually work here — park4night's login form is behind
|
||||
# invisible reCAPTCHA, which no browserless login can satisfy — so
|
||||
# P4N_SESSION_COOKIE (a real logged-in browser's session cookie,
|
||||
# copied out by hand and refreshed whenever it expires) is what
|
||||
# p4n2gpx.rb's make_session actually ends up using.
|
||||
# the cookies of a Firefox logged in on the host (the plugin's own
|
||||
# firefox_cookie.py on a host timer, docs/deployment.adoc) or P4N_SESSION_COOKIE (a browser's Cookie header, by hand —
|
||||
# also settable in the plugins panel) are what it ends up using.
|
||||
P4N_USER: ${P4N_USER:-}
|
||||
P4N_PASSWORD: ${P4N_PASSWORD:-}
|
||||
P4N_SESSION_COOKIE: ${P4N_SESSION_COOKIE:-}
|
||||
|
||||
@@ -193,6 +193,26 @@ Its `.env` adds:
|
||||
* `SYNC_SERVER_URL` (`https://map.priesol.net`) and `SYNC_TOKEN`: it's a sync client.
|
||||
* `SELF_UPDATE=1` — the update button (below).
|
||||
|
||||
=== park4night's login from the Pi's Firefox
|
||||
|
||||
The private p4n2gpx plugin (`data/plugins/p4n2gpx/`) borrows a logged-in
|
||||
browser's cookies (park4night's login is behind reCAPTCHA). Log in once in
|
||||
Firefox on the Pi as `randy` (on its screen or over remote desktop) and
|
||||
leave it logged in: there's no "remember me", the login is only the
|
||||
PHPSESSID session cookie, which Firefox keeps in its session store rather
|
||||
than in `cookies.sqlite`. A timer on the host runs the plugin's
|
||||
`firefox_cookie.py` as that user: it copies only park4night.com's cookies
|
||||
(both stores; profiles in `~/.config/mozilla/firefox` or `~/.mozilla/firefox`) into
|
||||
`data/plugins/p4n2gpx/firefox-cookie` (mode 600). The profile itself (every
|
||||
synced password, every site's cookies) is never mounted into the container.
|
||||
Every 15 min it also asks park4night with them, which keeps the session
|
||||
alive; once park4night refuses it, it stops asking until the next login.
|
||||
|
||||
The plugin, `p4n-cookie.service` and `p4n-cookie.timer` live in the private
|
||||
home-gitops repo (`ansible/files/p4n2gpx/`), not here: its
|
||||
`deploy-p4n2gpx` workflow runs `ansible/playbooks/p4n2gpx.yaml` against
|
||||
the Pi on every change.
|
||||
|
||||
=== Updates (a button, not CI)
|
||||
|
||||
CI deploys brick only: the car's server is often offline, and a deploy
|
||||
@@ -322,6 +342,94 @@ No tilt compensation or hard-iron calibration yet, so only roughly right
|
||||
standing level. The node goes operational by itself, so no `nmt_start`.
|
||||
Sensor16/8: `value = wire * (max - min) / (2^n - 2) + min`, all ones unknown.
|
||||
|
||||
Keypads for drive mode (`lib/maptool/keypad.rb`), the way PDMs do it: a
|
||||
device's keys and knobs become named channels, and the screen profile's
|
||||
`"bindings"` say what each one does (`public/drive/road.json`) — nothing
|
||||
in the server knows what a key is for.
|
||||
|
||||
----
|
||||
"keypads": [
|
||||
{ "name": "pad", "protocol": "pkp", "node": 20, "keys": 8, "heartbeat_node": 32,
|
||||
"inputs": { "E1": "mcu-stm32-xiao-c5.encoder_1", "E1 press": "mcu-stm32-xiao-c5.encoder_button_1",
|
||||
"E2": "mcu-stm32-xiao-c5.encoder_2", "E3": "mcu-stm32-xiao-c5.encoder_3",
|
||||
"E3 press": "mcu-stm32-xiao-c5.encoder_button_3" } } ]
|
||||
----
|
||||
|
||||
The knobs turn freely once entity 7's bits are set — an action writes it
|
||||
(a number is REAL32 at `0x2002 + 0x10 × entity`, sub 1; 7.0 = knobs 1–3):
|
||||
`{ "name": "Encoders 1-3 free turning", "node": 32, "index": "0x2072",
|
||||
"subindex": 1, "data": "0000e040" }`, once (the node keeps it).
|
||||
|
||||
`name` prefixes its channels (`pad.K1`, `pad.E3`, `pad.E3 press`).
|
||||
`"protocol": "pkp"` — a Blink Marine PKP CANopen keypad, or ours speaking
|
||||
its protocol (home-gitops `docs/canopen-nodes.adoc`): K1… come from its
|
||||
TPDO1 (`0x180+node`, a bit each, `keys` of them) with no signals, and its
|
||||
key LEDs take colours. Without it a keypad is just `inputs`: channel → any
|
||||
signal, can.json's own or a discovered node's (as `/can.html` names them);
|
||||
a channel starting with E is a knob (a free-turning counter mod 256 — set
|
||||
its bit in the 8Encoder's "Encoder Relative Modes", entity 7, e.g. by an
|
||||
`actions` SDO write), anything else a key. `heartbeat_node`: whose
|
||||
heartbeat says it's there (a real PKP has it off; ours is the XIAO's own
|
||||
node 0x20, the one with the knobs) — default `node`. The PKP waits for
|
||||
NMT Start: `"nmt_start": true`.
|
||||
|
||||
A binding in the profile: `{ "input": "pad.K5", "action": "menu", "menu":
|
||||
"close", "led": "cyan", "led_on": "green" }` — `action` a screen key's
|
||||
(`trip`, `zoomIn`, `follow`, …) or a knob's (`zoom`, `panX`, `panY`,
|
||||
`rows`), `menu` what it does while a menu is open (`rows`, `enter`,
|
||||
`close`, or any action), `led` the key LED's colour (red green blue yellow
|
||||
cyan magenta white), `led_on` while its screen key is on. `GET
|
||||
/api/keypad?since=<seq>` is a long poll of the channels' events, `PUT
|
||||
/api/keypad/leds` (`{"keypad": "pad", "on": {"K1": "cyan"}, "blink": {}}`)
|
||||
sets a PKP's key LEDs.
|
||||
|
||||
The bindings are edited in `/keypad.html` (after the Design canvas'
|
||||
GridBinding): the keypads drawn as can.json has them, a key or knob picked
|
||||
by a tap or by pressing it on the keypad, then what it drives (a screen
|
||||
key's action or an output), the output's mode, what it does in an open
|
||||
menu, its LEDs. Saved, they're this car's own, `data/drive/bindings.json`
|
||||
(`GET`/`PUT`/`DELETE /api/keypad/bindings`), and win over the profile's;
|
||||
"Back to the profile's" deletes the file. Drive mode takes them when it
|
||||
loads.
|
||||
|
||||
Outputs (`lib/maptool/outputs.rb`): relay modules on the bus, maptool the
|
||||
controller, nothing measured (no current, no feedback). A binding with an
|
||||
`output` in place of an `action` drives one channel:
|
||||
|
||||
----
|
||||
"outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true,
|
||||
"labels": { "1": "Lights", "2": "Winch in" } } ]
|
||||
----
|
||||
|
||||
`{ "input": "pad.E2 press", "output": "relays.1", "mode": "hold", "led":
|
||||
"red" }` — `mode`: `toggle` (default), `on`, `off`, `hold` (on while held;
|
||||
off when let go or when the keypad's heartbeat is gone), `pulse` (on for
|
||||
`pulse_s`, 1 s by default), `positions` (`"outputs": [a, b, …]`: a press
|
||||
steps off → a → b → … → off, a knob turns up and down, one on at a time,
|
||||
the last off before the next on), `strobe` (a press starts / stops it
|
||||
blinking, `period_s` a whole on + off, 1 s), `dimmer` (a knob sets the
|
||||
level by `step` %, 10; a press switches it on / off — only a module with
|
||||
`"dimmable": true` dims, a relay just switches). A PKP key bound to an
|
||||
output shows `led` (red by default) while it's on (a position chosen, a
|
||||
strobe running), whatever the screen says. The module's
|
||||
protocol is ours (after LD's native CAN control): RPDO1 `0x200+node`, a
|
||||
bit per channel (byte 0 channels 1–8, byte 1 9–16) — a dimmable one a
|
||||
byte per channel, 0–255, 8 channels at most — the whole state sent
|
||||
on every change and every 100 ms; the module is to switch everything off
|
||||
after 2 s without a frame. `"simulated": true` sends nothing, the state
|
||||
only lives in the server — `/sim.html` shows the relays and switches
|
||||
them by hand. `GET /api/outputs`, `POST /api/outputs/<module>/<n>` (`{"on":
|
||||
true}`, empty toggles). An output in the profile that this car's can.json
|
||||
hasn't is skipped.
|
||||
|
||||
CANopen TIME (`lib/maptool/can_time.rb`): maptool sends the TIME object
|
||||
(`0x100`, CiA 301 TIME_OF_DAY, UTC: ms after midnight + days since
|
||||
1984-01-01) once a second, but only while no other node does — once the
|
||||
GNSS node sends it (esphome-canopen has no TIME yet), maptool stays quiet
|
||||
until it's been silent 3 s. Nothing goes out while the Pi's clock is
|
||||
unset (before 2025). `"time": false` in can.json turns it off; `/can.html`
|
||||
shows who's sending it.
|
||||
|
||||
The node sends no course: `App.gnss_update` (where every fix lands, the
|
||||
node's and the GNSS simulation's) works it out from the fix ≥ 5 m back
|
||||
while moving ≥ 1.5 m/s and keeps the last one standing still, so
|
||||
|
||||
+152
-8
@@ -279,7 +279,15 @@ comes from, is one too) of *16 × 10 cells of 80 px* on the navigator's
|
||||
user's to arrange later.
|
||||
|
||||
Mockups: the Design canvas (claude.ai, private), artboards Grid,
|
||||
GridTrip, GridSearch. To be tried against: OpenCPN itself.
|
||||
GridTrip, GridSearch, GridPoints, GridLayers, GridTerrain. To be tried
|
||||
against: OpenCPN itself.
|
||||
|
||||
Built (2026-12-03): `driving.js` lays the page out as the profile's cells
|
||||
(`public/drive/road.json`), the menus in `drive_menus.js` — Trip and
|
||||
Search, Points (the library nearest the car, along the route ahead, shown,
|
||||
or by folder), Layers (the On the map panel's own switches, presets Road /
|
||||
Off-road / Overnight, + Keep saves what's on into one) and Terrain. A menu
|
||||
is a grid of cells too: a row per item, a cell per action.
|
||||
|
||||
Sources: OpenCPN manuals — Dashboard
|
||||
(opencpn-manuals.github.io/main/dashboard), inland ECDIS getting started;
|
||||
@@ -296,6 +304,25 @@ map, a menu panel or a row of keys — plus the condition that switches it
|
||||
on. Every cell is configurable; the grid differs per screen (16″
|
||||
1280×800 is 16 × 10), so profiles are per screen type. Edited in the app,
|
||||
standing only: tap a cell → widget and signal, drag a corner → its size.
|
||||
Today one profile, `public/drive/road.json` (`columns`, `rows`, the map's
|
||||
area, the menu's area and the map's beside it, `cells`: `{area, widget,
|
||||
value | action | km}`; widgets `maneuver`, `field`, `status`,
|
||||
`elevation`, `compass`, `key`); once the editor exists it saves to
|
||||
`data/` and the file is the default.
|
||||
|
||||
*Keys* (artboard GridKeys): a `key` cell's `key` is the keyboard key
|
||||
that clicks it (the uConsole has no touch), `keypad` the CAN keypad's;
|
||||
the menus' own buttons carry theirs (1 2 3, H). In an open menu ↑ ↓
|
||||
move the row (the keypad's encoder sends the same arrows), Enter its
|
||||
first button, Space its eye, + adds it, ⌫ up a folder, Esc closes.
|
||||
Every bound button shows its key in the corner, from the first key
|
||||
pressed on. Keypads are channels (`pad.K1`, `pad.E3`) and the
|
||||
profile's `"bindings"` say what each does (below, a binding), so any
|
||||
keypad fits; a keypad's heartbeat switches the labels to its channels by
|
||||
itself, a line under each screen key in its LED colour (menus cyan, the
|
||||
map white, the view amber, green while on).
|
||||
Still to do: the switch (auto / keyboard / keypad) and the mapping in our
|
||||
diagnostics.
|
||||
|
||||
*Terrain* (artboard GridTerrain): the inclinometer only off-road — on
|
||||
the road its cells show the elevation ahead. A 7 × 8 panel like a menu,
|
||||
@@ -354,10 +381,11 @@ communication is lost, a confirmation for dangerous circuits.
|
||||
|
||||
What it means for us:
|
||||
|
||||
* *maptool is the whole controller*: keypads, relay modules and lights
|
||||
are I/O; the modes, timers, strobe, interlocks, conditions and LED
|
||||
colours run in maptool — unless a device has its own firmware for that
|
||||
function, which is outside our scope.
|
||||
* *One controller*: keypads, relay modules and lights are I/O; the
|
||||
modes, timers, strobe, interlocks, conditions and LED colours run in
|
||||
one place — unless a device has its own firmware for that function,
|
||||
which is outside our scope. Today that's maptool; it moves to the
|
||||
STM32C5 on the Pi's HAT (below, "The controller on the Pi's HAT").
|
||||
* *A binding* = an input (keypad node, key or encoder) + a mode + a
|
||||
target: an output (a relay or light channel, SDO/RPDO) or a screen
|
||||
function (zoom, the next profile, the next stop). Bindings live in the
|
||||
@@ -370,9 +398,9 @@ What it means for us:
|
||||
* *The LED colour on the screen*: a thin line in the key's LED colour
|
||||
under the tile or screen key it drives — dim off, full on, blinking red
|
||||
on a fault — so it's clear which key controls what.
|
||||
* *Fail-safe*: a Hold output goes off when the keypad or maptool goes
|
||||
silent; a relay node needs a heartbeat consumer on maptool and its own
|
||||
safe state.
|
||||
* *Fail-safe*: a Hold output goes off when the keypad or the controller
|
||||
goes silent; a relay node consumes the controller's heartbeat and has
|
||||
its own safe state.
|
||||
* *Encoders*: a value (dimmer, volume), a changer (profiles, wrap) or a
|
||||
parameter controller. The interim (Blink Marine style) keypad has 8
|
||||
keys and 8 encoders: two move the map, one zooms, the rest are bound
|
||||
@@ -397,6 +425,122 @@ ECUMaster, "How-to Set Up Keyboards with Encoders in PMU" (v1.0,
|
||||
2026-01-09); ECUMaster USA, CAN keypads with the PMU16; HP Academy, PDM
|
||||
control pad setup.
|
||||
|
||||
=== What the military vehicles do (MilCAN, NGVA; notes, 2026-12-05)
|
||||
|
||||
From a chat with Gemini, checked only partly — treat the details as
|
||||
leads, not facts.
|
||||
|
||||
* *MilCAN* (the MilCAN working group, UK): *MilCAN A* on 29-bit
|
||||
identifiers, J1939-like; *MilCAN B* on CANopen (11-bit). Used for the
|
||||
vehicle electronics (vetronics: power, lights, panels, keypads), the
|
||||
engine stays on its own J1939. *NGVA* (NATO Generic Vehicle
|
||||
Architecture, STANAG 4754) puts Ethernet on top for data and video,
|
||||
CAN/J1939 stays for the automotive side — close to our maptool + CANopen
|
||||
split.
|
||||
* *Connectors*: MIL-DTL-38999, 150–400 € a pair — not for us. Gemini's
|
||||
"7-pin vetronics pinout" (V+, GND, CAN_H, CAN_L, wake, interlock,
|
||||
shield) is not a standard we could find; the two extra signals are
|
||||
still worth having: *a wake line* and *a hardware interlock*.
|
||||
Dual CAN (A/B on both sides of the hull) is beyond what a car needs.
|
||||
|
||||
What we can borrow:
|
||||
|
||||
* *Silent Watch* — parked for days on battery: every node asleep at
|
||||
microamps, woken by a key, the ignition / wake line or a CAN wake-up.
|
||||
Node side: a transceiver with a wake input and INH (TCAN1043 wakes on
|
||||
any bus activity, WUP; TJA1145 / TCAN1145 also by a selected frame —
|
||||
partial networking); STM32 in Stop. For later: whether ESPHome and
|
||||
our CANopen can sleep and wake that way is unknown, and the node PCBs
|
||||
have to be designed around the chosen transceiver (its wake pin, INH
|
||||
switching the regulator). maptool's side: a *Sleep* action
|
||||
(all outputs to their safe state, nodes to NMT stopped / sleep, the
|
||||
screen off) and what wakes what.
|
||||
* *Blackout / camp mode* — only our own devices, one key: keypad LEDs to ~2 % in a dim red,
|
||||
the screen to Night at its lowest, the auxiliary outside lights
|
||||
(awning, work lights) off and *inhibited* (the door no longer turns the
|
||||
awning light on) until it's left. A screen profile + a condition on
|
||||
the outputs, not a new mechanism. The road lights are the car's own
|
||||
and stay untouched (the military's blackout keeps dim blackout stop
|
||||
lights too; on a public road it's not ours to switch).
|
||||
* *Smart fuses (SSPC)*: nothing new — that's the PDM node (dingoPDM and
|
||||
the like: high-side switches with current sense, trip on a short, reset
|
||||
over CAN); its current and faults on the switch tiles and load shedding
|
||||
by battery voltage are already in the virtual switch panel's TODO.
|
||||
* *Hardware interlock*: a wire that drops the power outputs (winch,
|
||||
inverter, heater) even with a hung MCU or a dead bus — a node's own
|
||||
safe state, maptool only shows it.
|
||||
|
||||
*Powering the Pi and the ignition* — two ways:
|
||||
|
||||
. *The Pi on the bus*: a 6-pin Deutsch DT — 12 V, GND, CAN H, CAN L, IGN
|
||||
and one spare (seen like that on another project); the Pi watches IGN
|
||||
and shuts itself down cleanly a while after the ignition goes off.
|
||||
. *The Pi on 12 V only* (the usual way, preferred): the car's CAN is
|
||||
read by *our gateway node*, which tells "the car is running" from the
|
||||
car's CAN data or from its own IGN input. The Pi then needs only power
|
||||
(12 V, GND, possibly IGN — a separate connector, like
|
||||
https://www.reddit.com/r/raspberry_pi/comments/1codbfw/raspberry_pi_for_automotive_applications_update/[r/raspberry_pi,
|
||||
"Raspberry Pi for automotive applications"]) and can sit anywhere in
|
||||
the car. A *HAT with an STM32C5* is its power supervisor: it turns the
|
||||
Pi on when the car runs or when something on the network needs it
|
||||
(a node, the tablet), asks it to shut down and cuts its power after,
|
||||
and measures the power (voltage, current, the battery) — later more.
|
||||
The HAT also carries the Pi's own CAN (a controller on SPI such as the
|
||||
MCP2518FD + a transceiver, so maptool keeps its `can0`); the STM32C5
|
||||
sits on the same bus as a node of its own and is the Pi's *watchdog*:
|
||||
it consumes maptool's heartbeat and power-cycles a Pi that hung.
|
||||
|
||||
IGN (or the gateway's "running") is also the simplest wake signal for
|
||||
the nodes.
|
||||
|
||||
The nodes' side (transceiver, wake pin, PROFET board) belongs in
|
||||
home-gitops `docs/canopen-nodes.adoc`.
|
||||
|
||||
=== The controller on the Pi's HAT (decided 2026-12-05)
|
||||
|
||||
The outputs' logic leaves maptool for the *STM32C5 on the Pi's HAT*, the
|
||||
way PDMs (ECUMaster PMU, MaxxECU) keep the keypad and output logic in
|
||||
themselves rather than on the display.
|
||||
|
||||
* *One owner of every output.* The keypads, the `mcu-lvgl` panel and
|
||||
maptool only send *requests* (toggle, on, off, a level); the controller
|
||||
decides, drives the output nodes and sends the outputs' state in a TPDO
|
||||
that everyone draws from. No two devices write to the same relay.
|
||||
* *It works with the Pi off.* The HAT's STM32C5 runs whenever there are
|
||||
12 V (it's the Pi's power supervisor and watchdog anyway), so the lights
|
||||
and the pump work while the Pi boots (20–30 s), hangs or is off at camp.
|
||||
* *The chip*: the same STM32C5A3CGT6 as the nodes (Cortex-M33, 144 MHz,
|
||||
1 MB internal flash, two FDCANs, LQFP48) plus the board's 16 MB
|
||||
external flash. An STM32H was considered and dropped: the controller is
|
||||
a state machine for a few dozen outputs, an H7 draws far more while the
|
||||
car stands (the HAT never sleeps fully, Silent Watch), needs a bigger
|
||||
package and power design, and would be a second MCU family to keep. An
|
||||
H5 only if the controller ever needs Ethernet.
|
||||
* *Firmware*: plain Zephyr, not ESPHome (which can't use the external
|
||||
flash yet). The external flash holds MCUboot's second slot (OTA over CAN
|
||||
without squeezing the 1 MB), a *black box* — who switched what, faults,
|
||||
heartbeats lost, the battery voltage — that maptool fetches when it
|
||||
comes up, so the night at camp can be seen afterwards, the bindings and
|
||||
scenes with their earlier versions (back to the last good one), and
|
||||
per-circuit current and on-time statistics.
|
||||
* *Conditions* come off the bus: speed from the GNSS node, the ignition
|
||||
from the gateway, the sun computed on the chip; a geofence (the trip's
|
||||
camp) is a point and a radius sent by maptool.
|
||||
* *maptool stays* the UI (the switch tiles, `/keypad.html`,
|
||||
`/sim.html`), the bindings' editor — `bindings.json` written to the
|
||||
controller (SDO) and kept in its flash — and the screen's own keypad
|
||||
actions (zoom, pan, menus), which it keeps reading off the bus. Today's
|
||||
`outputs.rb` stays as the simulator and the reference the firmware is
|
||||
checked against.
|
||||
* *A single point of failure*, softened: every relay node has its own safe
|
||||
state when the controller's heartbeat is lost, and a few key outputs
|
||||
(the interior light) can have an input of their own on their node.
|
||||
|
||||
Order: maptool stays the controller until the firmware is done. First
|
||||
the messages are fixed — requests, state, configuration as CANopen
|
||||
objects — so that maptool uses them now and the STM32 later, with no
|
||||
change to the other nodes.
|
||||
|
||||
== Typography
|
||||
|
||||
* Planning UI: the system sans; *National Park* (the router-carved
|
||||
|
||||
+3
-1
@@ -228,7 +228,8 @@ module Maptool
|
||||
# every retry): an adapter unplugged, not up yet or the bus gone down
|
||||
# isn't fatal, nor is anything else going wrong in here — the thread
|
||||
# never dies, it waits and starts over.
|
||||
def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5)
|
||||
# on_frame: called with every frame (CANopen TIME heard, can_time.rb).
|
||||
def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5, on_frame: nil)
|
||||
down = false
|
||||
loop do
|
||||
socket = open(interface)
|
||||
@@ -241,6 +242,7 @@ module Maptool
|
||||
frame = Frame.unpack(bytes)
|
||||
next unless frame
|
||||
|
||||
on_frame&.call(frame)
|
||||
values = decoder.decode(frame)
|
||||
store.record(interface, frame, values)
|
||||
yield(values) if block_given? && !values.empty?
|
||||
|
||||
@@ -6,15 +6,19 @@ module Maptool
|
||||
# writes every interface's frames into ASAM MDF4 files, one per segment
|
||||
# (`<dir>/<UTC start>.mf4`, asammdf with a DBC, CSS Electronics' tools);
|
||||
# this starts it, stops it (SIGTERM: the segment being recorded is
|
||||
# written) and lists what it wrote.
|
||||
# written) and lists what it wrote. Segments older than `keep` seconds
|
||||
# go (it's diagnostics, ~85 MB an hour at 1000 frames/s): when listed and
|
||||
# every segment while recording; `keep` nil keeps them all.
|
||||
class Recorder
|
||||
NAME = /\A\d{8}-\d{6}\.mf4\z/
|
||||
STOP_WAIT = 10 # s for the last segment to be written
|
||||
|
||||
attr_reader :dir, :error, :started_at
|
||||
|
||||
def initialize(dir, interfaces, binary: ENV.fetch("CAN_RECORDER", "can-recorder"), segment: 300)
|
||||
def initialize(dir, interfaces, binary: ENV.fetch("CAN_RECORDER", "can-recorder"), segment: 300,
|
||||
keep: (ENV.fetch("CAN_REC_KEEP_HOURS", "24").to_f * 3600).then { |s| s.positive? ? s : nil })
|
||||
@dir = dir
|
||||
@keep = keep
|
||||
@interfaces = interfaces
|
||||
@binary = binary
|
||||
@segment = segment
|
||||
@@ -35,6 +39,8 @@ module Maptool
|
||||
@pid = pid
|
||||
@started_at = Time.now.to_f
|
||||
@error = nil
|
||||
waiter = @waiter
|
||||
Thread.new { loop { prune; break if waiter.join(@segment) } }
|
||||
rescue SystemCallError => e
|
||||
@error = "#{@binary}: #{e.message}"
|
||||
raise
|
||||
@@ -57,12 +63,25 @@ module Maptool
|
||||
def files
|
||||
return [] unless Dir.exist?(@dir)
|
||||
|
||||
prune
|
||||
Dir.children(@dir).grep(NAME).sort.reverse.map do |name|
|
||||
stat = File.stat(File.join(@dir, name))
|
||||
{ name: name, size: stat.size, at: stat.mtime.to_f }
|
||||
end
|
||||
end
|
||||
|
||||
def prune
|
||||
return unless @keep && Dir.exist?(@dir)
|
||||
|
||||
old = Time.now - @keep
|
||||
Dir.children(@dir).grep(NAME).each do |name|
|
||||
path = File.join(@dir, name)
|
||||
File.delete(path) if File.mtime(path) < old
|
||||
rescue SystemCallError
|
||||
nil # gone meanwhile
|
||||
end
|
||||
end
|
||||
|
||||
def path(name)
|
||||
path = File.join(@dir, name)
|
||||
path if NAME.match?(name) && File.file?(path)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
require_relative "can"
|
||||
|
||||
module Maptool
|
||||
module Can
|
||||
# CANopen TIME (CiA 301, COB-ID 0x100): the nodes' clock off the bus.
|
||||
# maptool sends it only while nobody else does — the GNSS node, once
|
||||
# esphome-canopen has TIME, gives the real one off the satellites; heard
|
||||
# from it, maptool stays quiet until it's gone for 3 intervals.
|
||||
class TimeProducer
|
||||
ID = 0x100
|
||||
EPOCH = Time.utc(1984, 1, 1)
|
||||
INTERVAL_S = 1
|
||||
# ponytail: a clock before this is taken for unset (a Pi without its
|
||||
# RTC or NTP yet) and nothing is sent; chrony's sync state if that's wrong
|
||||
MIN_YEAR = 2025
|
||||
|
||||
# TIME_OF_DAY: ms after midnight (28 bits, u32 LE), days since 1984-01-01 (u16 LE), UTC.
|
||||
def self.frame(time)
|
||||
t = time.utc
|
||||
midnight = Time.utc(t.year, t.month, t.day)
|
||||
ms = ((t - midnight) * 1000).floor
|
||||
Frame.new(ID, [ms & 0x0FFFFFFF, ((midnight - EPOCH) / 86_400).round].pack("L<S<"), false)
|
||||
end
|
||||
|
||||
def self.parse(data)
|
||||
ms, days = data.unpack("L<S<")
|
||||
EPOCH + days * 86_400 + (ms & 0x0FFFFFFF) / 1000.0
|
||||
end
|
||||
|
||||
def initialize(&send)
|
||||
@send = send
|
||||
@sent = []
|
||||
@others_at = nil
|
||||
end
|
||||
|
||||
# A TIME frame read off the bus: ours (just sent, the reader's socket
|
||||
# gets it too) or someone else's.
|
||||
def heard(frame, at: Time.now.to_f)
|
||||
return unless frame.id == ID && !frame.extended
|
||||
|
||||
@others_at = at unless @sent.include?(frame.data)
|
||||
end
|
||||
|
||||
def others? (at = Time.now.to_f) = !!@others_at && at - @others_at < 3 * INTERVAL_S
|
||||
|
||||
# Every INTERVAL_S: sends the time unless another producer is on or the clock isn't set.
|
||||
def tick(now = Time.now)
|
||||
return :others if others?(now.to_f)
|
||||
return :unset if now.year < MIN_YEAR
|
||||
|
||||
f = self.class.frame(now)
|
||||
@sent = (@sent + [f.data]).last(5)
|
||||
@send&.call(f)
|
||||
:sent
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
t = Time.utc(2026, 12, 4, 13, 45, 30.25)
|
||||
f = Maptool::Can::TimeProducer.frame(t)
|
||||
raise f.data.unpack1("H*") unless f.id == 0x100 && f.data.bytesize == 6
|
||||
raise Maptool::Can::TimeProducer.parse(f.data).inspect unless (Maptool::Can::TimeProducer.parse(f.data) - t).abs < 0.001
|
||||
sent = []
|
||||
p = Maptool::Can::TimeProducer.new { |x| sent << x }
|
||||
raise "send" unless p.tick(t) == :sent
|
||||
p.heard(sent.last, at: t.to_f) # our own echo
|
||||
raise "own echo" unless p.tick(t + 1) == :sent
|
||||
p.heard(Maptool::Can::TimeProducer.frame(t + 0.5), at: t.to_f + 1) # the GNSS node's
|
||||
raise "quiet" unless p.tick(t + 2) == :others
|
||||
raise "back" unless p.tick(t + 5) == :sent
|
||||
raise "unset" unless Maptool::Can::TimeProducer.new.tick(Time.utc(1970, 1, 1)) == :unset
|
||||
puts "ok"
|
||||
end
|
||||
@@ -0,0 +1,66 @@
|
||||
module Maptool
|
||||
# A corridor either side of a route ([[lon, lat], ...]): what a plugin run
|
||||
# along the trip's route covers (lib/maptool/plugins.rb). Flat-earth
|
||||
# distances (equirectangular per segment) — fine for a few km either side.
|
||||
module Corridor
|
||||
KM_PER_DEG = 111.32
|
||||
|
||||
def self.km(a, b)
|
||||
Math.hypot((b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math::PI / 180), b[1] - a[1]) * KM_PER_DEG
|
||||
end
|
||||
|
||||
# The route's vertices at least step_km apart (its ends kept): a short
|
||||
# enough line for a query (Overpass' around: takes a polyline).
|
||||
def self.thin(coords, step_km)
|
||||
kept = [coords.first]
|
||||
coords.each { |c| kept << c if km(kept.last, c) >= step_km }
|
||||
kept << coords.last unless kept.last == coords.last
|
||||
kept
|
||||
end
|
||||
|
||||
# Circles ([[lon, lat], radius km]) covering the corridor half_km either
|
||||
# side: centers every 1.5 × half_km along the line, radius 1.25 × half_km
|
||||
# (√(0.75² + 1²) = 1.25, so no gap between two of them at the corridor's edge).
|
||||
def self.circles(coords, half_km)
|
||||
step = 1.5 * half_km
|
||||
centers = [coords.first]
|
||||
left = step
|
||||
coords.each_cons(2) do |a, b|
|
||||
length = km(a, b)
|
||||
at = 0.0
|
||||
while length - at >= left
|
||||
at += left
|
||||
t = at / length
|
||||
centers << [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
|
||||
left = step
|
||||
end
|
||||
left -= length - at
|
||||
end
|
||||
centers << coords.last unless centers.last == coords.last
|
||||
centers.map { |c| [c, 1.25 * half_km] }
|
||||
end
|
||||
|
||||
# Shortest distance (km) from a point to the line.
|
||||
def self.distance_km(point, coords)
|
||||
lat0 = point[1] * Math::PI / 180
|
||||
xy = ->(c) { [(c[0] - point[0]) * Math.cos(lat0) * KM_PER_DEG, (c[1] - point[1]) * KM_PER_DEG] }
|
||||
return Math.hypot(*xy.(coords.first)) if coords.size == 1
|
||||
|
||||
coords.each_cons(2).map do |a, b|
|
||||
(ax, ay), (bx, by) = xy.(a), xy.(b)
|
||||
dx, dy = bx - ax, by - ay
|
||||
len2 = dx * dx + dy * dy
|
||||
t = len2.zero? ? 0.0 : (-(ax * dx + ay * dy) / len2).clamp(0.0, 1.0)
|
||||
Math.hypot(ax + t * dx, ay + t * dy)
|
||||
end.min
|
||||
end
|
||||
|
||||
# [south, west, north, east] around the line, half_km wider each way.
|
||||
def self.bbox(coords, half_km)
|
||||
lons, lats = coords.map(&:first), coords.map { |c| c[1] }
|
||||
dlat = half_km / KM_PER_DEG
|
||||
dlon = half_km / (KM_PER_DEG * Math.cos(lats.map(&:abs).max * Math::PI / 180))
|
||||
[lats.min - dlat, lons.min - dlon, lats.max + dlat, lons.max + dlon]
|
||||
end
|
||||
end
|
||||
end
|
||||
+33
-1
@@ -54,12 +54,16 @@ module Maptool
|
||||
# Feature), that route from its start first, random trips after it;
|
||||
# each fix to the block:
|
||||
# { lat:, lon:, speed: m/s, satellites:, hdop:, mode: 3, time: the simulation's epoch s }.
|
||||
def start(lon = nil, lat = nil, bboxes: nil, route: nil, &on_fix)
|
||||
# With track ([[lon, lat, elapsed s], ...], a library track's) instead:
|
||||
# that track replayed at its own speed, then it stops.
|
||||
def start(lon = nil, lat = nil, bboxes: nil, route: nil, track: nil, &on_fix)
|
||||
stop
|
||||
@error = nil
|
||||
@clock = Time.now.to_f
|
||||
@mutex.synchronize do
|
||||
@thread = Thread.new do
|
||||
next replay(track, &on_fix) if track
|
||||
|
||||
position, route = if route then [route[:geometry][:coordinates].first, with_detours(route)]
|
||||
elsif bboxes then random_start(bboxes)
|
||||
else [[Float(lon), Float(lat)], nil]
|
||||
@@ -120,6 +124,34 @@ module Maptool
|
||||
coords.last
|
||||
end
|
||||
|
||||
MAX_GAP_S = 30 # a stop longer than this in a replayed track: cut to it
|
||||
|
||||
# A recorded track driven again at its own pace (sped up like the
|
||||
# rest): points [lon, lat, elapsed s]; long stops shortened to MAX_GAP_S.
|
||||
def replay(points, &on_fix)
|
||||
shift = 0.0
|
||||
points = points.each_cons(2).each_with_object([[*points.first.first(2), 0.0]]) do |(a, b), out|
|
||||
shift += [b[2] - a[2] - MAX_GAP_S, 0].max
|
||||
out << [b[0], b[1], b[2] - points.first[2] - shift]
|
||||
end
|
||||
t = 0.0
|
||||
i = 1
|
||||
while i < points.size
|
||||
t += TICK_S * @speedup
|
||||
@clock += TICK_S * @speedup
|
||||
i += 1 while i < points.size - 1 && points[i][2] < t
|
||||
a, b = points[i - 1], points[i]
|
||||
dt = b[2] - a[2]
|
||||
f = dt.positive? ? ((t - a[2]) / dt).clamp(0.0, 1.0) : 1.0
|
||||
lon, lat = a.first(2).zip(b.first(2)).map { |p, q| p + (q - p) * f }
|
||||
speed = dt.positive? ? self.class.meters(a, b) / dt : 0.0
|
||||
on_fix&.call(lat: lat, lon: lon, speed: speed, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1))
|
||||
break if i == points.size - 1 && f >= 1
|
||||
|
||||
@sleep.call(TICK_S)
|
||||
end
|
||||
end
|
||||
|
||||
def speed_kmh(limit)
|
||||
(limit == "unlimited" ? UNLIMITED_KMH : limit || NO_LIMIT_KMH) * LIMIT_SHARE
|
||||
end
|
||||
|
||||
+6
-1
@@ -117,9 +117,14 @@ module Maptool
|
||||
if route
|
||||
segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) }
|
||||
else
|
||||
times = props["times"] if segments.size == 1 # a LineString's: an ISO time per point
|
||||
segments.each do |segment|
|
||||
trkseg = element.add_element("trkseg")
|
||||
segment.each { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) }
|
||||
segment.each_with_index do |c, i|
|
||||
trkpt = trkseg.add_element("trkpt", position_attributes(c))
|
||||
add_text(trkpt, "ele", c[2])
|
||||
add_text(trkpt, "time", times&.[](i))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
require_relative "can"
|
||||
|
||||
module Maptool
|
||||
# Keypads as inputs, the way PDMs do it (docs/design.adoc, "Switches and
|
||||
# the keypad: how others do it"): a device's keys and knobs become named
|
||||
# channels — "pad.K1", "pad.E3" — and the screen profile binds a channel
|
||||
# to a function ("bindings" in public/drive/road.json); nothing here knows
|
||||
# what a key does. A device is any signals off the bus; a Blink Marine PKP
|
||||
# (ours speak its protocol too, home-gitops docs/canopen-nodes.adoc) also
|
||||
# brings its keys without signals and takes LED colours back.
|
||||
#
|
||||
# can.json: "keypads": [
|
||||
# { "name": "pad", "protocol": "pkp", "node": 20, "keys": 8, "heartbeat_node": 32,
|
||||
# "inputs": { "E1": "mcu-stm32-xiao-c5.encoder_1", "E1 press": "mcu-stm32-xiao-c5.encoder_button_1" } },
|
||||
# { "name": "wheel", "heartbeat_node": 40, "inputs": { "K1": "wheel.Button 1" } } ]
|
||||
# name the channels' prefix
|
||||
# protocol "pkp": K1…K<keys> from its TPDO1 (0x180+node, a bit each), LEDs by RPDO
|
||||
# heartbeat_node whose heartbeat says it's there (a real PKP has it off) — default node
|
||||
# inputs channel → any signal (can.json's or a discovered node's, as /can.html
|
||||
# names them): a key (0 → 1 is a press), a knob (a free-turning
|
||||
# counter mod 256, a step per change) when its name starts with E,
|
||||
# its button "<knob> press"
|
||||
class Keypad
|
||||
COLORS = { "off" => 0, "red" => 1, "green" => 2, "blue" => 4, "yellow" => 3, "cyan" => 6, "magenta" => 5, "white" => 7 }.freeze
|
||||
PRESENT_S = 6 # heartbeat seen this recently (5 s interval): there
|
||||
LOG_SIZE = 200
|
||||
|
||||
# One device: its channels by signal name, its LEDs if it has them.
|
||||
Device = Struct.new(:name, :protocol, :node, :keys, :heartbeat_node, :inputs) do
|
||||
def self.parse(config)
|
||||
protocol = config["protocol"]
|
||||
raise ArgumentError, "unknown protocol #{protocol}" unless [nil, "pkp"].include?(protocol)
|
||||
|
||||
node = config["node"] && Integer(config["node"])
|
||||
raise ArgumentError, "a pkp keypad needs its node" if protocol == "pkp" && !node
|
||||
|
||||
new(config.fetch("name"), protocol, node, config.fetch("keys", 8), config["heartbeat_node"] ? Integer(config["heartbeat_node"]) : node,
|
||||
config.fetch("inputs", {}))
|
||||
end
|
||||
|
||||
# The PKP's keys as decoder signals (Decoder#set_node).
|
||||
def signals
|
||||
return [] unless protocol == "pkp"
|
||||
|
||||
(1..keys).map { |k| { "name" => "#{name}.K#{k}", "id" => format("0x%03X", 0x180 + node), "byte" => (k - 1) / 8, "bit" => (k - 1) % 8, "type" => "bit" } }
|
||||
end
|
||||
|
||||
# signal name → channel
|
||||
def channels
|
||||
@channels ||= signals.to_h { |s| [s["name"], s["name"]] }.merge(inputs.to_h { |channel, signal| [signal, "#{name}.#{channel}"] })
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :devices
|
||||
|
||||
def initialize(configs)
|
||||
@devices = configs.map { |c| Device.parse(c) }
|
||||
@by_signal = @devices.flat_map { |d| d.channels.to_a }.to_h
|
||||
@mutex = Mutex.new
|
||||
@changed = ConditionVariable.new
|
||||
@log = []
|
||||
@seq = 0
|
||||
@last = {}
|
||||
end
|
||||
|
||||
def signals = @devices.flat_map(&:signals)
|
||||
|
||||
def device(name) = @devices.find { |d| d.name == name }
|
||||
|
||||
# Decoded values → events on channels (returned too): a key or a knob's
|
||||
# button pressed (0 → 1) and let go ("… up"), a knob turned (a step
|
||||
# each, "⟳" or "⟲", wrapping at 256).
|
||||
def update(values)
|
||||
events = []
|
||||
values.each do |signal, value|
|
||||
next unless (channel = @by_signal[signal])
|
||||
|
||||
previous = @last[channel]
|
||||
@last[channel] = value
|
||||
if channel.split(".").last.match?(/\AE\d+\z/)
|
||||
next if previous.nil? # a knob's first value: where it is, no turn
|
||||
|
||||
delta = ((value.to_i - previous.to_i + 128) % 256) - 128
|
||||
events.concat(["#{channel} #{delta.positive? ? '⟳' : '⟲'}"] * delta.abs)
|
||||
elsif value.to_i == 1 && previous.to_i != 1
|
||||
events << channel
|
||||
elsif value.to_i != 1 && previous.to_i == 1
|
||||
events << "#{channel} up" # let go (the outputs' Hold)
|
||||
end
|
||||
end
|
||||
return events if events.empty?
|
||||
|
||||
@mutex.synchronize do
|
||||
events.each { |input| @log << { seq: @seq += 1, input: input } }
|
||||
@log.shift(@log.size - LOG_SIZE) if @log.size > LOG_SIZE
|
||||
@changed.broadcast
|
||||
end
|
||||
events
|
||||
end
|
||||
|
||||
# The events after seq `since`, waiting up to `wait` s for one (a long
|
||||
# poll); since nil: none, just the last seq to start from.
|
||||
def events(since, wait: 10)
|
||||
@mutex.synchronize do
|
||||
if since
|
||||
deadline = Time.now + wait
|
||||
while @seq <= since && (left = deadline - Time.now).positive?
|
||||
@changed.wait(@mutex, left)
|
||||
end
|
||||
end
|
||||
{ seq: @seq, events: since ? @log.select { |e| e[:seq] > since } : [] }
|
||||
end
|
||||
end
|
||||
|
||||
# A PKP's two LED frames (RPDO 0x200+node on, 0x300+node blink: bytes
|
||||
# R, G, B, a bit per key) from { "K1" => "cyan", … } (nil, absent: off);
|
||||
# on and blink both set alternate between the two colours.
|
||||
def led_frames(name, on, blink = {})
|
||||
d = device(name)
|
||||
raise ArgumentError, "no keypad #{name}" unless d
|
||||
raise ArgumentError, "#{name} has no LEDs" unless d.protocol == "pkp"
|
||||
|
||||
[[0x200, on], [0x300, blink]].map do |base, colors|
|
||||
masks = [0, 0, 0]
|
||||
(colors || {}).each do |channel, color|
|
||||
k = channel[/\AK(\d+)\z/, 1]&.to_i
|
||||
next unless k&.between?(1, d.keys)
|
||||
|
||||
rgb = COLORS.fetch(color.to_s.empty? ? "off" : color.to_s) { raise ArgumentError, "unknown colour #{color}" }
|
||||
3.times { |c| masks[c] |= 1 << (k - 1) if rgb[c] == 1 }
|
||||
end
|
||||
bytes = (d.keys + 7) / 8
|
||||
Can::Frame.new(base + d.node, masks.flat_map { |m| [m].pack("Q<").bytes.first(bytes) }.pack("C*"), false)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
pads = Maptool::Keypad.new([{ "name" => "pad", "protocol" => "pkp", "node" => 0x14, "inputs" => { "E3" => "x.Encoder 3", "E3 press" => "x.Button 3" } }])
|
||||
pads.update("pad.K1" => 1)
|
||||
pads.update("pad.K1" => 1) # held: no second press
|
||||
pads.update("x.Encoder 3" => 250)
|
||||
pads.update("x.Encoder 3" => 2) # +8 across the wrap
|
||||
pads.update("x.Button 3" => 1)
|
||||
pads.update("pad.K1" => 0)
|
||||
inputs = pads.events(0)[:events].map { |e| e[:input] }
|
||||
raise inputs.inspect unless inputs == ["pad.K1"] + ["pad.E3 ⟳"] * 8 + ["pad.E3 press", "pad.K1 up"]
|
||||
on, blink = pads.led_frames("pad", { "K1" => "cyan", "K2" => "white", "K3" => "yellow" }, { "K2" => "red" })
|
||||
raise on.data.unpack("C*").inspect unless on.id == 0x214 && on.data.unpack("C*") == [0b110, 0b111, 0b011]
|
||||
raise blink.data.unpack("C*").inspect unless blink.id == 0x314 && blink.data.unpack("C*") == [0b10, 0, 0]
|
||||
puts "ok"
|
||||
end
|
||||
@@ -539,6 +539,11 @@ module Maptool
|
||||
|
||||
# A folder's own items (not its subfolders') as one GPX with points and
|
||||
# tracks together — what Locus imports into one folder.
|
||||
# A folder's own features (not its subfolders').
|
||||
def folder_features(path)
|
||||
export_entries(path).map { |e| e[:feature] }
|
||||
end
|
||||
|
||||
def export_gpx(path)
|
||||
Gpx.from_features(export_entries(path).map { |e| e[:feature] })
|
||||
end
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
require "net/http"
|
||||
require "uri"
|
||||
require "ipaddr"
|
||||
require "resolv"
|
||||
require "cgi"
|
||||
|
||||
module Maptool
|
||||
# A link pasted into the search (the Design canvas' Plan) → a place:
|
||||
# { name:, lat:, lng:, url: }, or nil. The coordinates come from the URL
|
||||
# itself (Google Maps' @lat,lng / !3d!4d / ?q=, geo:), else from the page
|
||||
# it leads to (redirects followed: maps.app.goo.gl): its geo meta tags,
|
||||
# JSON-LD, or a map link in it — the way a chat app unfurls a link, one
|
||||
# page the user pasted. Only public addresses are fetched (never this
|
||||
# server's LAN).
|
||||
module LinkPlace
|
||||
MAX_BYTES = 2_000_000
|
||||
MAX_REDIRECTS = 5
|
||||
TIMEOUT_S = 10
|
||||
LAT_LNG = /(-?\d{1,2}\.\d+)\s*[,;]\s*(-?\d{1,3}\.\d+)/
|
||||
|
||||
class Error < StandardError; end
|
||||
|
||||
def self.resolve(url)
|
||||
place = from_url(url)
|
||||
return place if place
|
||||
|
||||
html, final = fetch(url)
|
||||
from_url(final) || from_html(html)&.then { |p| p.merge(url: final) }
|
||||
end
|
||||
|
||||
# Coordinates in the link itself.
|
||||
def self.from_url(url)
|
||||
text = CGI.unescape(url.to_s)
|
||||
lat, lng = text.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/)&.captures ||
|
||||
text.match(/[?&](?:q|query|ll|destination|daddr|center)=(?:loc:)?#{LAT_LNG}/)&.captures ||
|
||||
text.match(/@#{LAT_LNG}/)&.captures ||
|
||||
text.match(/\Ageo:#{LAT_LNG}/)&.captures ||
|
||||
text.match(%r{/place/#{LAT_LNG}})&.captures
|
||||
return nil unless lat
|
||||
|
||||
name = text[%r{/place/([^/@]+)/}, 1]&.tr("+", " ")
|
||||
place(name, lat, lng, url)
|
||||
end
|
||||
|
||||
# Coordinates in the page: meta tags, JSON-LD, then a map link.
|
||||
def self.from_html(html)
|
||||
meta = ->(key) { html[/<meta[^>]+(?:property|name)=["']#{Regexp.escape(key)}["'][^>]*content=["']([^"']+)/i, 1] || html[/<meta[^>]+content=["']([^"']+)["'][^>]*(?:property|name)=["']#{Regexp.escape(key)}["']/i, 1] }
|
||||
name = meta.("og:title") || html[%r{<title[^>]*>([^<]+)</title>}i, 1]
|
||||
name = CGI.unescapeHTML(name.strip) if name
|
||||
lat, lng = [meta.("place:location:latitude") || meta.("og:latitude"), meta.("place:location:longitude") || meta.("og:longitude")]
|
||||
lat, lng = (meta.("geo.position") || meta.("ICBM"))&.match(LAT_LNG)&.captures unless lat && lng
|
||||
lat, lng = html.match(/"latitude"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"longitude"\s*:\s*"?(-?\d+\.\d+)/)&.captures unless lat && lng
|
||||
lat, lng = html.scan(%r{https?://(?:www\.)?google\.[a-z.]+/maps[^"'\s<>]*}).lazy.filter_map { |u| from_url(CGI.unescapeHTML(u)) }.first&.values_at(:lat, :lng) unless lat && lng
|
||||
lat && lng ? place(name, lat, lng, nil) : nil
|
||||
end
|
||||
|
||||
def self.place(name, lat, lng, url)
|
||||
lat = Float(lat)
|
||||
lng = Float(lng)
|
||||
return nil unless lat.between?(-90, 90) && lng.between?(-180, 180)
|
||||
|
||||
{ name: name&.strip&.then { |n| n.empty? ? nil : n[0, 160] }, lat: lat, lng: lng, url: url }.compact
|
||||
end
|
||||
|
||||
# [body, final url]; raises Error.
|
||||
def self.fetch(url, redirects = MAX_REDIRECTS)
|
||||
uri = URI.parse(url)
|
||||
raise Error, "only http(s) links" unless %w[http https].include?(uri.scheme) && uri.host
|
||||
ip = public_ip(uri.host)
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = ip # the address checked, not a second lookup
|
||||
http.use_ssl = uri.scheme == "https"
|
||||
http.open_timeout = http.read_timeout = TIMEOUT_S
|
||||
request = Net::HTTP::Get.new(uri, "User-Agent" => "Mozilla/5.0 (maptool link preview)", "Accept" => "text/html")
|
||||
http.request(request) do |response|
|
||||
case response
|
||||
when Net::HTTPRedirection
|
||||
raise Error, "too many redirects" if redirects.zero?
|
||||
|
||||
return fetch(URI.join(url, response["location"]).to_s, redirects - 1)
|
||||
when Net::HTTPSuccess
|
||||
body = +""
|
||||
response.read_body do |chunk|
|
||||
body << chunk
|
||||
break if body.bytesize > MAX_BYTES
|
||||
end
|
||||
return [body.force_encoding("UTF-8").scrub, url]
|
||||
else
|
||||
raise Error, "the page answered #{response.code}"
|
||||
end
|
||||
end
|
||||
rescue URI::InvalidURIError, SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
def self.public_ip(host)
|
||||
address = Resolv.getaddress(host)
|
||||
ip = IPAddr.new(address)
|
||||
raise Error, "not a public address" if ip.private? || ip.loopback? || ip.link_local? || address.start_with?("0.") || ip == IPAddr.new("::") ||
|
||||
IPAddr.new("100.64.0.0/10").include?(ip) # CGNAT: Tailscale
|
||||
|
||||
address
|
||||
rescue Resolv::ResolvError
|
||||
raise Error, "unknown host #{host}"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,273 @@
|
||||
require "json"
|
||||
require_relative "can"
|
||||
|
||||
module Maptool
|
||||
# Outputs on the bus — relay modules for now, no current measured — and
|
||||
# the bindings that drive them from a keypad's channels (docs/design.adoc,
|
||||
# "Switches and the keypad"): maptool is the controller, the module only
|
||||
# switches. The bindings are the screen profile's (public/drive/road.json)
|
||||
# or this car's (data/drive/bindings.json) with an "output" in place of an "action":
|
||||
# { "input": "pad.K6", "output": "relays.2", "mode": "hold", "led": "red" }
|
||||
# Modes (after Garmin PowerSwitch, OnDeck, MaxxECU — docs/design.adoc):
|
||||
# toggle, on, off
|
||||
# hold on while the key is held — off when it's let go or the keypad goes silent
|
||||
# pulse on for "pulse_s" (1 s)
|
||||
# positions "outputs": [a, b, …] — a press steps off → a → b → … → off, a knob
|
||||
# turns up and down; one on at a time, the last off before the next on
|
||||
# strobe a press starts / stops it blinking, "period_s" (1 s) a whole on + off
|
||||
# dimmer a knob sets the level by "step" % (10), a press switches it on / off;
|
||||
# only a "dimmable" module dims, a relay is on above 0
|
||||
#
|
||||
# can.json: "outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true,
|
||||
# "labels": { "1": "Lights", "2": "Winch in" } },
|
||||
# { "name": "dim", "node": 49, "channels": 4, "dimmable": true, "simulated": true } ]
|
||||
# A module's protocol, ours (after LD's native CAN control): RPDO1
|
||||
# 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16) — a dimmable
|
||||
# one a byte per channel instead (0–255, up to 8) — the whole state in
|
||||
# every frame, sent on a change and every REPEAT_S; the module turns
|
||||
# everything off after 2 s without one. "simulated": no frames, the state
|
||||
# is just kept here (/sim.html shows it).
|
||||
class Outputs
|
||||
REPEAT_S = 0.1
|
||||
MODES = %w[toggle on off hold pulse positions strobe dimmer].freeze
|
||||
|
||||
Module = Struct.new(:name, :node, :channels, :simulated, :dimmable, :labels, :state, :level, keyword_init: true)
|
||||
|
||||
attr_reader :modules
|
||||
|
||||
# send: a block that puts a Frame on the bus (not called for simulated modules)
|
||||
def initialize(configs, &send)
|
||||
@modules = configs.map do |c|
|
||||
n = c.fetch("channels", 8)
|
||||
raise ArgumentError, "#{c['name']}: a dimmable module has 8 channels at most" if c["dimmable"] && n > 8
|
||||
|
||||
Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: n, simulated: c.fetch("simulated", false),
|
||||
dimmable: c.fetch("dimmable", false), labels: c.fetch("labels", {}), state: Array.new(n, false), level: Array.new(n, 100))
|
||||
end
|
||||
@send = send
|
||||
@mutex = Mutex.new
|
||||
@pulses = {}
|
||||
@held = {} # channel (the key) → outputs it holds on
|
||||
@positions = {} # channel → its position, 0 = all off
|
||||
@strobes = {} # output → [since, period]
|
||||
end
|
||||
|
||||
def find(output)
|
||||
name, ch = output.to_s.split(".", 2)
|
||||
m = @modules.find { |x| x.name == name }
|
||||
i = Integer(ch, exception: false)
|
||||
[m, i - 1] if m && i&.between?(1, m.channels)
|
||||
end
|
||||
|
||||
def on?(output)
|
||||
m, i = find(output)
|
||||
m ? @mutex.synchronize { m.state[i] } : nil
|
||||
end
|
||||
|
||||
def level(output)
|
||||
m, i = find(output)
|
||||
m ? @mutex.synchronize { m.level[i] } : nil
|
||||
end
|
||||
|
||||
def set(output, value)
|
||||
m, i = find(output)
|
||||
raise ArgumentError, "no output #{output}" unless m
|
||||
|
||||
changed = @mutex.synchronize do
|
||||
next false if m.state[i] == value
|
||||
|
||||
m.state[i] = value
|
||||
@pulses.delete(output) unless value
|
||||
true
|
||||
end
|
||||
transmit(m) if changed
|
||||
changed
|
||||
end
|
||||
|
||||
# By hand (/sim.html, a screen tile): a strobe stops.
|
||||
def manual(output, value)
|
||||
@mutex.synchronize { @strobes.delete(output) }
|
||||
set(output, value)
|
||||
end
|
||||
|
||||
# The binding's outputs: "outputs" (positions) or "output".
|
||||
def self.outputs_of(binding) = Array(binding["outputs"] || binding["output"])
|
||||
|
||||
# Whether a binding's function is on (its key's LED): a position chosen, a strobe running, else its output on.
|
||||
def active?(binding)
|
||||
outs = self.class.outputs_of(binding)
|
||||
case binding["mode"]
|
||||
when "positions" then @mutex.synchronize { @positions.fetch(binding["input"], 0) }.positive?
|
||||
when "strobe" then @mutex.synchronize { @strobes.key?(outs.first) }
|
||||
else !!on?(outs.first)
|
||||
end
|
||||
end
|
||||
|
||||
# A keypad event ("pad.K6", "pad.K6 up", "pad.E4 ⟳") through the bindings that have an output.
|
||||
def input(event, bindings, at: Time.now.to_f)
|
||||
turn = event[/ ([⟳⟲])\z/, 1]
|
||||
up = event.end_with?(" up")
|
||||
channel = event.sub(/ (up|⟳|⟲)\z/, "")
|
||||
bindings.each do |b|
|
||||
outs = self.class.outputs_of(b)
|
||||
# a profile's output this car hasn't: skipped
|
||||
next unless b["input"] == channel && outs.any? && outs.all? { |o| find(o) }
|
||||
|
||||
output = outs.first
|
||||
mode = b.fetch("mode", "toggle")
|
||||
if turn
|
||||
step = turn == "⟳" ? 1 : -1
|
||||
if mode == "positions" then position(channel, outs, @mutex.synchronize { @positions.fetch(channel, 0) } + step)
|
||||
elsif mode == "dimmer" then dim(output, step * b.fetch("step", 10).to_f)
|
||||
end
|
||||
next
|
||||
end
|
||||
case mode
|
||||
when "toggle", "dimmer" then switch(output, !on?(output)) unless up
|
||||
when "on" then set(output, true) unless up
|
||||
when "off" then set(output, false) unless up
|
||||
when "hold"
|
||||
set(output, !up)
|
||||
up ? @held.delete(channel) : (@held[channel] ||= []) << output
|
||||
when "pulse"
|
||||
next if up
|
||||
|
||||
set(output, true)
|
||||
@mutex.synchronize { @pulses[output] = at + b.fetch("pulse_s", 1).to_f }
|
||||
when "positions" then position(channel, outs, (@mutex.synchronize { @positions.fetch(channel, 0) } + 1) % (outs.size + 1)) unless up
|
||||
when "strobe"
|
||||
next if up
|
||||
|
||||
started = @mutex.synchronize { @strobes.delete(output) ? false : (@strobes[output] = [at, b.fetch("period_s", 1).to_f]) && true }
|
||||
set(output, started) # started: on now; stopped: off
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# A keypad gone silent: what it held goes off (the fail-safe).
|
||||
def keypad_lost(device)
|
||||
@held.select { |channel, _| channel.start_with?("#{device}.") }.each do |channel, outputs|
|
||||
outputs.each { |o| set(o, false) }
|
||||
@held.delete(channel)
|
||||
end
|
||||
end
|
||||
|
||||
# Every REPEAT_S: pulses ending, strobes blinking, the state sent again (the module's watchdog).
|
||||
def tick(at: Time.now.to_f)
|
||||
ended, strobes = @mutex.synchronize { [@pulses.select { |_, till| till <= at }.keys, @strobes.dup] }
|
||||
ended.each { |o| set(o, false) }
|
||||
strobes.each { |o, (since, period)| set(o, ((at - since) / (period / 2)).floor.even?) }
|
||||
@modules.each { |m| transmit(m) }
|
||||
end
|
||||
|
||||
def frame(m)
|
||||
data = if m.dimmable
|
||||
m.state.each_with_index.map { |on, i| on ? (m.level[i] * 255 / 100.0).round : 0 }.pack("C*")
|
||||
else
|
||||
[m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 }].pack("Q<").byteslice(0, (m.channels + 7) / 8)
|
||||
end
|
||||
Can::Frame.new(0x200 + m.node, data, false)
|
||||
end
|
||||
|
||||
def snapshot
|
||||
@mutex.synchronize do
|
||||
@modules.map do |m|
|
||||
{ name: m.name, node: m.node, simulated: m.simulated, dimmable: m.dimmable,
|
||||
channels: (1..m.channels).map do |n|
|
||||
{ n: n, label: m.labels[n.to_s], on: m.state[n - 1], level: m.dimmable ? m.level[n - 1] : nil, strobe: @strobes.key?("#{m.name}.#{n}") }.compact
|
||||
end }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# on with its level above 0 (a dimmer switched on at 0 comes back at 100)
|
||||
def switch(output, value)
|
||||
m, i = find(output)
|
||||
@mutex.synchronize { m.level[i] = 100 if value && m.level[i].zero? }
|
||||
set(output, value)
|
||||
end
|
||||
|
||||
def dim(output, delta)
|
||||
m, i = find(output)
|
||||
level = @mutex.synchronize { m.level[i] = (m.level[i] + delta).clamp(0, 100) }
|
||||
transmit(m) unless set(output, level.positive?)
|
||||
end
|
||||
|
||||
# The channel's position n (clamped to 0..outputs): the others off first, then its own on.
|
||||
def position(channel, outs, n)
|
||||
n = n.clamp(0, outs.size)
|
||||
@mutex.synchronize { @positions[channel] = n }
|
||||
outs.each_with_index { |o, i| set(o, false) unless i == n - 1 }
|
||||
set(outs[n - 1], true) if n.positive?
|
||||
end
|
||||
|
||||
def transmit(m)
|
||||
return if m.simulated || !@send
|
||||
|
||||
@send.call(frame(m))
|
||||
rescue StandardError => e
|
||||
warn "outputs: #{m.name}: #{e.message}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
sent = []
|
||||
out = Maptool::Outputs.new([{ "name" => "relays", "node" => 48 }, { "name" => "dim", "node" => 49, "channels" => 2, "dimmable" => true }]) { |f| sent << f }
|
||||
b = [{ "input" => "pad.K1", "output" => "relays.1" }, { "input" => "pad.K6", "output" => "relays.2", "mode" => "hold" },
|
||||
{ "input" => "pad.K7", "output" => "relays.3", "mode" => "pulse", "pulse_s" => 2 }]
|
||||
out.input("pad.K1", b)
|
||||
raise "toggle" unless out.on?("relays.1")
|
||||
out.input("pad.K6", b)
|
||||
raise "hold" unless out.on?("relays.2")
|
||||
out.keypad_lost("pad")
|
||||
raise "fail-safe" if out.on?("relays.2")
|
||||
out.input("pad.K7", b, at: 100)
|
||||
out.tick(at: 101)
|
||||
raise "pulse early" unless out.on?("relays.3")
|
||||
out.tick(at: 102.1)
|
||||
raise "pulse" if out.on?("relays.3")
|
||||
out.input("pad.K1", [{ "input" => "pad.K1", "output" => "winch.1" }]) # no such module: nothing, no error
|
||||
relay_frame = sent.reverse.find { |f| f.id == 0x230 }
|
||||
raise relay_frame.inspect unless relay_frame.data == "\x01".b
|
||||
|
||||
# positions: off → 4 → 5 → off by presses; a knob up and down, clamped
|
||||
pos = [{ "input" => "pad.K2", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" },
|
||||
{ "input" => "pad.E4", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" }]
|
||||
states = -> { [out.on?("relays.4"), out.on?("relays.5")] }
|
||||
out.input("pad.K2", pos)
|
||||
raise "pos 1" unless states.call == [true, false] && out.active?(pos[0])
|
||||
out.input("pad.K2", pos)
|
||||
raise "pos 2" unless states.call == [false, true]
|
||||
out.input("pad.K2", pos)
|
||||
raise "pos 0" unless states.call == [false, false] && !out.active?(pos[0])
|
||||
3.times { out.input("pad.E4 ⟳", pos) }
|
||||
raise "knob clamp" unless states.call == [false, true]
|
||||
out.input("pad.E4 ⟲", pos)
|
||||
raise "knob down" unless states.call == [true, false]
|
||||
|
||||
# strobe: blinks at half the period, a press stops it off
|
||||
st = [{ "input" => "pad.K3", "output" => "relays.6", "mode" => "strobe", "period_s" => 1 }]
|
||||
out.input("pad.K3", st, at: 200)
|
||||
out.tick(at: 200.6)
|
||||
raise "strobe off phase" if out.on?("relays.6")
|
||||
out.tick(at: 201.1)
|
||||
raise "strobe on phase" unless out.on?("relays.6") && out.active?(st[0])
|
||||
out.input("pad.K3", st, at: 201.2)
|
||||
out.tick(at: 201.6)
|
||||
raise "strobe stopped" if out.on?("relays.6") || out.active?(st[0])
|
||||
|
||||
# dimmer: a knob down to 0 is off, up is on again; a dimmable module sends bytes
|
||||
dm = [{ "input" => "pad.E5", "output" => "dim.1", "mode" => "dimmer", "step" => 50 }, { "input" => "pad.E5 press", "output" => "dim.1", "mode" => "dimmer" }]
|
||||
out.input("pad.E5 press", dm)
|
||||
raise "dimmer on" unless out.on?("dim.1") && out.level("dim.1") == 100
|
||||
out.input("pad.E5 ⟲", dm)
|
||||
raise sent.last.data.bytes.inspect unless sent.last.id == 0x231 && sent.last.data.bytes == [128, 0]
|
||||
out.input("pad.E5 ⟲", dm)
|
||||
raise "dimmer 0 off" if out.on?("dim.1")
|
||||
out.input("pad.E5 ⟳", dm)
|
||||
raise "dimmer up" unless out.on?("dim.1") && out.level("dim.1") == 50
|
||||
puts "ok"
|
||||
end
|
||||
@@ -58,9 +58,10 @@ module Maptool
|
||||
["operator", "Operator"],
|
||||
].freeze
|
||||
|
||||
# bbox: [south, west, north, east] (Overpass's own axis order).
|
||||
def self.fetch(bbox, timeout: 60)
|
||||
query = build_query(bbox, timeout: timeout)
|
||||
# bbox: [south, west, north, east] (Overpass's own axis order); or
|
||||
# around: [radius m, [[lon, lat], ...]] — a corridor along a line.
|
||||
def self.fetch(bbox, timeout: 60, around: nil)
|
||||
query = build_query(bbox, timeout: timeout, around: around)
|
||||
errors = OVERPASS_APIS.map do |url|
|
||||
return post(URI(url), query, timeout)
|
||||
rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e
|
||||
@@ -83,8 +84,13 @@ module Maptool
|
||||
JSON.parse(response.body)
|
||||
end
|
||||
|
||||
def self.build_query(bbox, timeout: 60)
|
||||
bbox_str = bbox.join(",")
|
||||
def self.build_query(bbox, timeout: 60, around: nil)
|
||||
bbox_str = if around
|
||||
radius, line = around
|
||||
"around:#{radius.round},#{line.map { |lon, lat| "#{lat.round(5)},#{lon.round(5)}" }.join(',')}"
|
||||
else
|
||||
bbox.join(",")
|
||||
end
|
||||
filters = CATEGORIES.keys.map do |tags|
|
||||
conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join
|
||||
"node#{conditions}(#{bbox_str});"
|
||||
|
||||
+49
-9
@@ -1,5 +1,6 @@
|
||||
require "json"
|
||||
require "open3"
|
||||
require "fileutils"
|
||||
|
||||
module Maptool
|
||||
# Runs an external "importer" script that turns a bbox into a GeoJSON
|
||||
@@ -33,26 +34,64 @@ module Maptool
|
||||
Dir.glob(File.join(dir, "*", "plugin.json")).filter_map do |manifest_path|
|
||||
name = File.basename(File.dirname(manifest_path))
|
||||
manifest = JSON.parse(File.read(manifest_path))
|
||||
{ "name" => name, "label" => manifest["label"] || name }
|
||||
{ "name" => name, "label" => manifest["label"] || name, "route" => manifest["route"] == true,
|
||||
"settings" => setting_fields(manifest) }
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] }
|
||||
end
|
||||
|
||||
# bbox: [south, west, north, east]. Raises RunError with a short
|
||||
# The settings a plugin asks for in its plugin.json ("settings": [{"key":
|
||||
# "P4N_COOKIE", "label": "…", "help": "…"}]) — a login cookie, a key —
|
||||
# set in the panel, kept server-side (never sent back to a browser) and
|
||||
# handed to the plugin's command as environment variables. A key is an
|
||||
# env var name; anything else in the list is ignored.
|
||||
SETTING_KEY = /\A[A-Z][A-Z0-9_]*\z/
|
||||
|
||||
def self.setting_fields(manifest)
|
||||
Array(manifest["settings"]).select { |f| f.is_a?(Hash) && f["key"].to_s =~ SETTING_KEY }
|
||||
.map { |f| f.slice("key", "label", "help") }
|
||||
end
|
||||
|
||||
# Saved settings: { name => { KEY => value } } in one JSON file (mode 600).
|
||||
def self.saved_settings(path)
|
||||
File.file?(path) ? JSON.parse(File.read(path)) : {}
|
||||
rescue JSON::ParserError
|
||||
{}
|
||||
end
|
||||
|
||||
# Sets (or, empty, clears) the plugin's declared keys only.
|
||||
def self.save_settings(path, dirs, name, values)
|
||||
plugin_dir = find(dirs, name)
|
||||
fields = setting_fields(JSON.parse(File.read(File.join(plugin_dir, "plugin.json")))).map { |f| f["key"] }
|
||||
all = saved_settings(path)
|
||||
mine = (all[name] || {}).merge(values.to_h.slice(*fields).transform_values { |v| v.to_s.strip })
|
||||
all[name] = mine.reject { |_, v| v.empty? }
|
||||
FileUtils.mkdir_p(File.dirname(path))
|
||||
File.write("#{path}.part", JSON.generate(all), perm: 0o600)
|
||||
File.rename("#{path}.part", path)
|
||||
all[name].keys
|
||||
end
|
||||
|
||||
def self.find(dirs, name)
|
||||
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
|
||||
|
||||
Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) } or raise RunError, "unknown plugin"
|
||||
end
|
||||
|
||||
# bbox: [south, west, north, east]. With route (a GeoJSON file's path,
|
||||
# the trip's route) and corridor_km, a plugin with "route": true in its
|
||||
# plugin.json also gets --route=<path> --corridor-km=<km> (the bbox is
|
||||
# then the corridor's). env: its saved settings. Raises RunError with a short
|
||||
# message on anything that isn't a clean run — an unknown plugin, a
|
||||
# non-zero exit, or output that isn't a GeoJSON FeatureCollection — so
|
||||
# the route can turn it into a single error response without knowing
|
||||
# any of these details itself. When the same name exists under more
|
||||
# than one of `dirs`, the first one that has it wins — same precedence
|
||||
# as list's `uniq` above.
|
||||
def self.run(dirs, name, bbox)
|
||||
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
|
||||
|
||||
plugin_dir = Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) }
|
||||
raise RunError, "unknown plugin" unless plugin_dir
|
||||
|
||||
def self.run(dirs, name, bbox, route: nil, corridor_km: nil, env: {})
|
||||
plugin_dir = find(dirs, name)
|
||||
manifest_path = File.join(plugin_dir, "plugin.json")
|
||||
|
||||
command = begin
|
||||
@@ -64,8 +103,9 @@ module Maptool
|
||||
|
||||
south, west, north, east = bbox
|
||||
args = ["--south=#{south}", "--west=#{west}", "--north=#{north}", "--east=#{east}"]
|
||||
args += ["--route=#{route}", "--corridor-km=#{corridor_km}"] if route
|
||||
|
||||
stdout, stderr, status = Open3.capture3(command, *args, chdir: plugin_dir)
|
||||
stdout, stderr, status = Open3.capture3(env.to_h, command, *args, chdir: plugin_dir)
|
||||
# First stderr line too — for a Ruby plugin that's the exception
|
||||
# message (e.g. "...: unexpected response 406"), the only clue to why.
|
||||
unless status.success?
|
||||
|
||||
+113
-10
@@ -177,10 +177,16 @@ module Maptool
|
||||
{ id: "hike", name: "Hike", type: "foot", speed: 4.5, sac: 3.0 },
|
||||
].freeze
|
||||
TYPES = %w[car bicycle foot].freeze
|
||||
# A car's fuel and emissions (low-emission zones) and what it has paid
|
||||
# for: vignettes / toll units per country, until a date (YYYY-MM-DD).
|
||||
FUELS = %w[petrol diesel lpg cng electric hybrid].freeze
|
||||
EUROS = %w[3 4 5 6 6d].freeze
|
||||
PAYMENT_KINDS = %w[vignette toll].freeze
|
||||
BICYCLE_TYPES = %w[Road Hybrid Cross Mountain].freeze
|
||||
# speed: km/h (bicycle, foot); hills: 0 avoid .. 1 seek (Valhalla's
|
||||
# use_hills); sac: the hardest SAC hiking grade allowed on foot.
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
|
||||
# wheelbase, track (m): the level gauge's geometry (drive_menus.js levelMenu).
|
||||
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, wheelbase: 1..10, track: 1..3, consumption: 1..100, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
|
||||
# Up to this weight Valhalla's "auto" costing (with height/width) fits
|
||||
# better than "truck": a camper isn't kept off roads closed to lorries.
|
||||
CAR_MAX_WEIGHT = 3.5
|
||||
@@ -228,7 +234,8 @@ module Maptool
|
||||
|
||||
[key, value]
|
||||
end
|
||||
{ id: id, name: name, type: type, bicycle_type: bicycle_type, **limits }.compact
|
||||
car = type == "car" ? car_details(name, values) : {}
|
||||
{ id: id, name: name, type: type, bicycle_type: bicycle_type, **limits, **car }.compact
|
||||
end
|
||||
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
|
||||
|
||||
@@ -236,6 +243,34 @@ module Maptool
|
||||
vehicles
|
||||
end
|
||||
|
||||
def self.car_details(name, values)
|
||||
fuel = values["fuel"].to_s.empty? ? nil : values["fuel"].to_s
|
||||
euro = values["euro"].to_s.empty? ? nil : values["euro"].to_s
|
||||
raise ArgumentError, "#{name}: invalid fuel" unless fuel.nil? || FUELS.include?(fuel)
|
||||
raise ArgumentError, "#{name}: invalid Euro class" unless euro.nil? || EUROS.include?(euro)
|
||||
|
||||
stickers = values["stickers"].to_s.strip[0, 80]
|
||||
# the levelling ramps' steps, cm ("3 6 9"), for the level gauge
|
||||
ramps = values["ramps"].to_s.scan(/\d+(?:[.,]\d+)?/).map { |s| s.tr(",", ".").to_f }
|
||||
raise ArgumentError, "#{name}: ramps: up to 6 steps of 1 to 40 cm" unless ramps.size <= 6 && ramps.all? { |cm| (1..40).cover?(cm) }
|
||||
list = values["vignettes"] || []
|
||||
raise ArgumentError, "#{name}: invalid vignettes" unless list.is_a?(Array) && list.size <= 30
|
||||
|
||||
vignettes = list.map do |v|
|
||||
country = v.is_a?(Hash) && v["country"].to_s.upcase
|
||||
kind = v.is_a?(Hash) ? (v["kind"] || "vignette").to_s : nil
|
||||
until_date = v.is_a?(Hash) ? v["until"].to_s : ""
|
||||
raise ArgumentError, "#{name}: a vignette needs a country code" unless country&.match?(/\A[A-Z]{2}\z/)
|
||||
raise ArgumentError, "#{name}: invalid vignette kind" unless PAYMENT_KINDS.include?(kind)
|
||||
raise ArgumentError, "#{name}: invalid date #{until_date}" unless until_date.empty? || until_date.match?(/\A\d{4}-\d{2}-\d{2}\z/)
|
||||
|
||||
{ country: country, kind: kind, until: (until_date unless until_date.empty?) }.compact
|
||||
end
|
||||
{ fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?),
|
||||
ramps: (ramps.sort.map { |cm| cm % 1 == 0 ? cm.to_i : cm }.join(" ") unless ramps.empty?) }
|
||||
end
|
||||
private_class_method :car_details
|
||||
|
||||
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
|
||||
# (km), time (s), the turn-by-turn instructions and, per country, the
|
||||
# km on motorways and toll roads (for vignettes and tolls).
|
||||
@@ -253,7 +288,7 @@ module Maptool
|
||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||
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],
|
||||
speed_limits: along[:speed_limits], signals: along[:signals], roads: along[:roads],
|
||||
legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting
|
||||
legs_s: legs.map { |leg| leg.dig("summary", "time") }, # the time of each, for the stops list
|
||||
# lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them
|
||||
@@ -263,9 +298,41 @@ module Maptool
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
# Routes of consecutive pieces (a trip's days with avoids of their own,
|
||||
# TripStore) as one: the lines joined, km along it shifted by the pieces
|
||||
# before, the countries summed.
|
||||
def self.merge(parts)
|
||||
return parts.first if parts.size <= 1
|
||||
|
||||
km = 0.0
|
||||
coords = []
|
||||
out = { distance_km: 0.0, time_s: 0.0, legs_km: [], legs_s: [], maneuvers: [], speed_limits: [], signals: [], roads: [] }
|
||||
countries = {}
|
||||
parts.each do |part|
|
||||
props = part[:properties]
|
||||
line = part[:geometry][:coordinates]
|
||||
coords.concat(coords.empty? ? line : line.drop(1))
|
||||
out[:distance_km] += props[:distance_km]
|
||||
out[:time_s] += props[:time_s]
|
||||
%i[legs_km legs_s maneuvers].each { |key| out[key].concat(props[key] || []) }
|
||||
out[:speed_limits].concat((props[:speed_limits] || []).map { |at, limit| [(at + km).round(3), limit] })
|
||||
out[:signals].concat((props[:signals] || []).map { |lon, lat, at| [lon, lat, (at + km).round(3)] })
|
||||
out[:roads].concat((props[:roads] || []).map { |at, *rest| [(at + km).round(3), *rest] })
|
||||
(props[:countries] || []).each do |row|
|
||||
sum = countries[row[:code]] ||= { code: row[:code], km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
|
||||
%i[km motorway_km toll_km].each { |key| sum[key] = (sum[key] + row[key].to_f).round(1) }
|
||||
end
|
||||
km += props[:distance_km]
|
||||
end
|
||||
first = parts.first
|
||||
{ type: "Feature", geometry: { type: "LineString", coordinates: coords },
|
||||
properties: first[:properties].merge(out, distance_km: out[:distance_km].round(3), countries: countries.values) }
|
||||
end
|
||||
|
||||
def self.maneuver(m)
|
||||
{ text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first,
|
||||
exit: m["roundabout_exit_count"], lanes: m["lanes"] }.compact
|
||||
exit: m["roundabout_exit_count"], lanes: m["lanes"],
|
||||
alert: m["verbal_transition_alert_instruction"], say: m["verbal_pre_transition_instruction"] }.compact
|
||||
end
|
||||
private_class_method :maneuver
|
||||
|
||||
@@ -274,12 +341,15 @@ module Maptool
|
||||
# order (vignettes, tolls);
|
||||
# speed_limits: [[km from the start, km/h | "unlimited" | nil], ...], an
|
||||
# entry where the limit changes (nil: not tagged);
|
||||
# signals: [[lon, lat, km from the start], ...], the traffic signals.
|
||||
# signals: [[lon, lat, km from the start], ...], the traffic signals;
|
||||
# roads: [[km from the start, road class, country code], ...], an entry
|
||||
# where either changes (a vehicle's limits by country and road class).
|
||||
# nil if that lookup fails: it's extra.
|
||||
def self.along_route(valhalla_url, legs, costing, options)
|
||||
totals = {}
|
||||
limits = []
|
||||
signals = []
|
||||
roads = []
|
||||
km = 0.0
|
||||
legs.each do |leg|
|
||||
shape = decode_polyline(leg["shape"])
|
||||
@@ -297,13 +367,15 @@ module Maptool
|
||||
row[:toll_km] += edge["length"] if edge["toll"]
|
||||
limit = speed_limit(edge["speed_limit"])
|
||||
limits << [km.round(3), limit] if limits.empty? || limits.last[1] != limit
|
||||
road = [km.round(3), edge["road_class"], code]
|
||||
roads << road if roads.empty? || roads.last.drop(1) != road.drop(1)
|
||||
km += edge["length"]
|
||||
point = shape[edge["end_shape_index"].to_i] if edge.dig("end_node", "traffic_signal")
|
||||
signals << [*point, km.round(3)] if point
|
||||
end
|
||||
end
|
||||
{ countries: totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } },
|
||||
speed_limits: limits, signals: signals }
|
||||
speed_limits: limits, signals: signals, roads: roads }
|
||||
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
|
||||
nil
|
||||
end
|
||||
@@ -316,21 +388,50 @@ module Maptool
|
||||
end
|
||||
|
||||
# The road at the end of a short trace ([[lon, lat], ...] oldest first,
|
||||
# the last few fixes) for driving without a route: its name, class and
|
||||
# speed limit. Map-matched, so the road actually driven, not just the
|
||||
# the last few fixes) for driving without a route: its name, class,
|
||||
# speed limit and surface (Valhalla's: paved_smooth … impassable — the
|
||||
# driving grid's Terrain view switches itself on past "paved_rough"). Map-matched, so the road actually driven, not just the
|
||||
# nearest one (a bridge over the motorway).
|
||||
def self.road(valhalla_url, points)
|
||||
raise RouteError, "at least two points are needed" if points.size < 2
|
||||
|
||||
data = valhalla(valhalla_url, "/trace_attributes",
|
||||
shape: points.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, costing: "auto", shape_match: "map_snap",
|
||||
filters: { attributes: %w[edge.names edge.road_class edge.speed_limit], action: "include" })
|
||||
filters: { attributes: %w[edge.names edge.road_class edge.speed_limit edge.surface node.admin_index admin.country_code],
|
||||
action: "include" })
|
||||
edge = data["edges"]&.last or raise RouteError, "no road here"
|
||||
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]) }
|
||||
country = data["admins"]&.dig(edge.dig("end_node", "admin_index").to_i, "country_code")
|
||||
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"], country: country,
|
||||
signals: signals_ahead(valhalla_url, points) }.compact
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
AHEAD_KM = 1.5
|
||||
|
||||
# The traffic signals on the road ahead with no route: a route from the
|
||||
# last fix, leaving in the direction driven, to AHEAD_KM straight on;
|
||||
# [[lon, lat, km from the fix], ...], nil if that fails (it's extra).
|
||||
# ponytail: "straight on" picks the way at a junction, a signal past a
|
||||
# turn the driver then takes is missed until the next fix's lookup
|
||||
def self.signals_ahead(valhalla_url, points)
|
||||
(lon0, lat0), (lon, lat) = points.last(2).map { |p| p.map { |v| Float(v) } }
|
||||
rad = Math::PI / 180
|
||||
dx = (lon - lon0) * Math.cos(lat * rad)
|
||||
dy = lat - lat0
|
||||
return nil if dx.zero? && dy.zero?
|
||||
|
||||
heading = (Math.atan2(dx, dy) / rad) % 360
|
||||
deg = AHEAD_KM / 111.32
|
||||
to = { lon: lon + deg * Math.sin(heading * rad) / Math.cos(lat * rad), lat: lat + deg * Math.cos(heading * rad) }
|
||||
data = valhalla(valhalla_url, "/route", locations: [{ lon: lon, lat: lat, heading: heading.round, heading_tolerance: 45 }, to],
|
||||
costing: "auto", directions_type: "none")
|
||||
along_route(valhalla_url, data.dig("trip", "legs"), "auto", {})&.dig(:signals)
|
||||
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError, ArgumentError
|
||||
nil
|
||||
end
|
||||
private_class_method :signals_ahead
|
||||
|
||||
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
||||
|
||||
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
||||
@@ -364,6 +465,8 @@ module Maptool
|
||||
avoid = {} unless avoid.is_a?(Hash)
|
||||
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
|
||||
options = options.merge(use_highways: 0.0) if avoid["highways"]
|
||||
options = options.merge(use_ferry: 0.0) if avoid["ferries"]
|
||||
options = options.merge(exclude_unpaved: true) if avoid["unpaved"]
|
||||
[costing, options]
|
||||
end
|
||||
private_class_method :costing
|
||||
|
||||
@@ -60,7 +60,10 @@ module Maptool
|
||||
|
||||
def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "")
|
||||
words = normalize(text).split
|
||||
return [] if words.empty?
|
||||
# No words: only "what's saved near here" (the driving grid's Points) —
|
||||
# every library feature, nearest first; the other sources need a query.
|
||||
sources &= ["layers"] if words.empty?
|
||||
return [] if words.empty? && (center.nil? || sources.empty?)
|
||||
|
||||
ctx = { text: text.to_s.strip, library: library, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s }
|
||||
(sources & SOURCES.keys).flat_map do |source|
|
||||
|
||||
+75
-6
@@ -10,6 +10,56 @@ module Maptool
|
||||
# camera. Kept in data/trip.json across restarts.
|
||||
class TripStore
|
||||
EMPTY = { version: 0, points: [], vehicle: nil, avoid: {}, editing: nil, route: nil, error: nil }.freeze
|
||||
# The itinerary: the trip's name, when it starts (local "YYYY-MM-DDTHH:MM")
|
||||
# and when a day after a night stop starts ("HH:MM"); per point a night
|
||||
# stop (the day ends there), the stay in minutes, a note, its type (an
|
||||
# NPS pictogram's name, public/js/route.js STOP_TYPES) and, on a day's
|
||||
# first point, the day's note; park: where the car stays ({ lngLat:,
|
||||
# name: }, the route goes there, the place is a walk away); on a day's
|
||||
# first point avoid: the day's own (AVOIDS), else the trip's; cost / paid:
|
||||
# € planned there and paid; the trip's own note, budget and fuel price.
|
||||
MAX_STAY_MIN = 7 * 24 * 60
|
||||
AVOIDS = %i[tolls highways ferries unpaved].freeze
|
||||
DATE_TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\z/
|
||||
TIME = /\A\d{2}:\d{2}\z/
|
||||
|
||||
def self.point(p)
|
||||
stay = p[:stay].nil? || p[:stay].to_s.empty? ? nil : Integer(p[:stay], exception: false)
|
||||
raise ArgumentError, "stay must be 0–#{MAX_STAY_MIN} minutes" if stay && !(0..MAX_STAY_MIN).cover?(stay)
|
||||
|
||||
note, day_note = [p[:note], p[:day_note]].map { |n| n.to_s.strip[0, 500] }
|
||||
type = p[:type].to_s
|
||||
raise ArgumentError, "type must be an icon name" unless type.empty? || type.match?(/\A[a-z0-9-]{1,60}\z/)
|
||||
|
||||
cost, paid = [p[:cost], p[:paid]].map { |v| money(v) }
|
||||
avoid = (p[:avoid].to_h.slice(*AVOIDS).to_h { |k, v| [k, !!v] } if p[:avoid].is_a?(Hash))
|
||||
park = ({ lngLat: p[:park].fetch(:lngLat).map { |v| Float(v) }, name: p[:park][:name]&.to_s&.strip&.[](0, 120) }.compact if p[:park].is_a?(Hash))
|
||||
|
||||
{ lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed],
|
||||
night: (true if p[:night]), stay: (stay if stay&.positive?), note: (note unless note.empty?),
|
||||
type: (type unless type.empty?), day_note: (day_note unless day_note.empty?), park: park, avoid: avoid, cost: cost, paid: paid }.compact
|
||||
end
|
||||
|
||||
# € or nil; ArgumentError past MAX_MONEY or below 0.
|
||||
MAX_MONEY = 1_000_000
|
||||
def self.money(value)
|
||||
return nil if value.nil? || value.to_s.strip.empty?
|
||||
|
||||
amount = Float(value, exception: false)
|
||||
raise ArgumentError, "amounts must be 0–#{MAX_MONEY}" unless amount && (0..MAX_MONEY).cover?(amount)
|
||||
|
||||
amount.round(2)
|
||||
end
|
||||
|
||||
def self.itinerary(name:, start:, day_start:, note: nil, budget: nil, fuel_price: nil)
|
||||
name = name.to_s.strip[0, 80]
|
||||
note = note.to_s.strip[0, 2000]
|
||||
raise ArgumentError, "start must be YYYY-MM-DDTHH:MM" unless start.to_s.empty? || start.to_s.match?(DATE_TIME)
|
||||
raise ArgumentError, "day_start must be HH:MM" unless day_start.to_s.empty? || day_start.to_s.match?(TIME)
|
||||
|
||||
{ name: (name unless name.empty?), start: (start unless start.to_s.empty?), day_start: (day_start unless day_start.to_s.empty?),
|
||||
note: (note unless note.empty?), budget: money(budget), fuel_price: money(fuel_price) }.compact
|
||||
end
|
||||
|
||||
def initialize(path)
|
||||
@path = path
|
||||
@@ -111,31 +161,50 @@ module Maptool
|
||||
[here, GnssSim.bearing(GnssSim.point_at(coords, km, [to - 0.02, 0].max), GnssSim.point_at(coords, km, [to + 0.02, km.last].min)).round(1)]
|
||||
end
|
||||
|
||||
# The points to route, in pieces of the same avoids: [[locations,
|
||||
# avoid], ...] — one piece unless a day has avoids of its own (on its
|
||||
# first point in the list, the one after the night spot). A leg takes
|
||||
# the avoids of the day it's driven in.
|
||||
def self.pieces(points, avoid)
|
||||
day = points.first&.dig(:avoid) || avoid
|
||||
legs = points.each_with_index.filter_map do |p, i|
|
||||
day = points[i + 1]&.dig(:avoid) || avoid if p[:night] # the next day leaves from the night spot
|
||||
[p.dig(:park, :lngLat) || p[:lngLat], day] unless p[:passed]
|
||||
end
|
||||
legs.each_cons(2).chunk_while { |x, y| x[0][1] == y[0][1] }.map do |run|
|
||||
[[run.first[0][0], *run.map { |_, to| to[0] }], run.first[0][1]]
|
||||
end
|
||||
end
|
||||
|
||||
# points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through
|
||||
# the ones not passed with the block (locations, vehicle id, avoid → the
|
||||
# /api/route Feature, may raise Routing errors) unless only names/nav
|
||||
# changed — the old route stays then. Passed points stay in the trip
|
||||
# (shown dimmed, still editable: a stop missed out added afterwards),
|
||||
# just not routed. Last write wins.
|
||||
def update(points:, vehicle:, avoid:, editing:)
|
||||
points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed] } }
|
||||
def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil, note: nil, budget: nil, fuel_price: nil)
|
||||
points = points.map { |p| self.class.point(p) }
|
||||
itinerary = self.class.itinerary(name: name, start: start, day_start: day_start, note: note, budget: budget, fuel_price: fuel_price)
|
||||
avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] }
|
||||
before = get
|
||||
routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p[:lngLat] } }
|
||||
same_route = routed.(before[:points]) == routed.(points) &&
|
||||
routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p.dig(:park, :lngLat) || p[:lngLat] } }
|
||||
same_route = self.class.pieces(before[:points], before[:avoid]) == self.class.pieces(points, avoid) &&
|
||||
before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error]
|
||||
route, error = if same_route then [before[:route], nil]
|
||||
elsif routed.(points).size < 2 then [nil, nil]
|
||||
else
|
||||
begin
|
||||
[yield(routed.(points), vehicle, avoid), nil]
|
||||
pieces = self.class.pieces(points, avoid)
|
||||
[Routing.merge(pieces.map { |locations, day_avoid| yield(locations, vehicle, day_avoid) }), nil]
|
||||
rescue Routing::RouteError, Routing::Unavailable => e
|
||||
[nil, e.message]
|
||||
end
|
||||
end
|
||||
@mutex.synchronize do
|
||||
@trip = { version: @trip[:version] + 1, points: points, vehicle: vehicle, avoid: avoid, editing: editing,
|
||||
route: route, error: error, updated_at: Time.now.to_f }
|
||||
**itinerary, route: route, error: error, updated_at: Time.now.to_f }.compact
|
||||
@trip[:route] = route # nil kept: the client reads it
|
||||
@trip[:error] = error
|
||||
File.write("#{@path}.tmp", JSON.generate(@trip))
|
||||
File.rename("#{@path}.tmp", @path)
|
||||
@trip.dup
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
require "time"
|
||||
require_relative "track_stats"
|
||||
require_relative "gpx"
|
||||
|
||||
module Maptool
|
||||
# The days of a recorded trip (the Design canvas' GridRecording): the log
|
||||
# stays one continuous journal (lib/maptool/trip_log.rb), the days are only
|
||||
# cuts in it — where the car stood ≥ STOOD_S, else at NIGHT_HOUR local time
|
||||
# (a drive through the night with no long stop), plus the cuts made by
|
||||
# hand, minus the ones joined. A cut is the index of a day's first point.
|
||||
# points: [[lon, lat, alt, t], ...] (t: epoch s), as the journal has them.
|
||||
module TripDays
|
||||
STOOD_S = 4 * 3600
|
||||
NIGHT_HOUR = 3
|
||||
PAUSE_S = 300 # this long between two fixes: standing (a fix comes every 10 m moved)
|
||||
|
||||
# [[index, "auto" | "night" | "hand"], ...], sorted. hand / joined: epoch
|
||||
# s — a hand cut starts the day at the first point from then on; a join
|
||||
# names the cut by its day's first point's time.
|
||||
# ponytail: NIGHT_HOUR in the server's time zone, the client's if they differ
|
||||
def self.cuts(points, hand: [], joined: [])
|
||||
t = points.map { |p| p[3] }
|
||||
auto = (1...points.size).select { |i| t[i] - t[i - 1] >= STOOD_S }
|
||||
night = (1...points.size).select do |i|
|
||||
crossed = Time.at(t[i]).then { |b| Time.new(b.year, b.month, b.day, NIGHT_HOUR) }
|
||||
crossed = crossed - 86_400 if crossed.to_f > t[i]
|
||||
crossed.to_f > t[i - 1] && auto.none? { |j| (t[j] - t[i]).abs < 12 * 3600 }
|
||||
end
|
||||
by_hand = hand.filter_map { |h| t.index { |x| x >= h } }.select { |i| i.positive? }
|
||||
all = auto.map { |i| [i, "auto"] } + night.map { |i| [i, "night"] } + by_hand.map { |i| [i, "hand"] }
|
||||
all.reject { |i, _| joined.any? { |j| (t[i] - j).abs < 0.05 } }.uniq(&:first).sort_by(&:first)
|
||||
end
|
||||
|
||||
# The days: { index:, from:, to: (exclusive), started_at:, ended_at:,
|
||||
# distance_m:, driving_s:, ascent_m:, max_alt_m:, cut: (what ends it:
|
||||
# { kind:, stood_s:, at: [lon, lat], next: its time }) }.
|
||||
def self.days(points, cuts)
|
||||
bounds = [0, *cuts.map(&:first), points.size]
|
||||
bounds.each_cons(2).each_with_index.map do |(from, to), n|
|
||||
piece = points[from...to]
|
||||
day = { index: n + 1, from: from, to: to, started_at: piece.first[3], ended_at: piece.last[3] }.merge(stats(piece))
|
||||
if to < points.size
|
||||
day[:cut] = { kind: cuts[n][1], stood_s: (points[to][3] - piece.last[3]).round, at: piece.last.first(2), next: points[to][3] }
|
||||
end
|
||||
day
|
||||
end
|
||||
end
|
||||
|
||||
def self.stats(piece)
|
||||
coords = piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
|
||||
gaps = piece.each_cons(2).map { |a, b| b[3] - a[3] }
|
||||
{
|
||||
distance_m: TrackStats.compute(coords)["distance_meters"],
|
||||
driving_s: gaps.select { |g| g < PAUSE_S }.sum.round,
|
||||
standing_s: gaps.select { |g| g >= PAUSE_S }.sum.round,
|
||||
stops: gaps.count { |g| g >= PAUSE_S },
|
||||
ascent_m: TrackStats.compute(coords)["elevation_gain_meters"],
|
||||
max_alt_m: piece.filter_map { |p| p[2] }.max,
|
||||
}
|
||||
end
|
||||
|
||||
# [west, south, east, north] of a piece.
|
||||
def self.bbox(piece)
|
||||
lons, lats = piece.map(&:first), piece.map { |p| p[1] }
|
||||
[lons.min, lats.min, lons.max, lats.max]
|
||||
end
|
||||
|
||||
# A GPX of tracks — pieces: [[name, points], ...] — with each point's
|
||||
# time; extras: Features to add (the planned route, stops, pauses).
|
||||
def self.gpx(pieces, extras = [])
|
||||
tracks = pieces.map do |name, piece|
|
||||
{ "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } },
|
||||
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving",
|
||||
"times" => piece.map { |p| Time.at(p[3]).utc.iso8601 } } }
|
||||
end
|
||||
Gpx.from_features(extras + tracks)
|
||||
end
|
||||
|
||||
# The stands (≥ PAUSE_S) in a piece as waypoints.
|
||||
def self.pauses(piece)
|
||||
piece.each_cons(2).filter_map do |a, b|
|
||||
next if b[3] - a[3] < PAUSE_S
|
||||
|
||||
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => a.first(2) },
|
||||
"properties" => { "name" => "Stood #{duration(b[3] - a[3])}", "time" => Time.at(a[3]).utc.iso8601 } }
|
||||
end
|
||||
end
|
||||
|
||||
def self.duration(seconds)
|
||||
h, m = (seconds / 60).round.divmod(60)
|
||||
h.positive? ? format("%d h %02d", h, m) : "#{m} min"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -117,6 +117,47 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
# The running trip's journal, else the newest (the trip just ended), read
|
||||
# whole: { folder:, started_at:, points:, hand:, joined:, active: } — or nil.
|
||||
def recording
|
||||
path = @mutex.synchronize do
|
||||
@file&.flush
|
||||
@trip ? @trip[:path] : Dir[File.join(@dir, "*.ndjson")].max_by { |p| File.basename(p, ".ndjson").to_i }
|
||||
end
|
||||
return nil unless path
|
||||
|
||||
out = { points: [], hand: [], joined: [], active: false, path: path }
|
||||
File.foreach(path) do |line|
|
||||
entry = JSON.parse(line) rescue next
|
||||
case entry
|
||||
when Array then out[:points] << entry
|
||||
when Hash
|
||||
out[:folder] ||= entry["trip"]
|
||||
out[:started_at] ||= entry["started_at"]
|
||||
out[:hand] << entry["cut"] if entry["cut"]
|
||||
out[:joined] << entry["join"] if entry["join"]
|
||||
end
|
||||
end
|
||||
out[:active] = @mutex.synchronize { @trip&.dig(:path) == path }
|
||||
out
|
||||
end
|
||||
|
||||
# A day cut by hand at `at` (epoch s), or a cut joined (`at`: its day's
|
||||
# first point's time): a line in the journal, the trip itself untouched.
|
||||
def mark(kind, at)
|
||||
raise ArgumentError, "cut or join" unless %i[cut join].include?(kind)
|
||||
|
||||
path = recording&.dig(:path) or raise ArgumentError, "no trip recorded"
|
||||
@mutex.synchronize do
|
||||
if @trip && @trip[:path] == path
|
||||
journal(kind => at.to_f)
|
||||
sync
|
||||
else
|
||||
File.open(path, "a") { |f| f.puts(JSON.generate(kind => at.to_f)) }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# The newest journal with no end: the trip still running.
|
||||
|
||||
Generated
+13
-13
@@ -9,7 +9,7 @@
|
||||
"@mdi/js": "7.4.47",
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.2.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"maplibre-gl": "6.21.0",
|
||||
"maplibre-gl-lanes": "1.7.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
@@ -69,9 +69,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/maplibre-gl-style-spec": {
|
||||
"version": "26.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.11.0.tgz",
|
||||
"integrity": "sha512-MQMBqOkmVm7fLLun2l/bwOv9bURkvyEVISo/OYleb9/nsnfjQ6gs29isysARt5FK/k9RFM4SmH4eMTUQGlv0Pw==",
|
||||
"version": "27.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-27.1.0.tgz",
|
||||
"integrity": "sha512-8EkIhwOdhjhX6HdugboL0JEGQejqln7Xuve7X2sFFU35IUaCgucHRuuO0+0yWSzYEmEa/z4knkpwOYZdrF/wFA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
@@ -89,9 +89,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/mlt": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.3.0.tgz",
|
||||
"integrity": "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==",
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.4.0.tgz",
|
||||
"integrity": "sha512-kDjapA8mGAkSAAZr+ZF875w38PdJg7xS79oEADD7S/QdXELmd4hNHgZR/o5WRkWLBgWjKHJdHj/yRyYmU9Inbg==",
|
||||
"dev": true,
|
||||
"license": "(MIT OR Apache-2.0)",
|
||||
"dependencies": {
|
||||
@@ -184,9 +184,9 @@
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/maplibre-gl": {
|
||||
"version": "6.20.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.20.0.tgz",
|
||||
"integrity": "sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==",
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.21.0.tgz",
|
||||
"integrity": "sha512-mjMFzw99R1kvuWo3xj6XKcFFbVpwTPhO7g2TeyJyT5DdM1E6zKIC/uWG17WpXO6dnRFZ/3un9k44+KtDNjD2Hw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
@@ -195,8 +195,8 @@
|
||||
"@mapbox/unitbezier": "^1.0.0",
|
||||
"@mapbox/vector-tile": "^3.0.0",
|
||||
"@maplibre/geojson-vt": "^7.0.1",
|
||||
"@maplibre/maplibre-gl-style-spec": "^26.11.0",
|
||||
"@maplibre/mlt": "^1.3.0",
|
||||
"@maplibre/maplibre-gl-style-spec": "^27.0.0",
|
||||
"@maplibre/mlt": "^1.4.0",
|
||||
"@maplibre/vt-pbf": "^4.3.3",
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"bidi-js": "^1.1.0",
|
||||
@@ -204,7 +204,7 @@
|
||||
"gl-matrix": "^3.4.4",
|
||||
"kdbush": "^4.1.0",
|
||||
"murmurhash-js": "^1.0.0",
|
||||
"pbf": "^5.2.0",
|
||||
"pbf": "^5.2.1",
|
||||
"potpack": "^2.1.0",
|
||||
"quickselect": "^3.0.0",
|
||||
"tinyqueue": "^3.0.0",
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"@mdi/js": "7.4.47",
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.2.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"maplibre-gl": "6.21.0",
|
||||
"maplibre-gl-lanes": "1.7.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"label": "Camper POIs (Overpass)",
|
||||
"command": "./run.rb"
|
||||
"command": "./run.rb",
|
||||
"route": true
|
||||
}
|
||||
@@ -7,10 +7,19 @@
|
||||
# did all the real work for the "rake overpass:pois" dev-time task this
|
||||
# plugin now sits alongside as a second way to run the same query.
|
||||
|
||||
# Along the trip's route (--route=<GeoJSON LineString file> --corridor-km):
|
||||
# Overpass' around: with the route thinned to a vertex every half corridor.
|
||||
|
||||
require_relative "../../lib/maptool/overpass_pois"
|
||||
require_relative "../../lib/maptool/corridor"
|
||||
|
||||
args = ARGV.to_h { |arg| arg.sub(/\A--/, "").split("=", 2) }
|
||||
bbox = %w[south west north east].map { |key| Float(args.fetch(key)) }
|
||||
around = if args["route"]
|
||||
corridor = Float(args.fetch("corridor-km"))
|
||||
line = Maptool::Corridor.thin(JSON.parse(File.read(args["route"]))["coordinates"], [corridor / 2, 0.5].max)
|
||||
[corridor * 1000, line]
|
||||
end
|
||||
|
||||
response = Maptool::OverpassPois.fetch(bbox)
|
||||
response = Maptool::OverpassPois.fetch(bbox, timeout: around ? 180 : 60, around: around)
|
||||
puts JSON.generate(Maptool::OverpassPois.to_geojson(response))
|
||||
+1504
-232
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "Road",
|
||||
"screen": "16 × 10 cells (the navigator's 16″, 1280 × 800)",
|
||||
"columns": 16,
|
||||
"rows": 10,
|
||||
"cell": 80,
|
||||
"map": "2 / 1 / 10 / 14",
|
||||
"menu": { "area": "2 / 10 / 10 / 17", "map": "2 / 1 / 10 / 10" },
|
||||
"cells": [
|
||||
{ "area": "1 / 1 / 2 / 5", "widget": "maneuver" },
|
||||
{ "area": "1 / 5 / 2 / 9", "widget": "field", "value": "speed" },
|
||||
{ "area": "1 / 9 / 2 / 11", "widget": "field", "value": "altitude" },
|
||||
{ "area": "1 / 11 / 2 / 13", "widget": "field", "value": "time" },
|
||||
{ "area": "1 / 13 / 2 / 15", "widget": "field", "value": "sun" },
|
||||
{ "area": "1 / 15 / 2 / 17", "widget": "status" },
|
||||
{ "area": "2 / 1 / 3 / 5", "widget": "ahead" },
|
||||
{ "area": "2 / 1 / 5 / 6", "widget": "border" },
|
||||
{ "area": "2 / 14 / 3 / 17", "widget": "field", "value": "nextStop", "small": true },
|
||||
{ "area": "3 / 14 / 4 / 17", "widget": "field", "value": "toNextStop" },
|
||||
{ "area": "4 / 14 / 5 / 17", "widget": "field", "value": "etaNextStop" },
|
||||
{ "area": "5 / 14 / 6 / 17", "widget": "field", "value": "toEnd" },
|
||||
{ "area": "6 / 14 / 9 / 17", "widget": "elevation", "km": 10 },
|
||||
{ "area": "9 / 14 / 10 / 17", "widget": "compass" },
|
||||
{ "area": "10 / 1 / 11 / 3", "widget": "key", "action": "trip", "key": "F1" },
|
||||
{ "area": "10 / 3 / 11 / 5", "widget": "key", "action": "points", "key": "F2" },
|
||||
{ "area": "10 / 5 / 11 / 7", "widget": "key", "action": "layers", "key": "F3" },
|
||||
{ "area": "10 / 7 / 11 / 9", "widget": "key", "action": "search", "key": "/" },
|
||||
{ "area": "10 / 9 / 11 / 11", "widget": "key", "action": "menu", "key": "F5" },
|
||||
{ "area": "10 / 11 / 11 / 12", "widget": "key", "action": "zoomOut", "key": "-" },
|
||||
{ "area": "10 / 12 / 11 / 13", "widget": "key", "action": "zoomIn", "key": "+" },
|
||||
{ "area": "10 / 13 / 11 / 14", "widget": "key", "action": "pitch", "key": "3" },
|
||||
{ "area": "10 / 14 / 11 / 15", "widget": "key", "action": "follow", "key": "f" },
|
||||
{ "area": "10 / 15 / 11 / 16", "widget": "key", "action": "terrain", "key": "t" },
|
||||
{ "area": "10 / 16 / 11 / 17", "widget": "key", "action": "palette", "key": "n" }
|
||||
],
|
||||
"bindings": [
|
||||
{ "input": "pad.K1", "action": "trip", "led": "cyan" },
|
||||
{ "input": "pad.K2", "action": "points", "led": "cyan" },
|
||||
{ "input": "pad.K3", "action": "layers", "led": "cyan" },
|
||||
{ "input": "pad.K4", "action": "search", "led": "cyan" },
|
||||
{ "input": "pad.K5", "action": "menu", "menu": "close", "led": "cyan" },
|
||||
{ "input": "pad.K6", "action": "pitch", "led": "white" },
|
||||
{ "input": "pad.K7", "action": "terrain", "led": "yellow" },
|
||||
{ "input": "pad.K8", "action": "palette", "led": "yellow" },
|
||||
{ "input": "pad.E1", "action": "panX", "menu": "rows" },
|
||||
{ "input": "pad.E1 press", "menu": "enter" },
|
||||
{ "input": "pad.E2", "action": "panY" },
|
||||
{ "input": "pad.E2 press", "output": "relays.1" },
|
||||
{ "input": "pad.E3", "action": "zoom" },
|
||||
{ "input": "pad.E3 press", "action": "follow" }
|
||||
]
|
||||
}
|
||||
+128
-26
@@ -1,5 +1,6 @@
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { onRouteChanged, requestReroute, notifyRouteProgress } from "/js/panels.js";
|
||||
import { onRouteChanged, requestReroute, notifyRouteProgress, currentVehicle } from "/js/panels.js";
|
||||
import { effectiveLimit } from "/js/speed_limits.js";
|
||||
import { elevationAt } from "/js/dem.js";
|
||||
|
||||
// The car's dashboard over the map, off the CAN signals (GET /api/can,
|
||||
@@ -36,9 +37,22 @@ 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 LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close (or LANES_AHEAD_S at the speed driven)
|
||||
const LANES_AHEAD_S = 45;
|
||||
const ARRIVE_M = 30; // this close to the end: arrived (navigation goes on: past it, the route turns back)
|
||||
const ARRIVE_TYPES = [4, 5, 6]; // Valhalla's destination maneuvers
|
||||
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true };
|
||||
// Step advance after Ferrostar's DistanceEntryExit: a maneuver stays the next one
|
||||
// until the position is this far past it (not before reaching it: at the turn the
|
||||
// turn is still shown, "now"), then the one after it
|
||||
const STEP_EXIT_M = 5;
|
||||
const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely
|
||||
// Voice prompts (speechSynthesis, Valhalla's verbal instructions), on/off in
|
||||
// drive mode's Menu: "In 400 m, turn right…" from SOON_S ahead, the
|
||||
// instruction itself NOW_S before the maneuver (at least the metres given).
|
||||
export const VOICE_KEY = "maptool.voice";
|
||||
const SOON_S = 25, SOON_M = 400;
|
||||
const NOW_S = 7, NOW_M = 60;
|
||||
const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through
|
||||
|
||||
const load = () => {
|
||||
@@ -49,7 +63,7 @@ const load = () => {
|
||||
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`);
|
||||
export const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
|
||||
const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
|
||||
// An arrow from the bottom center turning by `angle` (° from straight on),
|
||||
@@ -66,7 +80,7 @@ const uturnPath = (cls) => `<path class="${cls}" d="M14 30 V14 A5 5 0 0 0 4 14 V
|
||||
// "uturn", "arrive", "roundabout" drawn their own way.
|
||||
const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45,
|
||||
20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 };
|
||||
function maneuverSvg(type) {
|
||||
export function maneuverSvg(type) {
|
||||
let body;
|
||||
if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow");
|
||||
else if (type >= 4 && type <= 6) body = `<path class="dash-banner__arrow" d="M8 30 V4 M8 5 H19 L16 9 L19 13 H8"/>`; // a flag: arriving
|
||||
@@ -80,7 +94,7 @@ const LANE_ANGLES = { 2: 0, 16: -45, 8: -90, 4: -135, 32: 45, 64: 90, 128: 135,
|
||||
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 }) {
|
||||
export function laneSvg({ directions, active = 0 }) {
|
||||
const arrow = (bit) => {
|
||||
const cls = `dash-lane__arrow${active & bit ? " dash-lane__take" : ""}`;
|
||||
return bit === LANE_REVERSE ? uturnPath(cls) : arrowPath(LANE_ANGLES[bit], cls);
|
||||
@@ -99,7 +113,7 @@ function prepareRoute(route) {
|
||||
const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; });
|
||||
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 };
|
||||
return { coords, km, limits: route.properties.speed_limits, roads: route.properties.roads || [], signals: route.properties.signals || [], maneuvers, viaKm };
|
||||
}
|
||||
|
||||
// Nearest point on the route: [km along it, meters off it]. Near the last
|
||||
@@ -163,8 +177,19 @@ const INCLINOMETER = `
|
||||
<text x="35" y="60" class="dash-caption">pitch</text>
|
||||
</svg>`;
|
||||
|
||||
// The driving grid (driving.js) reads the dashboard: watchDashboard(cb)
|
||||
// polls the bus while it's on, the overlay's card or not, and hands each
|
||||
// poll's state to cb; watchDashboard(null) stops that.
|
||||
let instance = null;
|
||||
export function watchDashboard(callback) {
|
||||
if (!instance || !isLoggedIn()) return; // /api/can wants a login
|
||||
instance._watch = callback;
|
||||
if (callback && !instance._timer) instance._poll();
|
||||
}
|
||||
|
||||
export class DashboardControl {
|
||||
constructor(map) {
|
||||
instance = this;
|
||||
this._map = map;
|
||||
this._settings = load();
|
||||
this._timer = null;
|
||||
@@ -176,7 +201,9 @@ export class DashboardControl {
|
||||
this._lastAt = 0;
|
||||
this._offFixes = 0;
|
||||
this._sentKm = undefined; // the new route drawn by the next fix
|
||||
this._said = new Set();
|
||||
}));
|
||||
this._said = new Set(); // voice prompts given: "maneuver index:soon|now"
|
||||
this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road
|
||||
this._road = null; // its last answer
|
||||
this._roadAt = 0;
|
||||
@@ -202,7 +229,7 @@ export class DashboardControl {
|
||||
if (this._values.alt == null) {
|
||||
this._values.alt = await elevationAt(lon, lat, offline, { zoom: TILT_ZOOM, smooth: true });
|
||||
}
|
||||
if (this._course == null || this._values.pitch != null || this._values.roll != null) return;
|
||||
if (this._course == null) return;
|
||||
const [front, back, right, left] = await Promise.all([0, 180, 90, 270].map((b) => at(this._course + b)));
|
||||
if ([front, back, right, left].includes(null)) return;
|
||||
const deg = (rise) => Math.atan(rise / (2 * TILT_HALF_M)) / rad;
|
||||
@@ -217,6 +244,36 @@ export class DashboardControl {
|
||||
notifyRouteProgress(km);
|
||||
}
|
||||
|
||||
// With no route: the nearest of /api/road's signals ahead that's still in
|
||||
// front (within 90° of the heading), straight-line metres.
|
||||
_signalAhead(position) {
|
||||
const heading = this._heading()?.deg;
|
||||
if (heading == null || !this._road?.signals?.length) return null;
|
||||
const ahead = this._road.signals
|
||||
.map(([lon, lat]) => {
|
||||
const dx = (lon - position[0]) * Math.cos(position[1] * RAD), dy = lat - position[1];
|
||||
const off = Math.abs((((Math.atan2(dx, dy) / RAD - heading) % 360) + 540) % 360 - 180);
|
||||
return off < 90 ? meters(position, [lon, lat]) : null;
|
||||
})
|
||||
.filter((m) => m != null);
|
||||
return ahead.length ? Math.min(...ahead) : null;
|
||||
}
|
||||
|
||||
_speak(index, maneuver, m, speed) {
|
||||
let voiceOn = false;
|
||||
try { voiceOn = localStorage.getItem(VOICE_KEY) === "on"; } catch { /* private window */ }
|
||||
if (!voiceOn || !window.speechSynthesis) return;
|
||||
const now = Math.max(NOW_M, speed * NOW_S);
|
||||
let stage = null, text = null;
|
||||
if (m <= now) [stage, text] = ["now", maneuver.say];
|
||||
else if (m <= Math.max(SOON_M, speed * SOON_S) && m > 2 * now && maneuver.alert) {
|
||||
[stage, text] = ["soon", `In ${distance(m).replace(" m", " meters").replace(" km", " kilometers")}, ${maneuver.alert[0].toLowerCase()}${maneuver.alert.slice(1)}`];
|
||||
}
|
||||
if (!text || this._said.has(`${index}:${stage}`)) return;
|
||||
this._said.add(`${index}:soon`).add(`${index}:${stage}`);
|
||||
speechSynthesis.speak(new SpeechSynthesisUtterance(text));
|
||||
}
|
||||
|
||||
// The limit and what's ahead: from the route while on it, else the road.
|
||||
_navigate() {
|
||||
const { lat, lon, speed } = this._values;
|
||||
@@ -230,11 +287,18 @@ export class DashboardControl {
|
||||
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 { limits, roads, signals, maneuvers } = this._route;
|
||||
// the road's sign capped by the profile's own limit for that country and road class
|
||||
const limitAt = (k) => {
|
||||
const road = roads.findLast(([km]) => km <= k);
|
||||
const sign = limits.findLast(([km]) => km <= k)?.[1] ?? null;
|
||||
return road ? effectiveLimit(sign, road[2], road[1], currentVehicle) : sign;
|
||||
};
|
||||
const limit = limitAt(at);
|
||||
const nextKm = [...limits, ...roads].map(([km]) => km).filter((km) => km > at).sort((a, b) => a - b).find((km) => limitAt(km) !== limit);
|
||||
const next = nextKm != null ? [nextKm, limitAt(nextKm)] : null;
|
||||
const signal = signals.find(([, , km]) => km > at);
|
||||
const index = maneuvers.findIndex((m) => m.at > at + 0.005);
|
||||
const index = maneuvers.findIndex((m) => m.at > at - STEP_EXIT_M / 1000);
|
||||
const maneuver = maneuvers[index];
|
||||
const then = maneuvers[index + 1];
|
||||
const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's
|
||||
@@ -243,17 +307,23 @@ export class DashboardControl {
|
||||
this._progress(at);
|
||||
}
|
||||
this._nav = {
|
||||
limit: current?.[1] ?? null,
|
||||
limit,
|
||||
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
|
||||
country: roads.findLast(([km]) => km <= at)?.[2] ?? null,
|
||||
signal: signal && (signal[2] - at) * 1000,
|
||||
maneuver: maneuver && { ...maneuver, m: (maneuver.at - at) * 1000 },
|
||||
maneuver: maneuver && { ...maneuver, m: Math.max(0, (maneuver.at - at) * 1000) },
|
||||
then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null,
|
||||
street: onStreet,
|
||||
arrived: ARRIVE_TYPES.includes(maneuvers.at(-1)?.type) && (!maneuver || (index === maneuvers.length - 1 && (maneuver.at - at) * 1000 <= ARRIVE_M)),
|
||||
lanesM: Math.max(LANES_AHEAD_M, (speed ?? 0) * LANES_AHEAD_S),
|
||||
};
|
||||
if (maneuver && off <= ON_ROUTE_M) this._speak(index, maneuver, (maneuver.at - at) * 1000, speed ?? 0);
|
||||
return;
|
||||
}
|
||||
this._progress(null);
|
||||
this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name };
|
||||
const road = this._road;
|
||||
this._nav = { limit: road ? effectiveLimit(road.speed_limit ?? null, road.country, road.road_class, currentVehicle) : null,
|
||||
offRoute: !!this._route, street: road?.name, signal: this._signalAhead(position), country: road?.country ?? null };
|
||||
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);
|
||||
@@ -348,13 +418,15 @@ export class DashboardControl {
|
||||
this._map.getContainer().appendChild(this._banner);
|
||||
this._status.hidden = false;
|
||||
this._status.textContent = "Connecting…";
|
||||
this._poll();
|
||||
if (!this._timer) this._poll();
|
||||
}
|
||||
|
||||
_disable() {
|
||||
if (!this._watch) {
|
||||
this._progress(null);
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
this._card?.remove();
|
||||
this._card = null;
|
||||
this._banner?.remove();
|
||||
@@ -363,6 +435,8 @@ export class DashboardControl {
|
||||
}
|
||||
|
||||
async _poll() {
|
||||
if (this._busy) return; // the grid and the card both asked
|
||||
this._busy = true;
|
||||
try {
|
||||
const response = await fetch("/api/can", { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
@@ -375,7 +449,12 @@ export class DashboardControl {
|
||||
}));
|
||||
this._updateCourse(this._values);
|
||||
this._simRunning = !!data.simulated; // /sim.html runs it
|
||||
if (this._simRunning) await this._simulateTerrain();
|
||||
this._actions = data.actions || []; // can.json's SDO actions (levelling), POST /api/can/actions/<n>
|
||||
if (this._simRunning) {
|
||||
// simulated driving: the tilt of the terrain under it, not the IMU of the car standing at home
|
||||
this._values.pitch = this._values.roll = null;
|
||||
await this._simulateTerrain();
|
||||
}
|
||||
this._navigate();
|
||||
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
|
||||
this._status.hidden = !this._status.textContent;
|
||||
@@ -385,7 +464,27 @@ export class DashboardControl {
|
||||
this._status.textContent = `Can't reach the server: ${e.message}`;
|
||||
}
|
||||
this._render();
|
||||
if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS);
|
||||
this._busy = false;
|
||||
this._watch?.(this.state());
|
||||
this._timer = this._card || this._watch ? setTimeout(() => this._poll(), POLL_MS) : null;
|
||||
}
|
||||
|
||||
// What the driving grid shows: the signals, the navigation, the heading
|
||||
// ({ deg, live }), the road's surface (off a route, /api/road), the CAN
|
||||
// actions, and the km along the route (null off it).
|
||||
state() {
|
||||
const onRoute = this._route && this._offFixes < OFF_ROUTE_FIXES;
|
||||
// the road's surface only off the route: back on it the last road's would stay (the terrain view never closed)
|
||||
return { values: this._values, nav: this._nav, heading: this._heading(), simulated: !!this._simRunning, actions: this._actions || [],
|
||||
surface: onRoute ? null : this._road?.surface ?? null, course: this._course, atKm: onRoute ? this._lastAt : null };
|
||||
}
|
||||
|
||||
// Driving, the GNSS course; standing, the compass — else the last of either, not live.
|
||||
_heading() {
|
||||
const v = this._values;
|
||||
const moving = v.speed != null && v.speed >= MOVING_MS;
|
||||
const deg = moving ? this._course ?? v.heading : v.heading ?? this._course;
|
||||
return deg == null ? null : { deg: (deg + 360) % 360, live: moving ? this._course != null : v.heading != null };
|
||||
}
|
||||
|
||||
_render() {
|
||||
@@ -414,12 +513,10 @@ export class DashboardControl {
|
||||
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
|
||||
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
|
||||
}
|
||||
const moving = v.speed != null && v.speed >= MOVING_MS;
|
||||
const heading = moving ? this._course ?? v.heading : v.heading ?? this._course;
|
||||
const live = heading != null && (moving ? this._course != null : v.heading != null);
|
||||
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`);
|
||||
svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55;
|
||||
svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`;
|
||||
const heading = this._heading();
|
||||
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading ? -heading.deg : 0})`);
|
||||
svg.querySelector(".dash-ring").style.opacity = !heading ? 0.3 : heading.live ? 1 : 0.55;
|
||||
svg.querySelector(".dash-heading").textContent = heading ? `${Math.round(heading.deg)}°` : "";
|
||||
speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6);
|
||||
}
|
||||
|
||||
@@ -440,7 +537,7 @@ export class DashboardControl {
|
||||
if (n?.maneuver && !this._settings.widgets.banner) {
|
||||
const { text, m, lanes } = n.maneuver;
|
||||
rows.push(`<div class="dash-maneuver">${distance(m)} · ${esc(text)}</div>`);
|
||||
if (lanes && m <= LANES_AHEAD_M) {
|
||||
if (lanes && m <= (n.lanesM ?? LANES_AHEAD_M)) {
|
||||
rows.push(`<div class="dash-lanes">${lanes.map(laneSvg).join("")}</div>`);
|
||||
}
|
||||
}
|
||||
@@ -452,14 +549,19 @@ export class DashboardControl {
|
||||
// closely, its lanes from LANES_AHEAD_M, and the street being driven.
|
||||
_renderBanner() {
|
||||
const n = this._nav;
|
||||
const show = this._settings.widgets.banner && !!n?.maneuver;
|
||||
const show = this._settings.widgets.banner && !!(n?.maneuver || n?.arrived);
|
||||
this._banner.hidden = !show;
|
||||
if (!show) return;
|
||||
this._banner.style.setProperty("--dash-alpha", Math.max(0.8, this._settings.opacity ?? DEFAULT_OPACITY));
|
||||
if (n.arrived) {
|
||||
this._banner.innerHTML = `<div class="dash-banner__main">${maneuverSvg(4)}<div><div class="dash-banner__distance">Arrived</div>` +
|
||||
`<div class="dash-banner__street">${esc(n.street || "")}</div></div></div>`;
|
||||
return;
|
||||
}
|
||||
const { m, type, street, text, exit, lanes } = n.maneuver;
|
||||
const what = street ? `${exit ? `${exit}. exit · ` : ""}${esc(street)}` : esc(text);
|
||||
const then = n.then ? `<div class="dash-banner__then">then ${maneuverSvg(n.then.type)} ${esc(n.then.street || n.then.text)}</div>` : "";
|
||||
const lanesRow = lanes && m <= LANES_AHEAD_M ? `<div class="dash-lanes dash-banner__lanes">${lanes.map(laneSvg).join("")}</div>` : "";
|
||||
const lanesRow = lanes && m <= (n.lanesM ?? LANES_AHEAD_M) ? `<div class="dash-lanes dash-banner__lanes">${lanes.map(laneSvg).join("")}</div>` : "";
|
||||
const onStreet = n.street ? `<div class="dash-banner__on">on ${esc(n.street)}</div>` : "";
|
||||
this._banner.innerHTML = `<div class="dash-banner__main">${maneuverSvg(type)}<div><div class="dash-banner__distance">${distance(m)}</div>` +
|
||||
`<div class="dash-banner__street">${what}</div></div></div>${lanesRow}${then}${onStreet}`;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+689
-121
@@ -1,97 +1,193 @@
|
||||
import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { LngLatBounds, Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { requestGnssFollow, onRouteChanged } from "/js/panels.js";
|
||||
import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js";
|
||||
import { formatDuration } from "/js/route.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { watchDashboard, maneuverSvg, laneSvg, distance, VOICE_KEY } from "/js/dashboard.js";
|
||||
import { SPEED_LIMITS, COUNTRY_NAMES, isHeavy, motorwayPayment } from "/js/speed_limits.js";
|
||||
import { currentVehicle, onVehicle } from "/js/panels.js";
|
||||
import { formatSunInfo } from "/js/sun.js";
|
||||
import { pointsMenu, layersMenu, terrainMenu, levelMenu, recordingMenu, todayMenu, switchesMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
|
||||
|
||||
// Driving mode: the few things needed on the road as big buttons, the
|
||||
// planning sidebar and panels out of the way. After the research in
|
||||
// docs/design.adoc ("Buttons while driving"): four buttons on the map
|
||||
// (Android Auto's action strip: at most four, 76 px), the recenter button
|
||||
// only while the map isn't following (as Google Maps), night automatic and
|
||||
// leaving by the topbar's Drive. Per device (localStorage).
|
||||
// Driving mode: the grid of docs/design.adoc ("Layout: a grid, not floating
|
||||
// panels"; the Design canvas' Grid) — the page becomes cells, the map one
|
||||
// of them, nothing over it; values in cells around it, keys in the bottom
|
||||
// row, a menu opens in place of the right column and the map narrows.
|
||||
// Which cell shows what is the screen profile's (public/drive/road.json:
|
||||
// {area, widget, ...} per cell), to be edited in the app later. Per device
|
||||
// (localStorage).
|
||||
const KEY = "drivingMode";
|
||||
const PROFILE_URL = "/drive/road.json";
|
||||
const PITCH_3D = 60; // as map.js's 3D toggle
|
||||
const CHECK_MS = 1000; // how often the recenter button looks whether the map follows
|
||||
const RENDER_MS = 1000;
|
||||
const BORDER_MS = 20000; // the border card's time on the screen // the clock, the follow state; the dashboard's polls render too
|
||||
const SEARCH_DELAY_MS = 300; // after the last key
|
||||
const LOG_POLL_MS = 5000; // the trip log's state and new points
|
||||
const DRIVEN_SOURCE = "trip-driven";
|
||||
const OVER_KMH = 3; // as dashboard.js: over the limit by more than this
|
||||
|
||||
const escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
// key action → [icon, label, title]
|
||||
const KEYS = {
|
||||
trip: ["⚑", "Trip", "The trip's stops: add, move, remove"],
|
||||
points: ["◉", "Points", "Saved points and tracks near the car"],
|
||||
layers: ["◫", "Layers", "Layers on the map, presets"],
|
||||
search: ["⌕", "Search", "Search saved points and places"],
|
||||
menu: ["☰", "Menu", "Menu: the whole route, leave driving"],
|
||||
zoomOut: ["−", "", "Zoom out"],
|
||||
zoomIn: ["+", "", "Zoom in"],
|
||||
pitch: ["3D", "", "2D or 3D"],
|
||||
follow: ["⌖", "", "Follow the position, heading up in 3D"],
|
||||
terrain: ["⛰", "", "Terrain view: roll, pitch, the slope ahead"],
|
||||
palette: ["", "", "Day, dusk, night"],
|
||||
};
|
||||
const NOT_YET = new Set();
|
||||
// A knob's function → the screen keys it stands for (their labels: ⟳ ⟲)
|
||||
const KNOB_KEYS = { zoom: ["zoomIn", "zoomOut"] };
|
||||
const KEYPAD_ABSENT_MS = 5000; // no keypad on the bus: asked again after this
|
||||
// The Terrain view switches itself on off-road (docs/design.adoc, Screen
|
||||
// profiles): an unpaved surface (/api/road, off a route) or roll / pitch past
|
||||
// TILT_DEG for TILT_S; back to the road view after PAVED_BACK_M on paved road.
|
||||
// Closed by hand while still off-road: not again until back on the road.
|
||||
const UNPAVED = new Set(["compacted", "dirt", "gravel", "path", "impassable"]);
|
||||
const TILT_DEG = 10;
|
||||
const TILT_S = 10;
|
||||
const PAVED_BACK_M = 2000;
|
||||
const TERRAIN_AUTO_KEY = "maptool.terrainAuto";
|
||||
const FIELDS = { speed: "Speed", limit: "Limit", altitude: "Altitude", time: "Time", sun: "Sun", nextStop: "Next stop",
|
||||
toNextStop: "To next stop", etaNextStop: "ETA next stop", toEnd: "To the end" };
|
||||
const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
|
||||
const clock = (date) => date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
const app = document.getElementById("app");
|
||||
let route = onRouteChanged((r) => { route = r; render(); });
|
||||
let dash = null; // the dashboard's last state
|
||||
let profile = null;
|
||||
const cells = []; // [{ cell, el }]
|
||||
let openPanel = null;
|
||||
|
||||
export function setupDriving(map, nightButton, routePanel) {
|
||||
let route = onRouteChanged((r) => (route = r));
|
||||
const toggle = document.createElement("button");
|
||||
toggle.type = "button";
|
||||
toggle.className = "topbar__drive";
|
||||
toggle.title = "Driving mode: big buttons, no planning panels";
|
||||
toggle.title = "Driving mode: the cockpit grid, no planning panels";
|
||||
toggle.textContent = "Drive";
|
||||
nightButton.before(toggle);
|
||||
|
||||
const button = (name, label, title, action) => {
|
||||
const el = document.createElement("button");
|
||||
el.type = "button";
|
||||
el.className = `drive-bar__${name}`;
|
||||
el.textContent = label;
|
||||
el.title = title;
|
||||
el.setAttribute("aria-label", title);
|
||||
el.addEventListener("click", action);
|
||||
return el;
|
||||
};
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "drive-bar";
|
||||
bar.hidden = true;
|
||||
bar.append(
|
||||
button("zoomIn", "+", "Zoom in", () => map.zoomIn()),
|
||||
button("zoomOut", "−", "Zoom out", () => map.zoomOut()),
|
||||
button("pitch", "3D", "2D / 3D", () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 })),
|
||||
button("trip", "Trip", "The trip's stops: add, move, remove", () => openTrip(tripPanel.hidden)),
|
||||
button("overview", "Route", "The whole route (the follow pauses)", () => {
|
||||
const overview = () => {
|
||||
const coords = route?.geometry?.coordinates;
|
||||
if (!coords?.length) return;
|
||||
pauseFollow(map);
|
||||
map.fitBounds(coords.reduce((b, c) => b.extend(c), new LngLatBounds(coords[0], coords[0])), { padding: 80, pitch: 0, bearing: 0 });
|
||||
}),
|
||||
);
|
||||
// the one "follow / back to the position", bottom left, only when needed
|
||||
const recenter = button("recenter", "Follow", "Follow the position, heading up in 3D", () => {
|
||||
requestGnssFollow();
|
||||
resumeFollow(map);
|
||||
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
|
||||
recenter.hidden = true;
|
||||
});
|
||||
recenter.hidden = true;
|
||||
// The Trip menu (the navigator's, docs/design.adoc): the stops as big
|
||||
// rows — tap a name to look at it, ↑ ↓ to reorder, ✕ to drop — and big
|
||||
// actions: a stop where the crosshair is (pan the map there first), the
|
||||
// start moved to the car. One level, no dragging, no typing.
|
||||
const tripPanel = document.createElement("div");
|
||||
tripPanel.className = "drive-trip";
|
||||
};
|
||||
|
||||
// The Trip menu (the navigator's, docs/design.adoc; the canvas' GridTrip
|
||||
// and GridSearch): the menu area as cells too — the stops a row each (name
|
||||
// over 3 cells, ✓ ↑ ↓ ✕ a cell each), recording on top, the actions at the
|
||||
// foot. Typing a search turns it into results (+ adds one as a stop), with
|
||||
// their pins on the map. One level, no dragging.
|
||||
const tripPanel = document.createElement("section");
|
||||
tripPanel.className = "drive-panel drive-trip";
|
||||
tripPanel.setAttribute("aria-label", "Trip");
|
||||
tripPanel.hidden = true;
|
||||
tripPanel.innerHTML = `<div class="drive-trip__head"><span>Trip <small class="drive-trip__total"></small></span><button type="button" class="drive-trip__close" aria-label="Close">✕</button></div>
|
||||
<div class="drive-trip__log"><button type="button" data-action="log"></button><span class="drive-trip__log-state"></span></div>
|
||||
<div class="drive-trip__search"><input type="search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
|
||||
<ol class="drive-trip__stops"></ol>
|
||||
<div class="drive-trip__actions">
|
||||
<button type="button" data-action="add">+ Stop at the crosshair</button>
|
||||
<button type="button" data-action="start">Start from here (the car)</button>
|
||||
</div>`;
|
||||
tripPanel.dataset.mode = "trip";
|
||||
tripPanel.innerHTML = `<div class="drive-panel__head">Trip <small class="drive-trip__total"></small></div>
|
||||
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
|
||||
<button type="button" class="drive-trip__log" data-action="log"></button>
|
||||
<button type="button" class="drive-trip__log-state" data-action="recording" title="The recording: its days, export"><span class="drive-cell__label">Recording ▸</span><span class="drive-trip__log-text"></span></button>
|
||||
<div class="drive-trip__search"><input type="search" aria-label="Search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
|
||||
<div class="drive-trip__stops"></div>
|
||||
<div class="drive-trip__results"></div>
|
||||
<button type="button" class="drive-panel__primary drive-trip__add" data-action="add">+ Stop at the crosshair</button>
|
||||
<button type="button" class="drive-trip__start" data-action="start">Start from the car</button>
|
||||
<button type="button" class="drive-trip__back" data-action="back">← Back to the stops</button>`;
|
||||
// The Menu: what has no key of its own (yet).
|
||||
const menuPanel = document.createElement("section");
|
||||
menuPanel.className = "drive-panel drive-menu";
|
||||
menuPanel.setAttribute("aria-label", "Menu");
|
||||
menuPanel.hidden = true;
|
||||
menuPanel.innerHTML = `<div class="drive-panel__head">Menu</div>
|
||||
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
|
||||
<button type="button" class="drive-menu__row" data-action="today">Today ▸ <small>the stops left, tonight, the weather, the day's notes</small></button>
|
||||
<button type="button" class="drive-menu__row" data-action="switches" hidden>Switches ▸ <small>the relays and lights, what drives them</small></button>
|
||||
<button type="button" class="drive-menu__row" data-action="overview">The whole route <small>the follow pauses</small></button>
|
||||
<button type="button" class="drive-menu__row" data-action="terrain-auto"></button>
|
||||
<button type="button" class="drive-menu__row" data-action="voice"></button>
|
||||
<button type="button" class="drive-menu__row" data-action="profile"></button>
|
||||
<button type="button" class="drive-menu__row" data-action="leave">Leave driving mode</button>`;
|
||||
// auto: opens off-road and closes back on the road; stay: opens and stays (the inclinometer all along); hand: neither
|
||||
const TERRAIN_MODES = { auto: "opens and closes by itself", stay: "opens by itself, stays", hand: "by hand" };
|
||||
const terrainMode = () => { try { const m = localStorage.getItem(TERRAIN_AUTO_KEY); return m in TERRAIN_MODES ? m : "auto"; } catch { return "auto"; } };
|
||||
const terrainAuto = () => terrainMode() !== "hand";
|
||||
const autoButton = menuPanel.querySelector('[data-action="terrain-auto"]');
|
||||
const renderAuto = () => { autoButton.innerHTML = `Terrain view: ${TERRAIN_MODES[terrainMode()]} <small>tap to switch</small>`; };
|
||||
autoButton.addEventListener("click", () => {
|
||||
const modes = Object.keys(TERRAIN_MODES);
|
||||
try { localStorage.setItem(TERRAIN_AUTO_KEY, modes[(modes.indexOf(terrainMode()) + 1) % modes.length]); } catch { /* private window: not kept */ }
|
||||
renderAuto();
|
||||
});
|
||||
renderAuto();
|
||||
const voiceButton = menuPanel.querySelector('[data-action="voice"]');
|
||||
const voiceOn = () => { try { return localStorage.getItem(VOICE_KEY) === "on"; } catch { return false; } };
|
||||
const renderVoice = () => { voiceButton.innerHTML = `Voice prompts: ${voiceOn() ? "on" : "off"} <small>tap to switch</small>`; };
|
||||
voiceButton.addEventListener("click", () => {
|
||||
try { localStorage.setItem(VOICE_KEY, voiceOn() ? "off" : "on"); } catch { /* private window: not kept */ }
|
||||
if (voiceOn()) window.speechSynthesis?.speak(new SpeechSynthesisUtterance("Voice prompts on"));
|
||||
renderVoice();
|
||||
});
|
||||
renderVoice();
|
||||
// the profile: a tap goes to the next one (re-routes); the dialog is the desktop's
|
||||
const profileButton = menuPanel.querySelector('[data-action="profile"]');
|
||||
const renderProfile = () => {
|
||||
const { current } = routePanel?.profiles() || {};
|
||||
profileButton.innerHTML = `Profile: ${escapeHtml(current?.name ?? "—")} <small>tap for the next one</small>`;
|
||||
};
|
||||
profileButton.addEventListener("click", () => {
|
||||
const { list, current } = routePanel?.profiles() || { list: [] };
|
||||
if (!list.length) return;
|
||||
routePanel.pickProfile(list[(list.indexOf(current) + 1) % list.length].id);
|
||||
});
|
||||
onVehicle(renderProfile);
|
||||
renderProfile();
|
||||
menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview);
|
||||
menuPanel.querySelector('[data-action="today"]').addEventListener("click", () => open(today.el));
|
||||
menuPanel.querySelector('[data-action="switches"]').addEventListener("click", () => open(switches.el));
|
||||
menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false));
|
||||
const crosshair = document.createElement("div");
|
||||
crosshair.className = "drive-crosshair";
|
||||
crosshair.hidden = true;
|
||||
// Search: saved points (the library) and places (the offline POI
|
||||
// database), nearest the crosshair first; a result's name shows it, + adds
|
||||
// it as a stop. While there's a query the list shows results, not stops.
|
||||
// database), nearest the crosshair first.
|
||||
const input = tripPanel.querySelector(".drive-trip__search input");
|
||||
let results = null;
|
||||
let pins = [];
|
||||
let searchTimer = null;
|
||||
let searchSeq = 0;
|
||||
let searching = false;
|
||||
const setResults = (list) => {
|
||||
results = list;
|
||||
tripPanel.dataset.mode = results ? "search" : "trip";
|
||||
for (const pin of pins) pin.remove();
|
||||
pins = (results || []).map((r) => {
|
||||
const el = document.createElement("div");
|
||||
el.className = `drive-pin drive-pin--${r.kind}`;
|
||||
return new Marker({ element: el }).setLngLat(r.lngLat).addTo(map);
|
||||
});
|
||||
renderTrip();
|
||||
render();
|
||||
};
|
||||
const backToStops = () => {
|
||||
input.value = "";
|
||||
clearTimeout(searchTimer);
|
||||
searchSeq++;
|
||||
searching = false;
|
||||
setResults(null);
|
||||
};
|
||||
input.addEventListener("input", () => {
|
||||
clearTimeout(searchTimer);
|
||||
if (!input.value.trim()) {
|
||||
results = null;
|
||||
return renderTrip();
|
||||
}
|
||||
if (!input.value.trim()) return setResults(null);
|
||||
searching = true;
|
||||
if (!results) setResults([]); // the search layout at once, the input stays focused
|
||||
searchTimer = setTimeout(async () => {
|
||||
const mine = ++searchSeq;
|
||||
const { lng, lat } = map.getCenter();
|
||||
@@ -100,75 +196,137 @@ export function setupDriving(map, nightButton, routePanel) {
|
||||
let found = [];
|
||||
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
|
||||
if (mine !== searchSeq) return;
|
||||
results = found.filter(({ bbox }) => bbox).map(({ name, bbox, source_label: where }) => ({ name, where, lngLat: [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] }));
|
||||
renderTrip();
|
||||
searching = false;
|
||||
setResults(found.filter(({ bbox }) => bbox).map(({ name, bbox, source, source_label: where }) => {
|
||||
const lngLat = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2];
|
||||
return { name, where, lngLat, kind: source === "places" ? "place" : "saved", away: distance(map.getCenter().distanceTo({ lng: lngLat[0], lat: lngLat[1] })) };
|
||||
}));
|
||||
}, SEARCH_DELAY_MS);
|
||||
});
|
||||
tripPanel.querySelector('[data-action="back"]').addEventListener("click", backToStops);
|
||||
const lookAt = (lngLat) => {
|
||||
pauseFollow(map);
|
||||
map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), 14) });
|
||||
};
|
||||
const renderResults = (list) => {
|
||||
list.replaceChildren(...results.map((r) => {
|
||||
const li = document.createElement("li");
|
||||
const name = button("stop-name", r.name, "Show it on the map", () => lookAt(r.lngLat));
|
||||
name.innerHTML = `${escapeHtml(r.name)}<small>${escapeHtml(r.where || "")}</small>`;
|
||||
const add = button("stop-add", "+", "Add as a stop", () => {
|
||||
input.value = "";
|
||||
results = null; // back to the stops, the new one among them
|
||||
list.replaceChildren(...results.flatMap((r) => [
|
||||
cellButton("result", `<span class="drive-pin drive-pin--${r.kind}"></span><span class="drive-panel__text"><b>${escapeHtml(r.name)}</b><small>${escapeHtml(r.where || "")} · ${r.away}</small></span>`,
|
||||
"Show it on the map", () => lookAt(r.lngLat)),
|
||||
cellButton("add", "+", "Add as a stop", () => {
|
||||
backToStops(); // back to the stops, the new one among them
|
||||
routePanel.addStop(r.lngLat, r.name);
|
||||
});
|
||||
li.append(name, add);
|
||||
return li;
|
||||
}));
|
||||
if (!results.length) list.innerHTML = `<li class="drive-trip__empty">Nothing found.</li>`;
|
||||
}),
|
||||
]));
|
||||
if (!results.length) list.append(empty(searching ? "Searching…" : input.value.trim() ? "Nothing found." : "Type a name — saved points and places, nearest first."));
|
||||
};
|
||||
const renderTrip = () => {
|
||||
if (tripPanel.hidden || !routePanel) return;
|
||||
if (results) return renderResults(tripPanel.querySelector(".drive-trip__stops"));
|
||||
if (results) return renderResults(tripPanel.querySelector(".drive-trip__results"));
|
||||
const stops = routePanel.stops();
|
||||
const list = tripPanel.querySelector(".drive-trip__stops");
|
||||
list.replaceChildren(...stops.map((stop, i) => {
|
||||
const li = document.createElement("li");
|
||||
const name = button("stop-name", "", "Show it on the map", () => lookAt(stop.lngLat));
|
||||
const leg = stop.leg ? `<small>+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}</small>` : "";
|
||||
name.innerHTML = `${escapeHtml(stop.label)} · ${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}${leg}`;
|
||||
const done = button("stop-done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
|
||||
list.replaceChildren(...stops.flatMap((stop, i) => {
|
||||
const leg = stop.leg ? `+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}` : "";
|
||||
const name = cellButton("stop", `<span class="drive-panel__text"><small class="drive-cell__label">${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}</small>` +
|
||||
`<b>${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}</b></span>`, "Show it on the map", () => lookAt(stop.lngLat));
|
||||
name.classList.toggle("drive-panel__passed", !!stop.passed || stop.behind);
|
||||
const done = cellButton("done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
|
||||
done.classList.toggle("active", !!stop.passed);
|
||||
li.classList.toggle("drive-trip__passed", !!stop.passed || stop.behind);
|
||||
const up = button("stop-up", "↑", "Earlier", () => routePanel.moveStop(i, -1));
|
||||
const down = button("stop-down", "↓", "Later", () => routePanel.moveStop(i, 1));
|
||||
const drop = button("stop-drop", "✕", "Remove this stop", () => routePanel.removeStop(i));
|
||||
const up = cellButton("up", "↑", "Earlier", () => routePanel.moveStop(i, -1));
|
||||
const down = cellButton("down", "↓", "Later", () => routePanel.moveStop(i, 1));
|
||||
const drop = cellButton("drop", "✕", "Remove this stop", () => routePanel.removeStop(i));
|
||||
up.disabled = i === 0;
|
||||
down.disabled = i === stops.length - 1;
|
||||
li.append(name, done, up, down, drop);
|
||||
return li;
|
||||
return [name, done, up, down, drop];
|
||||
}));
|
||||
if (!stops.length) list.innerHTML = `<li class="drive-trip__empty">No stops yet — pan the map to a place and add it.</li>`;
|
||||
if (!stops.length) list.append(empty("No stops yet — pan the map to a place and add it, or search."));
|
||||
const p = route?.properties;
|
||||
tripPanel.querySelector(".drive-trip__total").textContent = p && stops.length > 1 ? `${p.distance_km.toFixed(1)} km · ${formatDuration(p.time_s)}` : "";
|
||||
};
|
||||
function openTrip(open) {
|
||||
tripPanel.hidden = !open;
|
||||
crosshair.hidden = !open;
|
||||
bar.querySelector(".drive-bar__trip").classList.toggle("active", open);
|
||||
if (open) {
|
||||
// One panel at a time, in the profile's menu area; the map narrows to its
|
||||
// other area (its center — the follow, the crosshair — stays in view).
|
||||
// Points and Layers (drive_menus.js): the car's position, else the map's center.
|
||||
const menuCtx = {
|
||||
map, gpxPanel, routePanel, lookAt,
|
||||
position: () => (dash?.values?.lon != null && dash?.values?.lat != null ? [dash.values.lon, dash.values.lat] : map.getCenter().toArray()),
|
||||
route: () => route,
|
||||
atKm: () => dash?.atKm,
|
||||
close: () => open(null),
|
||||
};
|
||||
const points = pointsMenu(menuCtx);
|
||||
const layers = layersMenu(menuCtx);
|
||||
const terrain = terrainMenu({ ...menuCtx, state: () => dash, openLevel: () => open(level.el) });
|
||||
const level = levelMenu({ ...menuCtx, state: () => dash, openTerrain: () => open(terrain.el) });
|
||||
const recording = recordingMenu({
|
||||
...menuCtx,
|
||||
showBounds: ([w, s, e, n]) => { pauseFollow(map); map.fitBounds([[w, s], [e, n]], { padding: 60, pitch: 0, maxZoom: 15 }); },
|
||||
endTrip: () => endTrip(),
|
||||
});
|
||||
const today = todayMenu(menuCtx);
|
||||
const switches = switchesMenu(menuCtx);
|
||||
switches.available().then((yes) => { menuPanel.querySelector('[data-action="switches"]').hidden = !yes; });
|
||||
const menus = [points, layers, terrain, level, recording, today, switches];
|
||||
let offRoad = false;
|
||||
let tiltSince = null;
|
||||
let pavedM = 0;
|
||||
let autoOpened = false;
|
||||
let suppressed = false;
|
||||
let lastState = Date.now();
|
||||
const autoTerrain = (state) => {
|
||||
const v = state.values || {};
|
||||
const now = Date.now();
|
||||
const dt = (now - lastState) / 1000;
|
||||
lastState = now;
|
||||
// simulated, the tilt is the DEM's slope round the car — on a road cut into a hillside that's the
|
||||
// hill's, not the car's, so it doesn't count (the surface still does); the dials still show it
|
||||
const tilted = !state.simulated && Math.max(Math.abs(v.roll ?? 0), Math.abs(v.pitch ?? 0)) >= TILT_DEG;
|
||||
tiltSince = tilted ? tiltSince ?? now : null;
|
||||
offRoad = UNPAVED.has(state.surface) || (tiltSince != null && now - tiltSince >= TILT_S * 1000);
|
||||
if (offRoad) pavedM = 0;
|
||||
else {
|
||||
suppressed = false;
|
||||
pavedM += (v.speed ?? 0) * dt;
|
||||
}
|
||||
if (!terrainAuto()) return;
|
||||
if (offRoad && !suppressed && !openPanel) {
|
||||
open(terrain.el);
|
||||
autoOpened = true;
|
||||
} else if (terrainMode() === "auto" && autoOpened && openPanel === terrain.el && pavedM >= PAVED_BACK_M) open(null);
|
||||
};
|
||||
function open(panel) {
|
||||
if (openPanel === terrain.el && panel !== terrain.el) {
|
||||
if (offRoad) suppressed = true; // closed by hand off-road: stays closed until the road
|
||||
autoOpened = false;
|
||||
}
|
||||
if (panel !== tripPanel && results) backToStops(); // the pins go with the search
|
||||
menus.find((m) => m.el === openPanel && m.el !== panel)?.closed?.();
|
||||
openPanel = panel;
|
||||
row = 0;
|
||||
tripPanel.hidden = panel !== tripPanel;
|
||||
menuPanel.hidden = panel !== menuPanel;
|
||||
for (const menu of menus) {
|
||||
menu.el.hidden = panel !== menu.el;
|
||||
if (panel === menu.el) menu.opened();
|
||||
}
|
||||
crosshair.hidden = panel !== tripPanel;
|
||||
if (profile) app.style.setProperty("--drive-map", panel ? profile.menu.map : profile.map);
|
||||
map.resize();
|
||||
renderTrip();
|
||||
render();
|
||||
}
|
||||
}
|
||||
tripPanel.querySelector(".drive-trip__close").addEventListener("click", () => openTrip(false));
|
||||
const togglePanel = (panel) => open(openPanel === panel ? null : panel);
|
||||
for (const panel of [tripPanel, menuPanel]) panel.querySelector(".drive-panel__close").addEventListener("click", () => open(null));
|
||||
tripPanel.querySelector('[data-action="add"]').addEventListener("click", () => {
|
||||
const { lng, lat } = map.getCenter();
|
||||
routePanel?.addStop([lng, lat]);
|
||||
});
|
||||
tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere());
|
||||
routePanel?.onStopsChanged(renderTrip);
|
||||
routePanel?.onStopsChanged(() => { renderTrip(); render(); });
|
||||
|
||||
// The trip log (lib/maptool/trip_log.rb): Start makes the trip's library
|
||||
// folder and records the car's GNSS into it, End closes it; the line
|
||||
// really driven drawn in --route-driven, grown by polling ?since=N.
|
||||
const logButton = tripPanel.querySelector('[data-action="log"]');
|
||||
const logState = tripPanel.querySelector(".drive-trip__log-state");
|
||||
const logState = tripPanel.querySelector(".drive-trip__log-text");
|
||||
let log = null;
|
||||
let driven = [];
|
||||
const drawDriven = () => {
|
||||
@@ -198,51 +356,461 @@ export function setupDriving(map, nightButton, routePanel) {
|
||||
setTimeout(pollLog, LOG_POLL_MS);
|
||||
};
|
||||
const renderLog = () => {
|
||||
logButton.textContent = log?.active ? "End the trip" : "Start the trip (record it)";
|
||||
logButton.textContent = log?.active ? "End the trip" : "Start the trip";
|
||||
logButton.classList.toggle("drive-trip__log--on", !!log?.active);
|
||||
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "";
|
||||
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "Not recording";
|
||||
logState.classList.toggle("drive-trip__log-text--on", !!log?.active);
|
||||
document.documentElement.classList.toggle("trip-rec", !!log?.active);
|
||||
};
|
||||
logButton.addEventListener("click", async () => {
|
||||
if (log?.active) {
|
||||
if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
|
||||
const endTrip = async () => {
|
||||
if (!log?.active || !window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
|
||||
await fetch("/api/trip/log", { method: "DELETE" });
|
||||
} else {
|
||||
driven = [];
|
||||
refreshLog();
|
||||
};
|
||||
tripPanel.querySelector('[data-action="recording"]').addEventListener("click", () => open(recording.el));
|
||||
logButton.addEventListener("click", async () => {
|
||||
if (log?.active) return endTrip();
|
||||
const ends = routePanel?.stops().at(-1)?.name || "";
|
||||
const name = window.prompt("The trip's name:", ends);
|
||||
if (name === null) return;
|
||||
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
|
||||
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
|
||||
}
|
||||
driven = [];
|
||||
refreshLog();
|
||||
});
|
||||
if (isLoggedIn()) pollLog();
|
||||
else tripPanel.querySelector(".drive-trip__log").hidden = true;
|
||||
map.getContainer().append(bar, recenter, crosshair);
|
||||
// the Trip menu beside the map, not over it (like Android Auto's side
|
||||
// panel): the map gets narrower and keeps its buttons, its center (the
|
||||
// follow, the crosshair, the overview) stays in what's seen
|
||||
map.getContainer().after(tripPanel);
|
||||
else {
|
||||
logButton.disabled = true;
|
||||
logButton.textContent = "Start the trip";
|
||||
logState.textContent = "Log in to record";
|
||||
}
|
||||
map.getContainer().append(crosshair);
|
||||
app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el, level.el, recording.el, today.el, switches.el);
|
||||
|
||||
const render = () => {
|
||||
bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D";
|
||||
bar.querySelector(".drive-bar__overview").disabled = !route;
|
||||
recenter.hidden = bar.hidden || isFollowing(map);
|
||||
// --- the grid's cells ---------------------------------------------------
|
||||
|
||||
const keyAction = {
|
||||
trip: () => {
|
||||
if (openPanel === tripPanel && results) return backToStops();
|
||||
togglePanel(tripPanel);
|
||||
},
|
||||
search: () => {
|
||||
if (openPanel === tripPanel && results) return open(null);
|
||||
open(tripPanel);
|
||||
if (!results) setResults([]);
|
||||
input.focus();
|
||||
},
|
||||
menu: () => togglePanel(menuPanel),
|
||||
points: () => togglePanel(points.el),
|
||||
layers: () => togglePanel(layers.el),
|
||||
terrain: () => togglePanel(terrain.el),
|
||||
zoomOut: () => map.zoomOut(),
|
||||
zoomIn: () => map.zoomIn(),
|
||||
pitch: () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 }),
|
||||
follow: () => {
|
||||
requestGnssFollow();
|
||||
resumeFollow(map);
|
||||
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
|
||||
render();
|
||||
},
|
||||
palette: () => nightButton.click(),
|
||||
};
|
||||
|
||||
const make = (cell) => {
|
||||
let el;
|
||||
if (cell.widget === "key") {
|
||||
const [icon, label, title] = KEYS[cell.action] || ["?", cell.action, cell.action];
|
||||
el = document.createElement("button");
|
||||
el.type = "button";
|
||||
el.title = title;
|
||||
el.setAttribute("aria-label", label || title);
|
||||
el.innerHTML = `<span class="drive-key__icon">${icon}</span>${label ? `<span class="drive-key__label">${label}</span>` : ""}`;
|
||||
el.disabled = NOT_YET.has(cell.action) || !keyAction[cell.action];
|
||||
el.addEventListener("click", () => keyAction[cell.action]?.());
|
||||
if (cell.action === "zoomIn" || cell.action === "zoomOut") el.classList.add("drive-key--big");
|
||||
if (cell.key) bindKey(el, cell.key);
|
||||
} else {
|
||||
el = document.createElement("div");
|
||||
}
|
||||
el.classList.add("drive-cell", `drive-cell--${cell.widget}`);
|
||||
if (cell.small) el.classList.add("drive-cell--small");
|
||||
el.style.gridArea = cell.area;
|
||||
return el;
|
||||
};
|
||||
|
||||
// To the next stop and to the end, from the km along the route (the start
|
||||
// of it while not on it): the leg's time in proportion to what's left of it.
|
||||
// ponytail: a straight share of the leg's time, Valhalla's per-maneuver times if it's off
|
||||
const ahead = () => {
|
||||
const p = route?.properties;
|
||||
const stops = routePanel?.stops().filter((s) => !s.passed) || [];
|
||||
if (!p?.legs_km?.length || stops.length !== p.legs_km.length + 1) return null;
|
||||
const at = dash?.atKm ?? 0;
|
||||
let end = 0;
|
||||
let i = 0;
|
||||
for (; i < p.legs_km.length; i++) {
|
||||
end += p.legs_km[i];
|
||||
if (end > at + 0.05) break;
|
||||
}
|
||||
i = Math.min(i, p.legs_km.length - 1);
|
||||
const toNext = Math.max(0, end - at);
|
||||
const sNext = p.legs_s?.[i] != null && p.legs_km[i] ? (p.legs_s[i] * toNext) / p.legs_km[i] : null;
|
||||
const toEnd = Math.max(0, p.distance_km - at);
|
||||
const sEnd = sNext != null ? sNext + p.legs_s.slice(i + 1).reduce((a, b) => a + b, 0) : (p.time_s * toEnd) / p.distance_km;
|
||||
const stop = stops[i + 1];
|
||||
return { name: stop.name || stop.label, toNext, sNext, toEnd, sEnd };
|
||||
};
|
||||
|
||||
// [value, unit, class]
|
||||
const fieldValue = (name, a) => {
|
||||
const v = dash?.values || {};
|
||||
const nav = dash?.nav;
|
||||
const kmh = v.speed == null ? null : v.speed * 3.6;
|
||||
const limit = nav?.limit;
|
||||
const now = new Date();
|
||||
switch (name) {
|
||||
case "speed": {
|
||||
// the limit as a sign at the field's end, the next one under it; the speed red past the limit
|
||||
const next = nav?.next ? `${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
|
||||
const sign = typeof limit === "number" || limit === "unlimited"
|
||||
? `<span class="drive-speed__limit" aria-label="Limit ${limit}"><b>${limit === "unlimited" ? "∞" : limit}</b>${next ? `<small>${escapeHtml(next)}</small>` : ""}</span>` : "";
|
||||
return [kmh == null ? "—" : Math.round(kmh), "km/h", typeof limit === "number" && kmh > limit + OVER_KMH ? "drive-cell--warn" : "", sign];
|
||||
}
|
||||
case "limit": {
|
||||
const next = nav?.next ? `· ${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
|
||||
return [typeof limit === "number" ? limit : limit === "unlimited" ? "∞" : "—", next, "drive-cell--limit"];
|
||||
}
|
||||
case "altitude":
|
||||
return [v.alt == null ? "—" : Math.round(v.alt), "m"];
|
||||
case "time":
|
||||
return [clock(now), ""];
|
||||
case "sun": {
|
||||
const { lng, lat } = map.getCenter();
|
||||
const info = formatSunInfo(lat, lng, now);
|
||||
if (!info) return ["—", ""];
|
||||
if (info.polar) return [info.polar, ""];
|
||||
return info.countdown?.endsWith("sunrise") ? [info.sunrise, "rise"] : [info.sunset, "set"];
|
||||
}
|
||||
case "nextStop":
|
||||
return [a?.name ?? "—", ""];
|
||||
case "toNextStop":
|
||||
return a ? [a.toNext.toFixed(1), `km${a.sNext != null ? ` · ${formatDuration(a.sNext)}` : ""}`] : ["—", ""];
|
||||
case "etaNextStop":
|
||||
return [a?.sNext != null ? clock(new Date(now.getTime() + a.sNext * 1000)) : "—", ""];
|
||||
case "toEnd":
|
||||
return a ? [a.toEnd.toFixed(1), `km · ${clock(new Date(now.getTime() + a.sEnd * 1000))}`] : ["—", ""];
|
||||
default:
|
||||
return ["?", ""];
|
||||
}
|
||||
};
|
||||
|
||||
// Under the maneuver, over the map, only when there's something: the next
|
||||
// maneuver's lanes (from 1 km, further at speed) and the next traffic signal.
|
||||
const renderAhead = (el) => {
|
||||
const n = dash?.nav;
|
||||
const lanes = !n?.arrived && n?.maneuver?.lanes && n.maneuver.m <= n.lanesM ? n.maneuver.lanes : null;
|
||||
const signal = n?.signal != null && n.signal <= 1000 ? n.signal : null;
|
||||
el.hidden = !lanes && signal == null;
|
||||
if (el.hidden) return;
|
||||
el.innerHTML = (lanes ? `<div class="dash-lanes drive-ahead__lanes">${lanes.map(laneSvg).join("")}</div>` : "") +
|
||||
(signal != null ? `<span class="drive-ahead__signal"><span class="dash-signal"></span>${distance(signal)}</span>` : "");
|
||||
};
|
||||
|
||||
// Past a border (the country along the route, or of the road driven):
|
||||
// the new country's limits for the profile and how its motorways are
|
||||
// paid, for BORDER_MS or until tapped (the Design canvas' GridBorder).
|
||||
let country = null;
|
||||
let border = null; // { code, until }
|
||||
const renderBorder = (el) => {
|
||||
const code = dash?.nav?.country;
|
||||
if (code && code !== country) {
|
||||
if (country) border = { code, until: Date.now() + BORDER_MS };
|
||||
country = code;
|
||||
}
|
||||
el.hidden = !border || Date.now() > border.until;
|
||||
if (el.hidden) return;
|
||||
if (!el.dataset.wired) {
|
||||
el.dataset.wired = "1";
|
||||
el.addEventListener("click", () => { border = null; el.hidden = true; });
|
||||
}
|
||||
const heavy = isHeavy(currentVehicle);
|
||||
const row = SPEED_LIMITS[border.code]?.[heavy ? "heavy" : "car"];
|
||||
const pay = motorwayPayment(border.code, currentVehicle);
|
||||
const sign = (v, k) => `<span class="drive-border__limit"><span class="drive-speed__limit"><b>${v ?? "–"}</b></span><small>${k}</small></span>`;
|
||||
let name = border.code;
|
||||
try { name = COUNTRY_NAMES.of(border.code); } catch { /* not a region code */ }
|
||||
el.innerHTML = `<div class="drive-border__head"><b>${escapeHtml(name)}</b><span class="drive-cell__muted">${border.code}${currentVehicle ? ` · ${escapeHtml(currentVehicle.name)}` : ""}</span></div>` +
|
||||
(row ? `<div class="drive-border__signs">${sign(row[0], "Motorway")}${sign(row[2], "Outside towns")}${sign(row[3], "In towns")}</div>` : `<span class="drive-cell__muted">No limits known for ${border.code}</span>`) +
|
||||
(pay.how ? `<span class="drive-border__pays">Motorways: ${pay.how} ${pay.has ? "✓" : "— not in the profile"}</span>` : "");
|
||||
};
|
||||
|
||||
const renderManeuver = (el) => {
|
||||
const n = dash?.nav;
|
||||
if (n?.offRoute) {
|
||||
el.innerHTML = `<div><span class="drive-cell__value drive-cell--caution">Off the route</span><span class="drive-cell__label">rerouting</span></div>`;
|
||||
} else if (n?.arrived) {
|
||||
el.innerHTML = `${maneuverSvg(4)}<div class="drive-cell__text"><span class="drive-cell__value">Arrived</span><span class="drive-cell__street">${escapeHtml(n.street || "")}</span></div>`;
|
||||
} else if (n?.maneuver) {
|
||||
const { m, type, street, text, exit } = n.maneuver;
|
||||
const what = street ? `${exit ? `${exit}. exit · ` : ""}${escapeHtml(street)}` : escapeHtml(text);
|
||||
const then = n.then ? ` <span class="drive-cell__muted">· then ${escapeHtml(n.then.street || n.then.text)}</span>` : "";
|
||||
el.innerHTML = `${maneuverSvg(type)}<div class="drive-cell__text"><span class="drive-cell__value">${distance(m)}</span><span class="drive-cell__street">${what}${then}</span></div>`;
|
||||
} else {
|
||||
el.innerHTML = `<div class="drive-cell__text"><span class="drive-cell__label">On</span><span class="drive-cell__street">${escapeHtml(n?.street ?? "—")}</span></div>`;
|
||||
}
|
||||
};
|
||||
|
||||
const renderElevation = (el, cell) => { el.innerHTML = elevationHtml(route, dash?.atKm, cell.km || 10); };
|
||||
|
||||
|
||||
const renderCompass = (el) => {
|
||||
const h = dash?.heading;
|
||||
const deg = h ? Math.round(h.deg) % 360 : null;
|
||||
el.innerHTML = `<svg class="drive-compass${h && !h.live ? " drive-compass--stale" : ""}" viewBox="-50 -50 100 100" role="img" aria-label="${deg == null ? "No heading" : `Heading ${deg}°`}">
|
||||
<circle r="46" class="drive-compass__ring"/>
|
||||
<g transform="rotate(${-(deg ?? 0)})">
|
||||
<path d="M0 -40 L6 0 L0 -6 L-6 0 Z" class="drive-compass__north"/>
|
||||
<path d="M0 40 L6 0 L0 6 L-6 0 Z" class="drive-compass__south"/>
|
||||
<text y="-22" transform="rotate(${deg ?? 0} 0 -27)" class="drive-compass__n">N</text>
|
||||
</g>
|
||||
<path d="M0 -50 l-5 0 l5 10 l5 -10 z" class="drive-compass__lubber"/>
|
||||
</svg>
|
||||
<span class="drive-cell__text"><span class="drive-cell__label">Heading</span><span class="drive-cell__value drive-cell__value--mid">${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} <small>${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}</small></span></span>`;
|
||||
};
|
||||
|
||||
const renderKey = (el, cell) => {
|
||||
const pressed = { trip: openPanel === tripPanel && !results, search: openPanel === tripPanel && !!results, points: openPanel === points.el, layers: openPanel === layers.el, terrain: openPanel === terrain.el, menu: openPanel === menuPanel, pitch: map.getPitch() > 0, follow: isFollowing(map) }[cell.action];
|
||||
el.setAttribute("aria-pressed", String(!!pressed));
|
||||
if (cell.action === "palette") el.querySelector(".drive-key__icon").textContent = nightButton.textContent;
|
||||
};
|
||||
|
||||
function render() {
|
||||
if (!document.documentElement.classList.contains("driving")) return;
|
||||
if (openPanel === terrain.el) terrain.render();
|
||||
if (openPanel === level.el) level.render();
|
||||
const a = ahead();
|
||||
for (const { cell, el } of cells) {
|
||||
if (cell.widget === "field") {
|
||||
const name = cell.value;
|
||||
const [value, unit, cls = "", extra = ""] = fieldValue(name, a);
|
||||
el.innerHTML = `${extra}<span class="drive-cell__label">${FIELDS[name] || name}</span><span class="drive-cell__value ${cls}">${escapeHtml(value)} <small>${escapeHtml(unit)}</small></span>`;
|
||||
} else if (cell.widget === "maneuver") renderManeuver(el);
|
||||
else if (cell.widget === "ahead") renderAhead(el);
|
||||
else if (cell.widget === "border") renderBorder(el);
|
||||
else if (cell.widget === "status") {
|
||||
el.innerHTML = `<b class="drive-status__brand">MAPTOOL</b><span class="drive-cell__muted"><span class="${navigator.onLine ? "drive-status--ok" : ""}">●</span> ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · <span class="drive-status--rec">● rec</span>` : ""}</span>`;
|
||||
} else if (cell.widget === "elevation") renderElevation(el, cell);
|
||||
else if (cell.widget === "compass") renderCompass(el);
|
||||
else if (cell.widget === "key") renderKey(el, cell);
|
||||
}
|
||||
sendLeds();
|
||||
}
|
||||
map.on("pitchend", render);
|
||||
onRouteChanged(render);
|
||||
setInterval(render, CHECK_MS);
|
||||
setInterval(render, RENDER_MS);
|
||||
|
||||
// the keypads' bindings: this car's own (saved in /keypad.html) over the profile's
|
||||
const savedBindings = fetch("/api/keypad/bindings", { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
||||
fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then(async (p) => {
|
||||
p.bindings = (await savedBindings)?.bindings || p.bindings;
|
||||
profile = p;
|
||||
// Cells of p.cell px at most; on a bigger screen only the map's columns
|
||||
// and rows (beside an open menu) stretch, the rest stays cell-sized.
|
||||
const [mr1, mc1, mr2, mc2] = p.menu.map.split("/").map(Number);
|
||||
const track = (n, from, to) => Array.from({ length: n }, (_, i) => (i + 1 >= from && i + 1 < to ? "minmax(0, 1fr)" : "var(--cell)")).join(" ");
|
||||
// One scale for everything (--s): the cells, the type, the icons — the
|
||||
// same elements on a 7″ as on the 16″, only smaller; never bigger than drawn.
|
||||
const fit = () => {
|
||||
const scale = Math.min(1, window.innerWidth / (p.columns * (p.cell || 80)), window.innerHeight / (p.rows * (p.cell || 80)));
|
||||
app.style.setProperty("--s", scale.toFixed(3));
|
||||
app.style.setProperty("--cell", `${((p.cell || 80) * scale).toFixed(1)}px`);
|
||||
};
|
||||
fit();
|
||||
window.addEventListener("resize", fit);
|
||||
app.style.setProperty("--drive-columns", track(p.columns, mc1, mc2));
|
||||
app.style.setProperty("--drive-row-sizes", track(p.rows, mr1, mr2));
|
||||
app.style.setProperty("--drive-map", openPanel ? p.menu.map : p.map);
|
||||
app.style.setProperty("--drive-menu", p.menu.area);
|
||||
const [r1, c1, r2, c2] = p.menu.area.split("/").map(Number);
|
||||
app.style.setProperty("--drive-menu-cols", c2 - c1);
|
||||
app.style.setProperty("--drive-menu-mid", r2 - r1 - 4); // the list rows between the 3 on top and the foot
|
||||
for (const cell of p.cells) {
|
||||
const el = make(cell);
|
||||
app.append(el);
|
||||
cells.push({ cell, el });
|
||||
}
|
||||
labelKeys(); // a keypad heard before the profile came
|
||||
render();
|
||||
map.resize();
|
||||
});
|
||||
|
||||
function set(on) {
|
||||
if (!on) openTrip(false);
|
||||
if (!on) open(null);
|
||||
document.documentElement.classList.toggle("driving", on);
|
||||
bar.hidden = !on;
|
||||
toggle.classList.toggle("active", on);
|
||||
try { localStorage.setItem(KEY, on ? "on" : "off"); } catch { /* private window: not kept */ }
|
||||
watchDashboard(on ? (state) => {
|
||||
dash = state;
|
||||
autoTerrain(state);
|
||||
render();
|
||||
map.resize(); // the sidebar came or went
|
||||
} : null);
|
||||
render();
|
||||
map.resize(); // the grid came or went
|
||||
}
|
||||
toggle.addEventListener("click", () => set(bar.hidden));
|
||||
toggle.addEventListener("click", () => set(!document.documentElement.classList.contains("driving")));
|
||||
|
||||
// Keys (canvas GridKeys): a screen key's "key" in the profile clicks it, a
|
||||
// menu's [data-key] buttons too (1 2 3, H); in an open menu ↑ ↓ move the row
|
||||
// (the keypad's encoder will send the same arrows), Enter its first button,
|
||||
// Space its eye, + adds it, ⌫ up a folder, Esc closes. The labels in the
|
||||
// corners show from the first key pressed on, so a touch-only screen stays clean.
|
||||
// (The keypads' channels: the profile's bindings, further down.)
|
||||
const KEYS_SEEN = "maptool.driveKeys";
|
||||
let row = 0;
|
||||
try { if (localStorage.getItem(KEYS_SEEN)) document.documentElement.classList.add("drive-keys"); } catch { /* nothing kept */ }
|
||||
const norm = (k) => (k.length === 1 ? k.toLowerCase() : k);
|
||||
const visible = (b) => b.offsetParent && !b.disabled;
|
||||
const rowsOf = (panel) => {
|
||||
const rows = new Map();
|
||||
for (const b of panel.querySelectorAll("button:not(.drive-panel__close)")) {
|
||||
if (!visible(b)) continue;
|
||||
const top = Math.round(b.getBoundingClientRect().top);
|
||||
rows.set(top, [...(rows.get(top) || []), b]);
|
||||
}
|
||||
return [...rows].sort((a, b) => a[0] - b[0]).map(([, r]) => r);
|
||||
};
|
||||
const markRow = (scroll) => {
|
||||
for (const b of document.querySelectorAll(".drive-focus")) b.classList.remove("drive-focus", "drive-focus--main");
|
||||
if (!openPanel || !document.documentElement.classList.contains("drive-keys")) return [];
|
||||
const rows = rowsOf(openPanel);
|
||||
row = Math.max(0, Math.min(row, rows.length - 1));
|
||||
const current = rows[row] || [];
|
||||
for (const b of current) b.classList.add("drive-focus");
|
||||
current[0]?.classList.add("drive-focus--main");
|
||||
if (scroll) current[0]?.scrollIntoView({ block: "nearest" });
|
||||
return current;
|
||||
};
|
||||
let marking = 0; // the menus re-render their rows: the highlight follows, once a frame
|
||||
new MutationObserver(() => { marking ||= requestAnimationFrame(() => { marking = 0; markRow(false); }); }).observe(app, { childList: true, subtree: true });
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (!document.documentElement.classList.contains("driving") || e.ctrlKey || e.altKey || e.metaKey) return;
|
||||
const key = norm(e.key);
|
||||
const move = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
|
||||
if (e.target.matches?.("input, textarea, select")) {
|
||||
if (key === "Escape" || move) e.target.blur(); else return; // typing a search
|
||||
}
|
||||
if (!document.documentElement.classList.contains("drive-keys")) {
|
||||
document.documentElement.classList.add("drive-keys");
|
||||
try { localStorage.setItem(KEYS_SEEN, "1"); } catch { /* private window: not kept */ }
|
||||
}
|
||||
const current = markRow(false);
|
||||
const press = (b) => (b && visible(b) ? (b.click(), true) : false);
|
||||
const bound = (scope) => [...(scope?.querySelectorAll("[data-key]") || [])].find((b) => norm(b.dataset.key) === key && visible(b));
|
||||
let done = false;
|
||||
if (key === "Escape") done = !!openPanel && (open(null), true);
|
||||
else if (openPanel && move) { row += move; markRow(true); done = true; }
|
||||
else if (openPanel && key === "Enter") done = press(current[0]);
|
||||
else if (openPanel && key === " ") done = press(current.find((b) => b.classList.contains("drive-panel__eye")));
|
||||
else if (openPanel && key === "Backspace") done = press(openPanel.querySelector(".drive-panel__up"));
|
||||
if (!done && openPanel && key === "+") done = press(current.find((b) => b.classList.contains("drive-panel__add")));
|
||||
if (!done) done = press(bound(openPanel) || bound(app));
|
||||
if (done) e.preventDefault(); // F1, F5, / are the browser's otherwise
|
||||
});
|
||||
|
||||
// Keypads (can.json's "keypads", GET /api/keypad, a long poll) and the
|
||||
// profile's "bindings" (docs/design.adoc, Switches and the keypad): a
|
||||
// channel ("pad.K1", "pad.E3" — a key, a knob, its "press") → an action,
|
||||
// another one while a menu is open ("menu"). A screen key's action clicks
|
||||
// it; knobs turn: zoom, panX / panY, rows (the menu's ↑ ↓); enter, close.
|
||||
// A keypad's heartbeat on the bus labels the screen keys with its
|
||||
// channels (none = touch only) and the line under them in the binding's
|
||||
// LED colour; its key LEDs follow them, "led_on" (green) while on.
|
||||
// ponytail: screen functions only — outputs (relays), the modes (hold,
|
||||
// pulse, positions…) and the mapping UI (the canvas' GridBinding) to come.
|
||||
const bindings = () => profile?.bindings || [];
|
||||
let present = [];
|
||||
let ledsSent = {};
|
||||
const keyEl = (action) => cells.find((c) => c.cell.widget === "key" && c.cell.action === action)?.el;
|
||||
const shortName = (input) => input.slice(input.indexOf(".") + 1).replace(/ press$/, " ⏎");
|
||||
function labelKeys() {
|
||||
for (const { cell, el } of cells) {
|
||||
if (cell.widget !== "key") continue;
|
||||
delete el.dataset.keypad;
|
||||
delete el.dataset.led;
|
||||
}
|
||||
for (const b of bindings()) {
|
||||
if (!present.some((d) => b.input.startsWith(`${d.name}.`)) || !b.action) continue;
|
||||
const knob = KNOB_KEYS[b.action];
|
||||
for (const [i, action] of (knob || [b.action]).entries()) {
|
||||
const el = keyEl(action);
|
||||
if (!el) continue;
|
||||
el.dataset.keypad = shortName(b.input) + (knob ? (i ? " ⟲" : " ⟳") : "");
|
||||
if (b.led) el.dataset.led = b.led;
|
||||
}
|
||||
}
|
||||
}
|
||||
function sendLeds() {
|
||||
for (const d of present.filter((p) => p.leds)) {
|
||||
const on = {};
|
||||
for (const b of bindings()) {
|
||||
const k = b.input.startsWith(`${d.name}.`) && /^K\d+$/.exec(b.input.slice(d.name.length + 1))?.[0];
|
||||
const el = k && b.led && keyEl(b.action);
|
||||
if (el) on[k] = el.disabled ? null : el.getAttribute("aria-pressed") === "true" ? b.led_on || "green" : b.led;
|
||||
}
|
||||
const body = JSON.stringify({ keypad: d.name, on });
|
||||
if (body === ledsSent[d.name]) continue;
|
||||
ledsSent[d.name] = body;
|
||||
fetch("/api/keypad/leds", { method: "PUT", headers: { "Content-Type": "application/json" }, body }).catch(() => { ledsSent[d.name] = ""; });
|
||||
}
|
||||
}
|
||||
const navKey = (key) => document.dispatchEvent(new KeyboardEvent("keydown", { key }));
|
||||
const PAN_PX = 80;
|
||||
const knobAction = {
|
||||
zoom: (dir) => keyEl(dir > 0 ? "zoomIn" : "zoomOut")?.click(),
|
||||
panX: (dir) => map.panBy([dir * PAN_PX, 0], { duration: 100 }),
|
||||
panY: (dir) => map.panBy([0, dir * PAN_PX], { duration: 100 }),
|
||||
rows: (dir) => navKey(dir > 0 ? "ArrowDown" : "ArrowUp"),
|
||||
enter: () => navKey("Enter"),
|
||||
close: () => navKey("Escape"),
|
||||
};
|
||||
const onInput = (event) => {
|
||||
if (!document.documentElement.classList.contains("driving")) return;
|
||||
const [, channel, turn] = /^(.*?)(?: (⟳|⟲))?$/.exec(event);
|
||||
const b = bindings().find((x) => x.input === channel);
|
||||
const action = (openPanel && b?.menu) || b?.action;
|
||||
if (!action) return;
|
||||
if (knobAction[action]) return knobAction[action](turn === "⟲" ? -1 : 1);
|
||||
const el = keyEl(action);
|
||||
if (el && visible(el)) el.click();
|
||||
};
|
||||
(async function keypadLoop() {
|
||||
let since = null;
|
||||
for (;;) {
|
||||
let answer = null;
|
||||
try {
|
||||
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
|
||||
if (response.status === 404) return; // no keypads configured on this server
|
||||
if (response.ok) answer = await response.json();
|
||||
} catch { /* the server restarting, offline for a moment */ }
|
||||
const now = answer?.present || [];
|
||||
if (JSON.stringify(now) !== JSON.stringify(present)) {
|
||||
present = now;
|
||||
document.documentElement.classList.toggle("drive-keypad", present.length > 0);
|
||||
if (present.length) document.documentElement.classList.add("drive-keys");
|
||||
ledsSent = {};
|
||||
labelKeys();
|
||||
sendLeds();
|
||||
}
|
||||
if (!present.length) {
|
||||
since = null;
|
||||
await new Promise((r) => setTimeout(r, KEYPAD_ABSENT_MS));
|
||||
continue;
|
||||
}
|
||||
if (since != null) for (const e of answer.events) onInput(e.input);
|
||||
since = answer.seq;
|
||||
}
|
||||
})();
|
||||
|
||||
let saved = null;
|
||||
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
|
||||
set(saved === "on");
|
||||
|
||||
@@ -245,9 +245,27 @@ export class GnssControl {
|
||||
this._marker.setRotation(data.track);
|
||||
}
|
||||
this._marker.getElement().classList.toggle("gnss-marker--estimated", !!data.estimated);
|
||||
this._showTag(lngLat, data);
|
||||
}
|
||||
|
||||
// The status pill above the car (pypilot's note in the Design canvas' SidePanel): REC while
|
||||
// drive mode records the trip (it sets .trip-rec on <html>), estimated / no fix; none when all is well
|
||||
_showTag(lngLat, data) {
|
||||
const rec = document.documentElement.classList.contains("trip-rec");
|
||||
const fix = data.estimated ? "estimated" : data.mode >= 2 ? "" : "no fix";
|
||||
if (!rec && !fix) return this._tag?.getElement().replaceChildren();
|
||||
if (!this._tag) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "gnss-tag";
|
||||
this._tag = new Marker({ element: el, anchor: "bottom", offset: [0, -16] }).setLngLat(lngLat).addTo(this._map);
|
||||
}
|
||||
glideMarker(this._tag, lngLat, POLL_INTERVAL_MS);
|
||||
this._tag.getElement().innerHTML = (rec ? `<span class="gnss-tag__rec">● REC</span>` : "") + (fix ? `<span>${fix}</span>` : "");
|
||||
}
|
||||
|
||||
_removeMarker() {
|
||||
this._tag?.remove();
|
||||
this._tag = null;
|
||||
if (this._marker) {
|
||||
this._marker.remove();
|
||||
this._marker = null;
|
||||
|
||||
+305
-167
@@ -4,9 +4,6 @@ import {
|
||||
GPX_ICON,
|
||||
NEW_FOLDER_ICON,
|
||||
UPLOAD_ICON,
|
||||
WAYPOINT_ICON,
|
||||
TRACK_ICON,
|
||||
ROUTE_ICON,
|
||||
DOWNLOAD_ICON,
|
||||
SYNC_ICON,
|
||||
MAP_MARKER_ICON,
|
||||
@@ -31,6 +28,9 @@ const POI_ICON_KEYS = Object.keys(POI_ICONS);
|
||||
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||
const POI_ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
|
||||
const MAP_MARKER_SIZE = 0.55;
|
||||
// The clusters as the same rounded-square badge, light -> dark by count
|
||||
// (16 / 20 / 26 px "radius" before, now that half the side).
|
||||
const CLUSTER_COLORS = ["#a8c8ea", "#5b9bd5", "#2e6da4"];
|
||||
const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge color actually seen, see _registerBadgeColors
|
||||
|
||||
// Custom drag payload MIME type for moving an already-uploaded file between
|
||||
@@ -38,7 +38,15 @@ const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge
|
||||
// one — both land on the same drop targets, told apart by this.
|
||||
const MOVE_MIME = "application/x-gpx-path";
|
||||
const GPX_VISIBLE_KEY = "gpxVisible";
|
||||
const FOLDER_DRAG_PREFIX = "folder:"; // a dragged folder's MOVE_MIME payload, vs. a node key
|
||||
// The kinds the Library filters by: chip label, a row's word for one, glyph and colour.
|
||||
const KINDS = {
|
||||
waypoint: { label: "Points", one: "points", glyph: "●", color: "#12bedf" },
|
||||
track: { label: "Tracks", one: "track", glyph: "〰", color: "#c2410c" },
|
||||
route: { label: "Routes", one: "route", glyph: "↝", color: "#1d6fdc" },
|
||||
layer: { label: "Layers", one: "layer", glyph: "▤", color: "#6b6b66" },
|
||||
};
|
||||
const FOLDER_DRAG_PREFIX = "folder:";
|
||||
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; // a dragged folder's MOVE_MIME payload, vs. a node key
|
||||
|
||||
// A sidebar icon that opens a side panel for uploading GPX files (via
|
||||
// drag & drop, stored server-side in a folder hierarchy the user can add to
|
||||
@@ -119,7 +127,7 @@ export class GpxPanelControl {
|
||||
mount(sidebar) {
|
||||
this._container = document.createElement("div");
|
||||
this._container.className = "sidebar-item";
|
||||
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Tracks & Points" aria-label="Tracks & Points">${GPX_ICON}</button>`;
|
||||
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Library" aria-label="Library">${GPX_ICON}</button>`;
|
||||
this._icon = this._container.querySelector(".sidebar-icon");
|
||||
this._icon.addEventListener("click", () => this._togglePanel());
|
||||
|
||||
@@ -162,6 +170,7 @@ export class GpxPanelControl {
|
||||
// panels.
|
||||
document.addEventListener("click", () => this._closeDownloadMenu());
|
||||
|
||||
this._setupFind();
|
||||
this._setupToolbarActions();
|
||||
this._setupRootDropTarget();
|
||||
this._setupMapDropTarget();
|
||||
@@ -184,13 +193,13 @@ export class GpxPanelControl {
|
||||
_setupToolbarActions() {
|
||||
const fileInput = this._panel.querySelector(".gpx-file-input");
|
||||
fileInput.addEventListener("change", () => {
|
||||
this._uploadFiles(fileInput.files, "");
|
||||
this._uploadFiles(fileInput.files, this._cwd);
|
||||
fileInput.value = "";
|
||||
});
|
||||
|
||||
this._panel.querySelector('[data-action="upload"]').addEventListener("click", () => fileInput.click());
|
||||
this._panel.querySelector('[data-action="new-folder"]').addEventListener("click", async () => {
|
||||
const path = window.prompt("New folder name (e.g. Hiking/2026):");
|
||||
const path = window.prompt("New folder name (e.g. Hiking/2026):", this._cwd ? `${this._cwd}/` : "");
|
||||
if (!path || !path.trim()) return;
|
||||
|
||||
const response = await fetch(FOLDER_URL, {
|
||||
@@ -223,11 +232,11 @@ export class GpxPanelControl {
|
||||
event.preventDefault();
|
||||
this._treeContainer.classList.remove("gpx-drop-hover");
|
||||
if (event.dataTransfer.files?.length > 0) {
|
||||
this._uploadFiles(event.dataTransfer.files, "");
|
||||
this._uploadFiles(event.dataTransfer.files, this._cwd);
|
||||
return;
|
||||
}
|
||||
const from = event.dataTransfer.getData(MOVE_MIME);
|
||||
if (from) this._moveFile(from, "");
|
||||
if (from) this._moveFile(from, this._cwd);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -258,67 +267,266 @@ export class GpxPanelControl {
|
||||
this._renderTree(tree);
|
||||
}
|
||||
|
||||
// The Design canvas' Library (after Locus Map): find on top — the text,
|
||||
// what kinds, only the shown ones — then one folder level at a time (← up,
|
||||
// the path), or, while searching or in List view, every match flat with
|
||||
// the folder it lives in. An eye per row: ● shown, ◐ some (a folder), ○ not.
|
||||
_renderTree(node) {
|
||||
this._root = node;
|
||||
this._files = new Map();
|
||||
const index = (n) => (n.children || []).forEach((c) => (c.type === "folder" ? index(c) : this._files.set(c.path, c)));
|
||||
index(node);
|
||||
this._treeContainer.innerHTML = "";
|
||||
this._treeContainer.appendChild(this._renderChildren(node.children));
|
||||
}
|
||||
|
||||
_renderChildren(children) {
|
||||
const ul = document.createElement("ul");
|
||||
if (children.length === 0) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "gpx-tree__empty";
|
||||
li.textContent = "No files yet";
|
||||
ul.appendChild(li);
|
||||
return ul;
|
||||
}
|
||||
|
||||
children.forEach((child) => {
|
||||
const li = document.createElement("li");
|
||||
if (child.type === "folder") {
|
||||
li.appendChild(this._renderFolder(child));
|
||||
} else if (child.points) {
|
||||
li.appendChild(this._renderTrackWithPoints(child));
|
||||
this._folders = new Map([["", node]]);
|
||||
const index = (n) => (n.children || []).forEach((c) => {
|
||||
if (c.type === "folder") {
|
||||
this._folders.set(c.path, c);
|
||||
index(c);
|
||||
} else {
|
||||
li.appendChild(this._renderFile(child));
|
||||
c.folder = n.path;
|
||||
this._files.set(c.path, c);
|
||||
}
|
||||
ul.appendChild(li);
|
||||
});
|
||||
|
||||
return ul;
|
||||
index(node);
|
||||
if (!this._folders.has(this._cwd ?? "")) this._cwd = "";
|
||||
if (this._openTrack && !this._files.has(this._openTrack)) this._openTrack = null;
|
||||
this._renderView();
|
||||
}
|
||||
|
||||
// A track/route holding points: collapsed by default (there can be many),
|
||||
// each point zooms to itself and can be taken out again.
|
||||
_renderTrackWithPoints(file) {
|
||||
this._openTracks ||= new Set();
|
||||
const details = document.createElement("details");
|
||||
details.className = "gpx-tree__track";
|
||||
details.open = this._openTracks.has(file.path);
|
||||
details.addEventListener("toggle", () => (details.open ? this._openTracks.add(file.path) : this._openTracks.delete(file.path)));
|
||||
const summary = document.createElement("summary");
|
||||
summary.appendChild(this._renderFile(file));
|
||||
details.appendChild(summary);
|
||||
_setupFind() {
|
||||
this._cwd = "";
|
||||
this._query = "";
|
||||
this._mode = "folders";
|
||||
this._kindsOn = new Set(Object.keys(KINDS));
|
||||
this._shownOnly = false;
|
||||
const find = this._panel.querySelector(".lib-find");
|
||||
const input = find.querySelector(".lib-find__input");
|
||||
input.addEventListener("input", () => {
|
||||
this._query = input.value.trim().toLowerCase();
|
||||
this._renderView();
|
||||
});
|
||||
find.querySelector(".lib-find__kinds").addEventListener("click", (event) => {
|
||||
const chip = event.target.closest("[data-kind]");
|
||||
if (!chip) return;
|
||||
const kind = chip.dataset.kind;
|
||||
if (this._kindsOn.has(kind) && this._kindsOn.size > 1) this._kindsOn.delete(kind);
|
||||
else this._kindsOn.add(kind);
|
||||
this._renderView();
|
||||
});
|
||||
find.querySelector('[data-find="shown"]').addEventListener("click", () => {
|
||||
this._shownOnly = !this._shownOnly;
|
||||
this._renderView();
|
||||
});
|
||||
find.querySelectorAll("[data-mode]").forEach((button) => button.addEventListener("click", () => {
|
||||
this._mode = button.dataset.mode;
|
||||
this._renderView();
|
||||
}));
|
||||
this._crumb = this._panel.querySelector(".lib-crumb");
|
||||
this._footer = this._panel.querySelector(".lib-foot__text");
|
||||
this._panel.querySelector('[data-action="hide-all"]').addEventListener("click", () => {
|
||||
[...this._visible].forEach((path) => this._toggleFileOnly(path, false));
|
||||
this._saveVisible();
|
||||
this._renderView();
|
||||
});
|
||||
}
|
||||
|
||||
_kindOf(file) {
|
||||
if (file.layer) return "layer";
|
||||
if (file.kinds?.includes("route")) return "route";
|
||||
if (file.kinds?.includes("track")) return "track";
|
||||
return "waypoint";
|
||||
}
|
||||
|
||||
_matches(file) {
|
||||
if (!this._kindsOn.has(this._kindOf(file))) return false;
|
||||
if (this._shownOnly && !this._visible.has(file.path)) return false;
|
||||
return !this._query || `${file.folder} ${file.name}`.toLowerCase().includes(this._query);
|
||||
}
|
||||
|
||||
// Every file under a folder (all levels).
|
||||
_filesUnder(path) {
|
||||
return [...this._files.values()].filter((f) => f.folder === path || f.folder.startsWith(`${path}/`) || path === "");
|
||||
}
|
||||
|
||||
_renderView() {
|
||||
if (!this._root) return;
|
||||
const find = this._panel.querySelector(".lib-find");
|
||||
const counts = {};
|
||||
this._files.forEach((f) => (counts[this._kindOf(f)] = (counts[this._kindOf(f)] || 0) + 1));
|
||||
find.querySelector(".lib-find__kinds").innerHTML = Object.entries(KINDS)
|
||||
.map(([kind, { label, color }]) => `<button type="button" class="lib-chip" data-kind="${kind}" aria-pressed="${this._kindsOn.has(kind)}"><span style="color: ${color}">●</span> ${label} <small>${counts[kind] || 0}</small></button>`)
|
||||
.join("");
|
||||
find.querySelector('[data-find="shown"]').setAttribute("aria-pressed", this._shownOnly);
|
||||
const flat = this._mode === "list" || this._query;
|
||||
find.querySelectorAll("[data-mode]").forEach((button) => button.setAttribute("aria-pressed", (button.dataset.mode === "list") === Boolean(flat)));
|
||||
|
||||
const ul = document.createElement("ul");
|
||||
ul.className = "gpx-tree__points";
|
||||
file.points.forEach((point) => {
|
||||
const li = document.createElement("li");
|
||||
li.className = "gpx-tree__point";
|
||||
const name = document.createElement("button");
|
||||
name.type = "button";
|
||||
name.className = "gpx-tree__point-name";
|
||||
name.textContent = point.name;
|
||||
name.addEventListener("click", () => this._goToPoint(file.path, point));
|
||||
li.appendChild(name);
|
||||
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(file, point)));
|
||||
ul.appendChild(li);
|
||||
ul.className = "lib-list";
|
||||
if (flat) {
|
||||
this._crumb.hidden = true;
|
||||
if (this._query) {
|
||||
[...this._folders.values()]
|
||||
.filter((f) => f.path && f.name.toLowerCase().includes(this._query))
|
||||
.forEach((f) => ul.appendChild(this._folderRow(f, true)));
|
||||
}
|
||||
[...this._files.values()].filter((f) => this._matches(f)).forEach((f) => ul.appendChild(this._fileRow(f, true)));
|
||||
} else if (this._openTrack) {
|
||||
const track = this._files.get(this._openTrack);
|
||||
this._renderCrumb(track.folder, track.name, plural(track.points.length, "point"), () => (this._openTrack = null));
|
||||
track.points.forEach((point) => ul.appendChild(this._pointRow(track, point)));
|
||||
} else {
|
||||
const folder = this._folders.get(this._cwd);
|
||||
const subfolders = folder.children.filter((c) => c.type === "folder");
|
||||
const files = folder.children.filter((c) => c.type !== "folder" && this._matches(c));
|
||||
if (this._cwd) {
|
||||
const parent = this._cwd.includes("/") ? this._cwd.slice(0, this._cwd.lastIndexOf("/")) : "";
|
||||
this._renderCrumb(parent, folder.name, `${plural(subfolders.length, "folder")} · ${plural(files.length, "item")}`, () => (this._cwd = parent), parent);
|
||||
} else {
|
||||
this._crumb.hidden = true;
|
||||
}
|
||||
subfolders.forEach((f) => ul.appendChild(this._folderRow(f)));
|
||||
files.forEach((f) => ul.appendChild(this._fileRow(f)));
|
||||
}
|
||||
if (!ul.children.length) {
|
||||
ul.innerHTML = `<li class="gpx-tree__empty">${this._query ? "Nothing found" : "Nothing here yet"}</li>`;
|
||||
}
|
||||
this._treeContainer.innerHTML = "";
|
||||
this._treeContainer.appendChild(ul);
|
||||
this._footer.textContent = `${plural(this._folders.size - 1, "folder")} · ${plural(this._files.size, "item")} · ${this._visible.size} shown`;
|
||||
}
|
||||
|
||||
// ← up, the path to here and its name; `dropTo` (the parent) also takes a
|
||||
// dragged item, to move it a level up.
|
||||
_renderCrumb(path, name, meta, up, dropTo) {
|
||||
this._crumb.hidden = false;
|
||||
this._crumb.innerHTML = "";
|
||||
const back = Object.assign(document.createElement("button"), { type: "button", className: "lib-crumb__up", textContent: "←", title: "Up" });
|
||||
back.addEventListener("click", () => {
|
||||
up();
|
||||
this._renderView();
|
||||
});
|
||||
details.appendChild(ul);
|
||||
return details;
|
||||
if (dropTo !== undefined && isLoggedIn()) this._wireFolderDropTarget(back, dropTo);
|
||||
const where = Object.assign(document.createElement("span"), { className: "lib-crumb__path", textContent: path ? `${path.replaceAll("/", " › ")} › ` : "" });
|
||||
this._crumb.append(back, where, Object.assign(document.createElement("b"), { textContent: name }), Object.assign(document.createElement("small"), { textContent: meta }));
|
||||
}
|
||||
|
||||
_row({ icon, color, name, meta, aside, eye, onOpen, onEye, bold }) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "lib-row";
|
||||
li.innerHTML = `<span class="lib-row__icon" aria-hidden="true"></span><span class="lib-row__text"><span class="lib-row__name"></span><small class="lib-row__meta"></small></span><span class="lib-row__aside"></span>`;
|
||||
const iconEl = li.querySelector(".lib-row__icon");
|
||||
iconEl.textContent = icon;
|
||||
iconEl.style.color = color || "";
|
||||
li.querySelector(".lib-row__name").textContent = name;
|
||||
li.querySelector(".lib-row__name").classList.toggle("lib-row__name--folder", Boolean(bold));
|
||||
li.querySelector(".lib-row__meta").textContent = meta || "";
|
||||
li.querySelector(".lib-row__aside").textContent = aside || "";
|
||||
li.querySelector(".lib-row__text").addEventListener("click", onOpen);
|
||||
if (eye) {
|
||||
const button = Object.assign(document.createElement("button"), { type: "button", className: `lib-eye lib-eye--${eye}`, textContent: { all: "●", some: "◐", none: "○" }[eye] });
|
||||
button.title = eye === "none" ? "Show on the map" : "Hide from the map";
|
||||
button.setAttribute("aria-label", button.title);
|
||||
button.setAttribute("aria-pressed", eye !== "none");
|
||||
button.addEventListener("click", onEye);
|
||||
li.appendChild(button);
|
||||
}
|
||||
return li;
|
||||
}
|
||||
|
||||
_folderRow(folder, withPath = false) {
|
||||
const files = this._filesUnder(folder.path);
|
||||
const shown = files.filter((f) => this._visible.has(f.path)).length;
|
||||
const subfolders = folder.children.filter((c) => c.type === "folder").length;
|
||||
const items = folder.children.length - subfolders;
|
||||
const parent = folder.path.includes("/") ? folder.path.slice(0, folder.path.lastIndexOf("/")).replaceAll("/", " › ") : "";
|
||||
const li = this._row({
|
||||
icon: "▣",
|
||||
name: folder.name,
|
||||
bold: true,
|
||||
meta: [withPath && parent, subfolders && plural(subfolders, "folder"), plural(items, "item")].filter(Boolean).join(" · "),
|
||||
aside: "›",
|
||||
eye: files.length ? (shown === 0 ? "none" : shown === files.length ? "all" : "some") : null,
|
||||
onOpen: () => {
|
||||
this._cwd = folder.path;
|
||||
this._openTrack = null;
|
||||
this._query = "";
|
||||
this._mode = "folders";
|
||||
this._panel.querySelector(".lib-find__input").value = "";
|
||||
this._renderView();
|
||||
},
|
||||
onEye: async () => {
|
||||
const show = shown === 0;
|
||||
await Promise.all(files.map((f) => this._toggleFileOnly(f.path, show)));
|
||||
this._saveVisible();
|
||||
this._renderView();
|
||||
},
|
||||
});
|
||||
if (isLoggedIn()) {
|
||||
li.appendChild(this._menuButton("⋯", "Actions", [
|
||||
{ label: "Rename…", run: () => this._renameFolder(folder) },
|
||||
...this._exportEntries(folder.path, folder.name),
|
||||
{ label: "Delete…", run: () => this._deleteFolder(folder.path) },
|
||||
]));
|
||||
li.draggable = true;
|
||||
li.addEventListener("dragstart", (event) => {
|
||||
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
this._wireFolderDropTarget(li, folder.path);
|
||||
}
|
||||
return li;
|
||||
}
|
||||
|
||||
_fileRow(file, withPath = false) {
|
||||
const kind = this._kindOf(file);
|
||||
const visible = this._visible.has(file.path);
|
||||
const li = this._row({
|
||||
icon: KINDS[kind].glyph,
|
||||
color: file.color || KINDS[kind].color,
|
||||
name: file.name,
|
||||
meta: [withPath && (file.folder ? file.folder.replaceAll("/", " › ") : "Top level"), KINDS[kind].one, file.points && plural(file.points.length, "point")].filter(Boolean).join(" · "),
|
||||
aside: file.points ? "›" : "",
|
||||
eye: visible ? "all" : "none",
|
||||
// the name zooms to it, shown first if needed; a track's points open
|
||||
// from its ›
|
||||
onOpen: async (event) => {
|
||||
if (file.points && event.target.closest(".lib-row__aside, .lib-row__meta")) {
|
||||
this._openTrack = file.path;
|
||||
return this._renderView();
|
||||
}
|
||||
if (!this._visible.has(file.path)) await this._toggleFile(file.path, true);
|
||||
if (this._visible.has(file.path)) this._zoomTo(file.path);
|
||||
this._renderView();
|
||||
},
|
||||
onEye: async () => {
|
||||
await this._toggleFile(file.path, !visible);
|
||||
this._renderView();
|
||||
},
|
||||
});
|
||||
if (file.points) {
|
||||
li.querySelector(".lib-row__aside").addEventListener("click", () => {
|
||||
this._openTrack = file.path;
|
||||
this._renderView();
|
||||
});
|
||||
}
|
||||
li.draggable = true;
|
||||
li.addEventListener("dragstart", (event) => {
|
||||
event.dataTransfer.setData(MOVE_MIME, file.path);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
// Every action behind one ⋯ menu (as OsmAnd does), shown only once
|
||||
// logged in: they all require login (app.rb).
|
||||
if (isLoggedIn()) li.appendChild(this._fileMenu(file));
|
||||
return li;
|
||||
}
|
||||
|
||||
_pointRow(track, point) {
|
||||
const li = this._row({
|
||||
icon: "●",
|
||||
color: KINDS.waypoint.color,
|
||||
name: point.name,
|
||||
meta: "point",
|
||||
onOpen: () => this._goToPoint(track.path, point),
|
||||
});
|
||||
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(track, point)));
|
||||
return li;
|
||||
}
|
||||
|
||||
async _goToPoint(path, point) {
|
||||
@@ -347,95 +555,6 @@ export class GpxPanelControl {
|
||||
await this._reloadFile(target);
|
||||
}
|
||||
|
||||
_renderFolder(folder) {
|
||||
const details = document.createElement("details");
|
||||
details.open = true;
|
||||
|
||||
const summary = document.createElement("summary");
|
||||
const row = document.createElement("span");
|
||||
row.className = "gpx-tree__folder-row";
|
||||
const name = document.createElement("span");
|
||||
name.textContent = folder.name;
|
||||
row.appendChild(name);
|
||||
if (isLoggedIn()) {
|
||||
row.appendChild(
|
||||
this._menuButton("⋯", "Actions", [
|
||||
{ label: "Rename…", run: () => this._renameFolder(folder) },
|
||||
...this._exportEntries(folder.path, folder.name),
|
||||
{ label: "Delete…", run: () => this._deleteFolder(folder.path) },
|
||||
]),
|
||||
);
|
||||
// Dragged onto another folder (or the tree's blank space) moves it.
|
||||
summary.draggable = true;
|
||||
summary.addEventListener("dragstart", (event) => {
|
||||
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
}
|
||||
summary.appendChild(row);
|
||||
this._wireFolderDropTarget(summary, folder.path);
|
||||
|
||||
details.appendChild(summary);
|
||||
details.appendChild(this._renderChildren(folder.children));
|
||||
return details;
|
||||
}
|
||||
|
||||
_renderFile(file) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "gpx-tree__file";
|
||||
row.draggable = true;
|
||||
row.addEventListener("dragstart", (event) => {
|
||||
event.dataTransfer.setData(MOVE_MIME, file.path);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
|
||||
const label = document.createElement("label");
|
||||
const checkbox = document.createElement("input");
|
||||
checkbox.type = "checkbox";
|
||||
checkbox.checked = this._visible.has(file.path);
|
||||
checkbox.dataset.path = file.path;
|
||||
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
|
||||
const loggedIn = isLoggedIn();
|
||||
const name = document.createElement("span");
|
||||
name.className = "gpx-tree__file-name";
|
||||
name.textContent = file.name;
|
||||
label.appendChild(checkbox);
|
||||
(file.kinds || []).forEach((kind) => label.appendChild(this._kindIcon(kind)));
|
||||
label.appendChild(name);
|
||||
// The name zooms to it (showing it first if needed); the checkbox
|
||||
// alone shows/hides.
|
||||
name.addEventListener("click", async (event) => {
|
||||
event.preventDefault();
|
||||
if (!checkbox.checked) {
|
||||
checkbox.checked = true;
|
||||
await this._toggleFile(file.path, true, checkbox);
|
||||
}
|
||||
if (checkbox.checked) this._zoomTo(file.path);
|
||||
});
|
||||
row.appendChild(label);
|
||||
// Every action behind one ⋯ menu (as OsmAnd does), shown only once
|
||||
// logged in: they all require login (app.rb).
|
||||
if (loggedIn) row.appendChild(this._fileMenu(file));
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
_kindIcon(kind) {
|
||||
const icon = document.createElement("span");
|
||||
icon.className = "gpx-tree__kind-icon";
|
||||
if (kind === "waypoint") {
|
||||
icon.innerHTML = WAYPOINT_ICON;
|
||||
icon.title = "Has waypoints";
|
||||
} else if (kind === "route") {
|
||||
icon.innerHTML = ROUTE_ICON;
|
||||
icon.title = "Has a route";
|
||||
} else {
|
||||
icon.innerHTML = TRACK_ICON;
|
||||
icon.title = "Has a track";
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
|
||||
_fileMenu(file) {
|
||||
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
|
||||
// A folder's "Points (N)" node has no name or color of its own.
|
||||
@@ -585,9 +704,28 @@ export class GpxPanelControl {
|
||||
// that isn't shown yet — same as ticking its box in the tree by hand.
|
||||
async show(path) {
|
||||
if (this._visible.has(path)) return;
|
||||
const checkbox = [...this._treeContainer.querySelectorAll("input[data-path]")].find((input) => input.dataset.path === path);
|
||||
if (checkbox) checkbox.checked = true;
|
||||
await this._toggleFile(path, true, checkbox);
|
||||
await this._toggleFile(path, true);
|
||||
this._renderView();
|
||||
}
|
||||
|
||||
// For the driving grid's Points (driving.js): the tree as indexed by
|
||||
// _renderTree, whether a node is shown, and showing / hiding nodes.
|
||||
libraryTree() {
|
||||
return { folders: this._folders || new Map(), files: this._files || new Map(), filesUnder: (path) => this._filesUnder(path) };
|
||||
}
|
||||
|
||||
isShown(path) {
|
||||
return this._visible.has(path);
|
||||
}
|
||||
|
||||
async setShown(paths, visible) {
|
||||
await Promise.all(paths.map((path) => this._toggleFileOnly(path, visible)));
|
||||
this._saveVisible();
|
||||
this._renderView();
|
||||
}
|
||||
|
||||
zoomTo(path) {
|
||||
return this._zoomTo(path);
|
||||
}
|
||||
|
||||
// Search result picked: show its file, then open the matching point's
|
||||
@@ -762,7 +900,7 @@ export class GpxPanelControl {
|
||||
// clusterRadius/clusterMaxZoom are harmless when there's nothing dense
|
||||
// enough to cluster (a handful of waypoints just render individually).
|
||||
this._map.addSource(pointsId, { type: "geojson", data: points, cluster: true, clusterRadius: 50, clusterMaxZoom: 14 });
|
||||
const badgeColors = new Set(points.features.map((f) => f.properties.color));
|
||||
const badgeColors = new Set([...points.features.map((f) => f.properties.color), ...CLUSTER_COLORS]);
|
||||
await Promise.all([this._registerCategoryGlyphs(new Set(points.features.map((f) => f.properties.icon))), this._registerBadgeColors(badgeColors)]);
|
||||
if (!this._map.getSource(pointsId)) return true; // a style.load (basemap switch) tore it down while icons were loading
|
||||
|
||||
@@ -777,21 +915,21 @@ export class GpxPanelControl {
|
||||
}
|
||||
|
||||
// A single-hue, light->dark ramp keyed on point_count (magnitude, not
|
||||
// category) for the clustered circles; individual points below that use
|
||||
// category) for the cluster badges; individual points below that use
|
||||
// each waypoint's own category color (see Maptool::Gpx#waypoint_color),
|
||||
// falling back to the plain track color for waypoints with no category
|
||||
// (e.g. a hand-placed GNSS pin, not from a POI export).
|
||||
_addClusterLayers(pointsId, path) {
|
||||
this._map.addLayer({
|
||||
id: `${pointsId}-clusters`,
|
||||
type: "circle",
|
||||
type: "symbol",
|
||||
source: pointsId,
|
||||
filter: ["has", "point_count"],
|
||||
paint: {
|
||||
"circle-radius": ["step", ["get", "point_count"], 16, 25, 20, 100, 26],
|
||||
"circle-color": ["step", ["get", "point_count"], "#a8c8ea", 25, "#5b9bd5", 100, "#2e6da4"],
|
||||
"circle-stroke-color": "#fff",
|
||||
"circle-stroke-width": 1.5,
|
||||
layout: {
|
||||
"icon-image": ["step", ["get", "point_count"], badgeImageId(CLUSTER_COLORS[0]), 25, badgeImageId(CLUSTER_COLORS[1]), 100, badgeImageId(CLUSTER_COLORS[2])],
|
||||
"icon-size": ["step", ["get", "point_count"], 32 / POI_ICON_IMAGE_SIZE, 25, 40 / POI_ICON_IMAGE_SIZE, 100, 52 / POI_ICON_IMAGE_SIZE],
|
||||
"icon-allow-overlap": true,
|
||||
"icon-ignore-placement": true,
|
||||
},
|
||||
});
|
||||
this._map.addLayer({
|
||||
@@ -812,20 +950,20 @@ export class GpxPanelControl {
|
||||
// default center anchoring is simplest and also means the glyph layer
|
||||
// below needs no offset, just the same center anchor.
|
||||
// A point with no NPS symbol (a Google saved place, a bare GPX
|
||||
// waypoint) is a small dot instead, like a place on an NPS map — an
|
||||
// waypoint) is a small badge instead, about half the size — a full-size
|
||||
// empty badge read as a big red square.
|
||||
const single = ["!", ["has", "point_count"]];
|
||||
const hasSymbol = ["in", ["get", "icon"], ["literal", POI_ICON_KEYS]];
|
||||
this._map.addLayer({
|
||||
id: `${pointsId}-dot`,
|
||||
type: "circle",
|
||||
type: "symbol",
|
||||
source: pointsId,
|
||||
filter: ["all", single, ["!", hasSymbol]],
|
||||
paint: {
|
||||
"circle-radius": ["interpolate", ["linear"], ["zoom"], 6, 3.5, 14, 6],
|
||||
"circle-color": ["get", "color"],
|
||||
"circle-stroke-color": "#fff",
|
||||
"circle-stroke-width": 1.5,
|
||||
layout: {
|
||||
"icon-image": ["concat", BADGE_IMAGE_PREFIX, ["get", "color"]],
|
||||
"icon-size": ["interpolate", ["linear"], ["zoom"], 6, 8 / POI_ICON_IMAGE_SIZE, 14, 13 / POI_ICON_IMAGE_SIZE],
|
||||
"icon-allow-overlap": true,
|
||||
"icon-ignore-placement": true,
|
||||
},
|
||||
});
|
||||
this._map.addLayer({
|
||||
|
||||
+113
-69
@@ -17,19 +17,20 @@ import { LocateControl } from "/js/locate.js";
|
||||
import { SearchControl } from "/js/search.js";
|
||||
import { OfflineDataControl } from "/js/offline_data.js";
|
||||
import { RoutePanelControl } from "/js/route.js";
|
||||
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js";
|
||||
import { WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js";
|
||||
import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
|
||||
import { getPosition } from "/vendor/suncalc/suncalc.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, setupSidePanelModes } from "/js/panels.js";
|
||||
import { addRoutePoint, setupSidePanelModes } from "/js/panels.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { DebugControl } from "/js/debug.js";
|
||||
import { setupUpdate } from "/js/update.js";
|
||||
import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap, declutterWhenDriving } from "/js/map_themes.js";
|
||||
import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap } from "/js/map_themes.js";
|
||||
import { offerSharedFiles } from "/js/share_import.js";
|
||||
import HomeButton from "/vendor/npmap-home-button/home-button.esm.js";
|
||||
import OverviewMap from "/vendor/npmap-overview/overview.esm.js";
|
||||
import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { setupDriving } from "/js/driving.js";
|
||||
import { elevationAt } from "/js/dem.js";
|
||||
|
||||
const CENTER = [17.1077, 48.1486];
|
||||
const ZOOM = 13;
|
||||
@@ -104,45 +105,20 @@ function offlineStyle() {
|
||||
return style;
|
||||
}
|
||||
|
||||
// A sidebar icon that opens a full-height side panel (like the GPX one)
|
||||
// with the Online/Offline choice — modelled after OsmAnd's "Configure map"
|
||||
// panel, rather than a small dropdown flyout.
|
||||
// The Online/Offline choice: the first group of the On the map panel
|
||||
// (the Overlays one, overlays.js), no rail item or panel of its own.
|
||||
class LayerToggleControl {
|
||||
constructor(onSelect) {
|
||||
this._onSelect = onSelect;
|
||||
this._panel = document.querySelector(".onthemap-map");
|
||||
}
|
||||
|
||||
mount(sidebar) {
|
||||
this._container = document.createElement("div");
|
||||
this._container.className = "sidebar-item";
|
||||
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Base map" aria-label="Base map">${LAYERS_ICON}</button>`;
|
||||
this._icon = this._container.querySelector(".sidebar-icon");
|
||||
this._icon.addEventListener("click", () => this._togglePanel());
|
||||
|
||||
this._panel = document.getElementById("basemap-panel");
|
||||
this._panel
|
||||
.querySelector(".basemap-panel__close")
|
||||
.addEventListener("click", () => this._togglePanel(false));
|
||||
mount() {
|
||||
this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
this._onSelect(button.dataset.style);
|
||||
this._togglePanel(false);
|
||||
button.addEventListener("click", () => this._onSelect(button.dataset.style));
|
||||
});
|
||||
});
|
||||
|
||||
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
|
||||
|
||||
sidebar.appendChild(this._container);
|
||||
}
|
||||
|
||||
_togglePanel(force) {
|
||||
const open = force === undefined ? this._panel.hidden : force;
|
||||
this._panel.hidden = !open;
|
||||
this._icon.classList.toggle("active", open);
|
||||
if (open) notifySidePanelOpen(this._panel);
|
||||
}
|
||||
|
||||
|
||||
setActive(name) {
|
||||
this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => {
|
||||
button.classList.toggle("active", button.dataset.style === name);
|
||||
@@ -151,8 +127,8 @@ class LayerToggleControl {
|
||||
|
||||
// Called once it's known there's no offline map to switch to (see the
|
||||
// /api/offline-tiles check below) — an Online/Offline switch doesn't make
|
||||
// sense to show at all when Offline was never going to work. The panel
|
||||
// itself stays for its legend link.
|
||||
// sense to show at all when Offline was never going to work. The legend
|
||||
// link stays.
|
||||
hideSources() {
|
||||
this._panel.querySelector(".basemap-panel__sources").hidden = true;
|
||||
}
|
||||
@@ -309,19 +285,48 @@ map.addControl(new MeasureControl(), "top-right");
|
||||
// button that can only ever end in a 401 for a logged-out viewer, same
|
||||
// "hide the write-only affordance" story as GpxPanelControl's own
|
||||
// upload/new-folder buttons.
|
||||
if (isLoggedIn()) map.addControl(new NotesControl(), "top-right");
|
||||
let notesControl = null; // what's here's "Save a point" (below)
|
||||
if (isLoggedIn()) map.addControl((notesControl = new NotesControl()), "top-right");
|
||||
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-right");
|
||||
// ...as the artboard's three cards: zoom; the view (compass, north lock, 3D,
|
||||
// my position); the tools (measure, note, home). Each control keeps its own
|
||||
// container (their popovers hang off it), the card only groups them.
|
||||
{
|
||||
const corner = map.getContainer().querySelector(".maplibregl-ctrl-top-right");
|
||||
const [nav, ...rest] = corner.children;
|
||||
const card = (...controls) => {
|
||||
const div = document.createElement("div");
|
||||
div.className = "maplibregl-ctrl map-card";
|
||||
div.append(...controls);
|
||||
corner.appendChild(div);
|
||||
return div;
|
||||
};
|
||||
const view = card(...rest.slice(0, 3));
|
||||
view.prepend(nav.querySelector(".maplibregl-ctrl-compass"));
|
||||
card(...rest.slice(3));
|
||||
}
|
||||
|
||||
// The status bar: the map's center (click to copy), the point under the
|
||||
// mouse, the zoom level, the scale.
|
||||
// mouse, the zoom level.
|
||||
const cursorLabel = document.querySelector(".statusbar__cursor");
|
||||
map.on("mousemove", ({ lngLat }) => (cursorLabel.textContent = `Cursor ${formatCoords(lngLat.lat, lngLat.lng)}`));
|
||||
let terrainOffline = false; // set once /api/terrain-tiles answers (below)
|
||||
let elevationTimer = null;
|
||||
map.on("mousemove", ({ lngLat }) => {
|
||||
const at = `Cursor ${formatCoords(lngLat.lat, lngLat.lng)}`;
|
||||
cursorLabel.textContent = at;
|
||||
// the ground's height there, once the mouse rests a moment
|
||||
clearTimeout(elevationTimer);
|
||||
elevationTimer = setTimeout(async () => {
|
||||
const metres = await elevationAt(lngLat.lng, lngLat.lat, terrainOffline).catch(() => null);
|
||||
if (metres != null && cursorLabel.textContent === at) cursorLabel.textContent = `${at} · ${Math.round(metres)} m`;
|
||||
}, 150);
|
||||
});
|
||||
map.getCanvasContainer().addEventListener("mouseleave", () => (cursorLabel.textContent = ""));
|
||||
const zoomLabel = document.querySelector(".statusbar__zoom");
|
||||
const updateZoom = () => (zoomLabel.textContent = `Zoom ${map.getZoom().toFixed(1)}`);
|
||||
updateZoom();
|
||||
map.on("zoom", updateZoom);
|
||||
document.querySelector(".statusbar__scale").appendChild(new ScaleControl({ unit: "metric" }).onAdd(map));
|
||||
map.addControl(new ScaleControl({ unit: "metric" }), "bottom-left"); // over the map, as in the canvas' Desktop
|
||||
|
||||
// A small inset map showing where the current view sits in context — NPS's
|
||||
// own overview plugin (docs/nps-resources.adoc's "overview" entry, still on
|
||||
@@ -366,7 +371,7 @@ coordsLabel.addEventListener("click", async () => {
|
||||
// barely moves between two nearby spots, not worth recomputing constantly)
|
||||
// plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting
|
||||
// down even while the map sits still.
|
||||
const sunLabel = document.querySelector(".topbar__sun");
|
||||
const sunLabel = document.querySelector(".statusbar__sun");
|
||||
const sunChart = document.querySelector(".sun-chart");
|
||||
const updateSun = () => {
|
||||
const { lng, lat } = map.getCenter();
|
||||
@@ -417,6 +422,9 @@ const NIGHT_MODES = {
|
||||
off: ["☀", "Night mode: off"],
|
||||
};
|
||||
const nightButton = document.querySelector(".topbar__night");
|
||||
// On the map's Theme row: the same cycle as the topbar's button
|
||||
const themeButton = document.querySelector(".onthemap-theme");
|
||||
themeButton.addEventListener("click", () => nightButton.click());
|
||||
const nightMap = new NightMap(map);
|
||||
// The base style's texture patterns (grass, scrub, military hatch) and the
|
||||
// peak triangle are drawn at runtime rather than shipped in a sprite
|
||||
@@ -430,7 +438,6 @@ const addPatterns = () => {
|
||||
}
|
||||
};
|
||||
map.on("style.load", addPatterns);
|
||||
declutterWhenDriving(map);
|
||||
if (map.isStyleLoaded()) addPatterns();
|
||||
// Still the fallback for one asked for before that.
|
||||
map.on("styleimagemissing", ({ id }) => {
|
||||
@@ -456,6 +463,7 @@ const updateNight = () => {
|
||||
else delete document.documentElement.dataset.palette;
|
||||
nightMap.set(dark);
|
||||
[nightButton.textContent, nightButton.title] = NIGHT_MODES[nightMode] || NIGHT_MODES.auto;
|
||||
themeButton.textContent = `${{ auto: "Auto", on: "Night", dusk: "Dusk", off: "Day" }[nightMode] || "Auto"} ›`;
|
||||
};
|
||||
nightButton.addEventListener("click", () => {
|
||||
const modes = Object.keys(NIGHT_MODES);
|
||||
@@ -471,15 +479,14 @@ setInterval(updateNight, 60000);
|
||||
|
||||
const sidebar = document.getElementById("sidebar");
|
||||
|
||||
// The rail of the Design canvas' Desktop, labelled: what's on the map (the
|
||||
// map, overlays), the library and imports; the route; offline data; live
|
||||
// (GNSS, LiveTrack); Status pinned at the bottom. Folding Map, Overlays and
|
||||
// Live into one "On the map" panel is the canvas' next step, not done yet.
|
||||
// The rail of the Design canvas' Desktop, labelled: On the map (the map,
|
||||
// overlays), the library and imports; the route; offline data; live
|
||||
// (GNSS, LiveTrack); Status pinned at the bottom.
|
||||
const layerToggle = new LayerToggleControl(applyStyle);
|
||||
const profilePanel = new TrackProfilePanel(map);
|
||||
profilePanel.mount();
|
||||
|
||||
layerToggle.mount(sidebar);
|
||||
layerToggle.mount();
|
||||
layerToggle.setActive("online");
|
||||
const overlaysControl = new OverlaysControl(map);
|
||||
overlaysControl.mount(sidebar);
|
||||
@@ -498,7 +505,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
|
||||
const routePanel = new RoutePanelControl(map, gnssControl, profilePanel);
|
||||
routePanel.mount(sidebar);
|
||||
setupDriving(map, nightButton, routePanel);
|
||||
setupDriving(map, nightButton, routePanel, gpxPanel);
|
||||
new OfflineDataControl().mount(sidebar);
|
||||
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
|
||||
@@ -508,7 +515,7 @@ new LiveTrackPanelControl(map).mount(sidebar);
|
||||
if (isLoggedIn()) new DebugControl().mount(sidebar);
|
||||
if (isLoggedIn()) setupUpdate(document.querySelector(".topbar__update"), document.querySelector(".debug-panel__update-check"));
|
||||
// A short name under each icon (CSS ::after), the title stays the tooltip.
|
||||
const RAIL_LABELS = { "Base map": "Map", "Tracks & Points": "Library", "Import plugins": "Import", "Offline data": "Offline", LiveTrack: "Live", "Status / debug": "Status" };
|
||||
const RAIL_LABELS = { "Import plugins": "Import", "Offline data": "Offline", LiveTrack: "Live", "Status / debug": "Status" };
|
||||
sidebar.querySelectorAll(".sidebar-icon").forEach((icon) => (icon.dataset.label = RAIL_LABELS[icon.title] ?? icon.title));
|
||||
setupSidePanelModes();
|
||||
|
||||
@@ -535,6 +542,7 @@ ready.push(fetch("/api/offline-tiles")
|
||||
offlineStatus.hidden = false;
|
||||
offlineStatus.classList.toggle("topbar__offline-status--ready", available);
|
||||
offlineStatus.title = available ? "Offline map data ready" : "No offline map data on this server";
|
||||
offlineStatus.textContent = available ? "Offline ready" : "Online only";
|
||||
})
|
||||
.catch(() => {
|
||||
// Backend check failed; keep the online style and leave the switch as
|
||||
@@ -545,6 +553,7 @@ ready.push(fetch("/api/offline-tiles")
|
||||
ready.push(fetch("/api/terrain-tiles")
|
||||
.then((response) => response.json())
|
||||
.then(({ available }) => {
|
||||
terrainOffline = available;
|
||||
overlaysControl.setHillshadeOfflineAvailable(available);
|
||||
overlaysControl.setShadowOfflineAvailable(available);
|
||||
})
|
||||
@@ -572,36 +581,71 @@ Promise.allSettled(ready).then(() => {
|
||||
else map.once("idle", restore);
|
||||
});
|
||||
|
||||
// Alt+click, right click or a long press (touch browsers fire
|
||||
// contextmenu for it) anywhere shows every rendered feature at that point — base map
|
||||
// (OSM tags via OpenFreeMap/protomaps), GPX/FIT layers, radar, all of it —
|
||||
// with its raw properties, inspired by NPMap4's infoboxControl (a generic
|
||||
// "show me everything here" debug view, kept separate from the curated
|
||||
// popups those same features already have via their own layer-specific
|
||||
// click handlers, e.g. gpx.js's waypoint popups — both can fire on the same
|
||||
// click, which is fine, this is a power-user/debugging affordance, not
|
||||
// something replacing the normal popups). No dedicated UI for this
|
||||
// deliberately — a keyboard-modified click needs no button, state, or
|
||||
// cursor change of its own.
|
||||
const inspect = (event) => {
|
||||
// Right click, a long press (touch browsers fire contextmenu for it) or
|
||||
// Alt+click: what's here (the Design canvas' Desktop). The position on top,
|
||||
// a click copies it; Route here / Add to the trip / Save a point; every
|
||||
// rendered feature's raw properties folded under it (the debug view it
|
||||
// was). C copies the position under the mouse with no popup.
|
||||
const copyPosition = async ({ lng, lat }) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(`${lat.toFixed(6)}, ${lng.toFixed(6)}`);
|
||||
return true;
|
||||
} catch {
|
||||
return false; // clipboard API unavailable (an insecure context)
|
||||
}
|
||||
};
|
||||
const whatsHere = (event) => {
|
||||
const { lngLat } = event;
|
||||
const features = map.queryRenderedFeatures(event.point);
|
||||
if (features.length === 0) return;
|
||||
|
||||
const html = features
|
||||
const rows = features
|
||||
.map((feature) => {
|
||||
const rows = Object.entries(feature.properties)
|
||||
const cells = Object.entries(feature.properties)
|
||||
.map(([key, value]) => `<tr><th>${escapeHtml(key)}</th><td>${escapeHtml(String(value))}</td></tr>`)
|
||||
.join("");
|
||||
return `<div class="debug-popup__feature"><strong>${escapeHtml(feature.layer.id)}</strong><table>${rows || "<tr><td>(no properties)</td></tr>"}</table></div>`;
|
||||
return `<div class="debug-popup__feature"><strong>${escapeHtml(feature.layer.id)}</strong><table>${cells || "<tr><td>(no properties)</td></tr>"}</table></div>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
new Popup({ maxWidth: "320px", className: "debug-popup" }).setLngLat(event.lngLat).setHTML(html).addTo(map);
|
||||
const el = document.createElement("div");
|
||||
el.className = "here";
|
||||
el.innerHTML = `
|
||||
<button type="button" class="here__position" title="Copy">
|
||||
<span><b>${lngLat.lat.toFixed(5)}, ${lngLat.lng.toFixed(5)}</b><small>${formatCoords(lngLat.lat, lngLat.lng)}<span class="here__alt"></span></small></span>
|
||||
<em>Copy</em>
|
||||
</button>
|
||||
<div class="here__actions">
|
||||
<button type="button" data-do="route">Route here</button>
|
||||
<button type="button" data-do="trip">Add to the trip</button>
|
||||
${notesControl ? `<button type="button" data-do="note">Save a point</button>` : ""}
|
||||
</div>
|
||||
<details class="here__features"><summary>${features.length} feature${features.length === 1 ? "" : "s"} here</summary>${rows}</details>
|
||||
<div class="here__hint">C copies the position under the cursor</div>`;
|
||||
const popup = new Popup({ maxWidth: "320px", className: "debug-popup here-popup" }).setLngLat(lngLat).setDOMContent(el).addTo(map);
|
||||
elevationAt(lngLat.lng, lngLat.lat, terrainOffline)
|
||||
.then((metres) => metres != null && (el.querySelector(".here__alt").textContent = ` · ${Math.round(metres)} m`))
|
||||
.catch(() => {});
|
||||
el.querySelector(".here__position").addEventListener("click", async () => {
|
||||
if (await copyPosition(lngLat)) el.querySelector(".here__position em").textContent = "Copied ✓";
|
||||
});
|
||||
const at = [lngLat.lng, lngLat.lat];
|
||||
const actions = { route: () => addRoutePoint(at, null), trip: () => routePanel.addStop(at), note: () => notesControl.placeAt(lngLat) };
|
||||
el.querySelector(".here__actions").addEventListener("click", (e) => {
|
||||
const action = actions[e.target.dataset?.do];
|
||||
if (!action) return;
|
||||
popup.remove();
|
||||
action();
|
||||
});
|
||||
};
|
||||
map.on("click", (event) => event.originalEvent.altKey && inspect(event));
|
||||
map.on("click", (event) => event.originalEvent.altKey && whatsHere(event));
|
||||
map.on("contextmenu", (event) => {
|
||||
event.originalEvent.preventDefault();
|
||||
inspect(event);
|
||||
whatsHere(event);
|
||||
});
|
||||
let mouseAt = null;
|
||||
map.on("mousemove", ({ lngLat }) => (mouseAt = lngLat));
|
||||
map.getCanvasContainer().addEventListener("mouseleave", () => (mouseAt = null));
|
||||
document.addEventListener("keydown", async (e) => {
|
||||
if (e.key !== "c" || !mouseAt || e.ctrlKey || e.altKey || e.metaKey || e.target.closest("input, textarea, select, [contenteditable]")) return;
|
||||
if (await copyPosition(mouseAt)) cursorLabel.textContent = "Copied ✓";
|
||||
});
|
||||
|
||||
// Feature properties can come straight from an uploaded GPX/FIT file (an
|
||||
|
||||
+9
-15
@@ -11,28 +11,22 @@
|
||||
// The driving view (the map tilted to 3D, as following does): route
|
||||
// numbers and minor roads' / paths' names hidden, the main roads' names
|
||||
// left — what's needed at a glance. Back as soon as the map is flat.
|
||||
// A ["pitch"] in the layers' filters (MapLibre ≥ 6.21), so they go already
|
||||
// while tilting, and come back with every style without a listener.
|
||||
const DRIVE_HIDDEN_LABELS = /^(highway-shield|road_shield|highway-name-(minor|path))/;
|
||||
const DRIVE_PITCH = 30;
|
||||
|
||||
export function declutterWhenDriving(map) {
|
||||
let hidden = null;
|
||||
const apply = () => {
|
||||
const hide = map.getPitch() >= DRIVE_PITCH;
|
||||
if (hide === hidden) return;
|
||||
hidden = hide;
|
||||
for (const layer of map.getStyle().layers) {
|
||||
if (DRIVE_HIDDEN_LABELS.test(layer.id)) map.setLayoutProperty(layer.id, "visibility", hide ? "none" : "visible");
|
||||
function declutterWhenDriving(style) {
|
||||
for (const layer of style.layers) {
|
||||
if (!DRIVE_HIDDEN_LABELS.test(layer.id)) continue;
|
||||
const flat = ["<", ["pitch"], DRIVE_PITCH];
|
||||
layer.filter = layer.filter ? ["all", flat, layer.filter] : flat;
|
||||
}
|
||||
};
|
||||
map.on("pitchend", apply);
|
||||
map.on("style.load", () => {
|
||||
hidden = null;
|
||||
apply();
|
||||
});
|
||||
return style;
|
||||
}
|
||||
|
||||
export function patchOnlineStyle(style) {
|
||||
return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(parkTilesStyle(style))));
|
||||
return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(declutterWhenDriving(parkTilesStyle(style)))));
|
||||
}
|
||||
|
||||
// Road names and route numbers repeat every symbol-spacing *pixels*, so
|
||||
|
||||
@@ -342,6 +342,14 @@ export class NotesControl {
|
||||
return this._container;
|
||||
}
|
||||
|
||||
// "Save a point" from what's here (map.js): the note's form at that spot.
|
||||
placeAt(lngLat) {
|
||||
if (!this._active) this._setActive(true);
|
||||
this._form.close();
|
||||
this._removeMarker();
|
||||
this._onClick({ lngLat });
|
||||
}
|
||||
|
||||
_removeMarker() {
|
||||
this._marker?.remove();
|
||||
this._marker = null;
|
||||
|
||||
@@ -224,7 +224,7 @@ export class OverlaysControl {
|
||||
mount(sidebar) {
|
||||
this._container = document.createElement("div");
|
||||
this._container.className = "sidebar-item";
|
||||
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Overlays" aria-label="Overlays">${OVERLAYS_ICON}</button>`;
|
||||
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="On the map" aria-label="On the map">${OVERLAYS_ICON}</button>`;
|
||||
this._icon = this._container.querySelector(".sidebar-icon");
|
||||
this._icon.addEventListener("click", () => this._togglePanel());
|
||||
|
||||
|
||||
@@ -123,6 +123,20 @@ export function notifyRouteChanged(route) {
|
||||
document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route }));
|
||||
}
|
||||
|
||||
// The profile in use (route.js; its /api/vehicles entry): the dashboard's
|
||||
// and the driving grid's limits for it, the border card's "how it pays".
|
||||
const VEHICLE_EVENT = "vehicle-changed";
|
||||
export let currentVehicle = null;
|
||||
|
||||
export function notifyVehicle(vehicle) {
|
||||
currentVehicle = vehicle;
|
||||
document.dispatchEvent(new CustomEvent(VEHICLE_EVENT, { detail: vehicle }));
|
||||
}
|
||||
|
||||
export function onVehicle(callback) {
|
||||
document.addEventListener(VEHICLE_EVENT, (event) => callback(event.detail));
|
||||
}
|
||||
|
||||
// How far along the route the position is, while the dashboard follows it
|
||||
// (km, or null once it's off it / not navigating): the route panel draws
|
||||
// the driven part dimmed and the rest as the active route.
|
||||
|
||||
+43
-3
@@ -1,6 +1,9 @@
|
||||
import { PLUGIN_ICON } from "/js/icons.js";
|
||||
import { notifyGpxStoreChanged, notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
|
||||
|
||||
const CORRIDORS_KM = [1, 2, 5, 10, 20];
|
||||
const CORRIDOR_KEY = "maptool.pluginCorridorKm";
|
||||
|
||||
// A side panel (#plugins-panel) listing whatever import plugins are on disk (see
|
||||
// lib/maptool/plugins.rb for the contract) — each one just a "Run for
|
||||
// this area" button using the current map viewport as the bbox, so there's
|
||||
@@ -56,28 +59,65 @@ export class PluginsControl {
|
||||
plugins.forEach((plugin) => this._list.appendChild(this._renderItem(plugin)));
|
||||
}
|
||||
|
||||
// Per plugin: "Run for this area"; with "route" in its plugin.json also
|
||||
// "Along the trip's route" N km either side (the corridor remembered); with
|
||||
// "settings" (a login cookie) their fields — a value set shows as "set",
|
||||
// never sent back from the server.
|
||||
_renderItem(plugin) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "plugins-panel__item";
|
||||
li.innerHTML = `
|
||||
<span class="plugins-panel__label"></span>
|
||||
<button type="button" class="plugins-panel__run">Run for this area</button>
|
||||
${plugin.route ? `<span class="plugins-panel__route"><button type="button" class="plugins-panel__run plugins-panel__run--route">Along the trip's route</button>
|
||||
<select class="plugins-panel__corridor" aria-label="How far either side of the route">${CORRIDORS_KM.map((km) => `<option value="${km}">± ${km} km</option>`).join("")}</select></span>` : ""}
|
||||
<span class="plugins-panel__status"></span>
|
||||
${plugin.settings?.length ? `<details class="plugins-panel__settings"><summary>Settings</summary>${plugin.settings.map(() => `<label class="plugins-panel__setting"><span></span><input type="password" autocomplete="off" spellcheck="false"><small></small></label>`).join("")}
|
||||
<button type="button" class="plugins-panel__save">Save</button></details>` : ""}
|
||||
`;
|
||||
li.querySelector(".plugins-panel__label").textContent = plugin.label;
|
||||
|
||||
const button = li.querySelector(".plugins-panel__run");
|
||||
const status = li.querySelector(".plugins-panel__status");
|
||||
button.addEventListener("click", () => this._run(plugin, button, status));
|
||||
const routeButton = li.querySelector(".plugins-panel__run--route");
|
||||
if (routeButton) {
|
||||
const corridor = li.querySelector(".plugins-panel__corridor");
|
||||
corridor.value = localStorage.getItem(CORRIDOR_KEY) || "5";
|
||||
corridor.addEventListener("change", () => localStorage.setItem(CORRIDOR_KEY, corridor.value));
|
||||
routeButton.addEventListener("click", () => this._run(plugin, routeButton, status, { route: "1", corridor_km: corridor.value }));
|
||||
}
|
||||
const fields = [...li.querySelectorAll(".plugins-panel__setting")];
|
||||
fields.forEach((label, i) => {
|
||||
const field = plugin.settings[i];
|
||||
label.querySelector("span").textContent = field.label || field.key;
|
||||
label.querySelector("small").textContent = field.help || "";
|
||||
label.querySelector("input").placeholder = plugin.set?.includes(field.key) ? "set — paste to replace" : "not set";
|
||||
});
|
||||
li.querySelector(".plugins-panel__save")?.addEventListener("click", async () => {
|
||||
const values = Object.fromEntries(plugin.settings.map((f, i) => [f.key, fields[i].querySelector("input").value]).filter(([, v]) => v));
|
||||
try {
|
||||
const response = await fetch(`/api/plugins/${encodeURIComponent(plugin.name)}/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values) });
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || `save failed: ${response.status}`);
|
||||
plugin.set = data.set;
|
||||
fields.forEach((label, i) => { const input = label.querySelector("input"); input.value = ""; input.placeholder = data.set.includes(plugin.settings[i].key) ? "set — paste to replace" : "not set"; });
|
||||
status.textContent = "Settings saved";
|
||||
status.classList.remove("plugins-panel__status--error");
|
||||
} catch (err) {
|
||||
status.textContent = err.message;
|
||||
status.classList.add("plugins-panel__status--error");
|
||||
}
|
||||
});
|
||||
return li;
|
||||
}
|
||||
|
||||
async _run(plugin, button, status) {
|
||||
async _run(plugin, button, status, along = null) {
|
||||
button.disabled = true;
|
||||
status.textContent = "Running…";
|
||||
try {
|
||||
const bounds = this._map.getBounds();
|
||||
const body = new URLSearchParams({
|
||||
const body = new URLSearchParams(along || {
|
||||
south: bounds.getSouth(),
|
||||
west: bounds.getWest(),
|
||||
north: bounds.getNorth(),
|
||||
@@ -91,7 +131,7 @@ export class PluginsControl {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`);
|
||||
notifyGpxStoreChanged(data.path);
|
||||
status.textContent = "Done";
|
||||
status.textContent = `Done · ${data.count} found`;
|
||||
status.classList.remove("plugins-panel__status--error");
|
||||
} catch (err) {
|
||||
// Plugins::RunError's message (e.g. "plugin exited with status 1")
|
||||
|
||||
+672
-83
@@ -1,9 +1,11 @@
|
||||
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, onReroute, onRouteProgress } from "/js/panels.js";
|
||||
import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON, NPS_SYMBOLS } from "/js/icons.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress, notifyVehicle } from "/js/panels.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { SPEED_LIMITS, isHeavy, motorwayPayment } from "/js/speed_limits.js";
|
||||
import { wirePreview } from "/js/preview.js";
|
||||
import { elevationAt } from "/js/dem.js";
|
||||
import { getTimes } from "/vendor/suncalc/suncalc.js";
|
||||
|
||||
const ROUTE_URL = "/api/route";
|
||||
// Logged in, the panel edits this server's shared trip (lib/maptool/trip.rb)
|
||||
@@ -18,11 +20,39 @@ const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart
|
||||
const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel
|
||||
const VEHICLES_URL = "/api/vehicles";
|
||||
const VEHICLE_KEY = "maptool.routeVehicle";
|
||||
const PROFILE_ICONS = { car: "🚗", bicycle: "🚲", foot: "🥾" };
|
||||
// What the chip and the lists say about a profile, past its name.
|
||||
const profileMeta = (v) =>
|
||||
(v.type || "car") === "car"
|
||||
? [v.height && `${v.height} m`, v.weight && `${v.weight} t`].filter(Boolean).join(" · ")
|
||||
: [v.speed && `${v.speed} km/h`, v.sac && `up to T${v.sac}`].filter(Boolean).join(" · ");
|
||||
const AVOID_KEY = "maptool.routeAvoid";
|
||||
// Motorways paid by a time-based vignette rather than per section. Not
|
||||
// reliably tagged as toll in OSM, so every motorway km there counts.
|
||||
const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
|
||||
export const DAY_COLORS = ["#a21caf", "#1d6fdc", "#c2410c", "#2a9d8f", "#b45309"];
|
||||
const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const escapeText = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
const NOTES_URL = "/api/library/notes";
|
||||
|
||||
// A stop's type: the NPS pictogram shown on its marker and in the list (the
|
||||
// Design canvas' Plan). The key is the symbol's name, as a library point's icon.
|
||||
export const STOP_TYPES = {
|
||||
"point-of-interest": "Sight",
|
||||
"food-service": "Food",
|
||||
"coffee": "Break",
|
||||
"parking": "Parking",
|
||||
"gas-station": "Fuel",
|
||||
"vehicle-ferry": "Ferry",
|
||||
"campground": "Campsite",
|
||||
"campsite": "Wild night",
|
||||
"mechanic": "Service",
|
||||
"residential-building": "Home",
|
||||
};
|
||||
// What a stop keeps in the shared trip (the marker and editing state stay here).
|
||||
const stopData = ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid }) => ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid });
|
||||
// what a route can avoid (Routing.costing), the trip's and a day's own
|
||||
const AVOIDS = { tolls: "Tolls", highways: "Motorways", ferries: "Ferries", unpaved: "Unpaved" };
|
||||
const WALK_SOURCE = "route-walks";
|
||||
const MAX_DAY_DRIVING_S = 8 * 3600; // the Check: a longer day is a warning
|
||||
const MAX_WALK_M = 1500;
|
||||
const SOURCE = "route";
|
||||
const COLOR = "#1d6fdc";
|
||||
const SAVE_FOLDER = "Routes";
|
||||
@@ -70,16 +100,38 @@ export class RoutePanelControl {
|
||||
});
|
||||
onRoutePoint(({ lngLat, name }) => {
|
||||
this._setOpen(true);
|
||||
// with no + picked: on the leg it lengthens least, not past the end
|
||||
if (this._insertAt == null && this._points.length >= 2) {
|
||||
let best = Infinity;
|
||||
for (let i = 1; i < this._points.length; i++) {
|
||||
if (this._points[i].passed) continue;
|
||||
const [a, b] = [this._points[i - 1].lngLat, this._points[i].lngLat];
|
||||
const detour = distanceM(a, lngLat) + distanceM(lngLat, b) - distanceM(a, b);
|
||||
if (detour < best) [best, this._insertAt] = [detour, i];
|
||||
}
|
||||
const end = this._points.at(-1).lngLat;
|
||||
if (distanceM(end, lngLat) < best) this._insertAt = null; // further on: a new end
|
||||
}
|
||||
this._addPoint(lngLat, name);
|
||||
});
|
||||
onRouteEdit(({ key, feature }) => this._edit(key, feature));
|
||||
|
||||
map.on("click", (event) => {
|
||||
if (this._panel.hidden || event.originalEvent.altKey) return;
|
||||
if (this._parkFor) {
|
||||
// the stop's parking spot picked: the route goes there now
|
||||
this._parkFor.park = { lngLat: [event.lngLat.lng, event.lngLat.lat] };
|
||||
this._parkFor = null;
|
||||
this._changed();
|
||||
return;
|
||||
}
|
||||
this._addPoint([event.lngLat.lng, event.lngLat.lat]);
|
||||
});
|
||||
// setStyle() (base map switch) drops custom sources.
|
||||
map.on("style.load", () => this._draw());
|
||||
map.on("style.load", () => {
|
||||
this._draw();
|
||||
this._drawParking();
|
||||
});
|
||||
}
|
||||
|
||||
mount(sidebar) {
|
||||
@@ -103,13 +155,24 @@ export class RoutePanelControl {
|
||||
});
|
||||
this._panel.querySelector('[data-action="clear"]').addEventListener("click", () => this._clear());
|
||||
this._panel.querySelector('[data-action="position"]').addEventListener("click", () => this._addPosition());
|
||||
const icons = { position: POSITION_ICON, "saved-point": SAVED_POINT_ICON, reverse: REVERSE_ICON, clear: CLEAR_ICON, save: SAVE_ICON };
|
||||
this._panel.querySelector('[data-action="search"]').addEventListener("click", () => document.querySelector(".search-panel__input")?.focus());
|
||||
this._totals = this._panel.querySelector(".route-panel__totals");
|
||||
const icons = { reverse: REVERSE_ICON, clear: CLEAR_ICON };
|
||||
for (const [action, icon] of Object.entries(icons)) this._panel.querySelector(`[data-action="${action}"]`).insertAdjacentHTML("afterbegin", icon);
|
||||
this._setupSavedPoints();
|
||||
this._editingNote = this._panel.querySelector(".route-panel__editing");
|
||||
this._itinerary = { name: null, start: null, day_start: null, note: null, budget: null, fuel_price: null };
|
||||
this._tripInputs = [...this._panel.querySelectorAll(".route-panel__trip input, .route-panel__trip textarea")];
|
||||
this._tripInputs.forEach((input) => input.addEventListener("change", () => {
|
||||
this._itinerary[input.name] = input.value.trim() || null;
|
||||
this._itineraryChanged();
|
||||
}));
|
||||
this._saveButton.addEventListener("click", () => this._save());
|
||||
this._profileButton = this._panel.querySelector(".route-panel__profile");
|
||||
this._profileButton.addEventListener("click", () => this._profilePanel.show(this._profileProperties()));
|
||||
this._profileButton.addEventListener("click", () => {
|
||||
this._profileShown = this._profileProperties();
|
||||
this._profilePanel.show(this._profileShown);
|
||||
});
|
||||
this._reachStatus = this._panel.querySelector(".route-panel__reach-status");
|
||||
this._reachClear = this._panel.querySelector('[data-action="reach-clear"]');
|
||||
this._panel.querySelector('[data-action="reach"]').addEventListener("click", () => this._showReach());
|
||||
@@ -155,10 +218,11 @@ export class RoutePanelControl {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
points: this._points.map(({ lngLat, name, nav, passed }) => ({ lngLat, name, nav, passed })),
|
||||
points: this._points.map(stopData),
|
||||
vehicle: this._vehicleId,
|
||||
avoid: this._avoid,
|
||||
editing: this._editing,
|
||||
...this._itinerary,
|
||||
}),
|
||||
});
|
||||
const trip = await response.json().catch(() => ({}));
|
||||
@@ -175,11 +239,17 @@ export class RoutePanelControl {
|
||||
// vehicle, avoids, the library route being edited) when they came from
|
||||
// another screen.
|
||||
_applyTrip(trip, fromElsewhere) {
|
||||
const first = this._version < 0;
|
||||
this._version = trip.version;
|
||||
if (fromElsewhere) {
|
||||
const before = this._points.map(stopData);
|
||||
const beforeItinerary = { ...this._itinerary };
|
||||
this._points.forEach((p) => p.marker.remove());
|
||||
this._points = [];
|
||||
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed }));
|
||||
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed }));
|
||||
this._itinerary = { name: trip.name || null, start: trip.start || null, day_start: trip.day_start || null, note: trip.note || null, budget: trip.budget ?? null, fuel_price: trip.fuel_price ?? null };
|
||||
this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || ""));
|
||||
if (!first) this._showRemoteChange(before, beforeItinerary); // the first load isn't another screen's change
|
||||
this._editing = trip.editing;
|
||||
this._avoid = { ...trip.avoid };
|
||||
this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name]));
|
||||
@@ -208,11 +278,11 @@ export class RoutePanelControl {
|
||||
|
||||
// A named place (a saved point, a search result) is shown in navigation
|
||||
// by default; a plain map click only shapes the route.
|
||||
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false } = {}) {
|
||||
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note, type, day_note, park, avoid, cost, paid } = {}) {
|
||||
const element = document.createElement("div");
|
||||
element.className = "route-marker";
|
||||
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
|
||||
const point = { lngLat, name, nav, marker };
|
||||
const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined, type: type || undefined, day_note: day_note || undefined, park: park || undefined, avoid: avoid || undefined, cost: cost ?? undefined, paid: paid ?? undefined };
|
||||
this._setPassed(point, passed);
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
@@ -220,7 +290,9 @@ export class RoutePanelControl {
|
||||
point.name = null; // no longer that place
|
||||
this._changed();
|
||||
});
|
||||
this._points.push(point);
|
||||
if (!quiet && this._insertAt != null && this._insertAt < this._points.length) this._points.splice(this._insertAt, 0, point);
|
||||
else this._points.push(point);
|
||||
if (!quiet) this._insertAt = null;
|
||||
if (!quiet) this._changed();
|
||||
}
|
||||
|
||||
@@ -268,6 +340,19 @@ export class RoutePanelControl {
|
||||
leg: this._leg(i), passed: p.passed, behind: this._behind(i) }));
|
||||
}
|
||||
|
||||
// For the driving mode's Today (drive_menus.js): every stop with its plan
|
||||
// (planned arrive / leave in ms, the day), the leg to it, behind the car or
|
||||
// not; the trip's itinerary and the Check's items.
|
||||
plan() {
|
||||
const schedule = this._schedule();
|
||||
return {
|
||||
stops: this._points.map((p, i) => ({ ...stopData(p), ...schedule[i], index: i, leg: this._leg(i), behind: this._behind(i) })),
|
||||
days: (schedule.at(-1)?.day ?? 0) + 1,
|
||||
itinerary: { ...this._itinerary },
|
||||
check: this._check(schedule),
|
||||
};
|
||||
}
|
||||
|
||||
togglePassed(index) {
|
||||
const point = this._points[index];
|
||||
if (!point) return;
|
||||
@@ -326,6 +411,17 @@ export class RoutePanelControl {
|
||||
this._changed();
|
||||
}
|
||||
|
||||
// The profiles and the one in use, for the driving Menu's row; picking
|
||||
// one re-routes.
|
||||
profiles() {
|
||||
return { list: this._vehicles || [], current: this._vehicle || null };
|
||||
}
|
||||
|
||||
pickProfile(id) {
|
||||
this._selectVehicle?.(id);
|
||||
this._fetchRoute();
|
||||
}
|
||||
|
||||
// The start moved to where the car is (GNSS, else the browser's position).
|
||||
startHere() {
|
||||
const set = (lngLat) => {
|
||||
@@ -357,36 +453,189 @@ export class RoutePanelControl {
|
||||
this._fetchRoute();
|
||||
}
|
||||
|
||||
// Night / stay / note / the trip's name and start: no new route, the
|
||||
// shared trip saved (the server doesn't route again for these).
|
||||
_itineraryChanged() {
|
||||
this._renderPoints();
|
||||
if (this._shared) this._pushTrip();
|
||||
}
|
||||
|
||||
// The planned times: leaving at the trip's start, each leg's time, a stay
|
||||
// where set; a night stop ends the day, the next one leaves at "Days start"
|
||||
// (09:00). [{ arrive, leave, day }] in ms, null where unknown (no start, a
|
||||
// leg not routed yet).
|
||||
_schedule() {
|
||||
const last = this._points.length - 1;
|
||||
const [dh, dm] = (this._itinerary.day_start || "09:00").split(":").map(Number);
|
||||
let t = this._itinerary.start ? new Date(this._itinerary.start).getTime() : null;
|
||||
let day = 0;
|
||||
return this._points.map((p, i) => {
|
||||
if (i > 0 && t != null) {
|
||||
const leg = this._leg(i);
|
||||
t = leg?.s != null ? t + leg.s * 1000 : null;
|
||||
}
|
||||
const arrive = i > 0 ? t : null;
|
||||
let leave = null;
|
||||
if (t != null && i < last) {
|
||||
if (p.night) {
|
||||
const next = new Date(t);
|
||||
next.setDate(next.getDate() + 1);
|
||||
next.setHours(dh, dm, 0, 0);
|
||||
leave = next.getTime();
|
||||
} else leave = t + (p.stay || 0) * 60000;
|
||||
}
|
||||
const out = { arrive, leave, day };
|
||||
if (p.night && i < last) day++;
|
||||
t = leave;
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
// Another screen changed the trip: where (the first point added or moved,
|
||||
// else the first one changed) a popup says so, with Undo (the points and
|
||||
// the itinerary as they were, saved back). The map isn't moved.
|
||||
_showRemoteChange(before, beforeItinerary) {
|
||||
const key = (p) => p.lngLat.join();
|
||||
const now = this._points;
|
||||
const keys = new Set(before.map(key));
|
||||
const added = now.find((p) => !keys.has(key(p)));
|
||||
const changed = added || now.find((p, i) => JSON.stringify(stopData(p)) !== JSON.stringify(before[i]));
|
||||
const removed = now.length < before.length;
|
||||
if (!changed && !removed && JSON.stringify(beforeItinerary) === JSON.stringify(this._itinerary)) return;
|
||||
const at = (changed || now[0] || before[0])?.lngLat;
|
||||
if (!at) return;
|
||||
const what = added ? `added ${added.name || "a point"}` : removed ? "removed a point" : changed ? `changed ${changed.name || "a point"}` : "changed the trip";
|
||||
const el = document.createElement("div");
|
||||
el.className = "route-remote";
|
||||
el.innerHTML = `<span>Another screen ${escapeText(what)}</span> <button type="button">Undo</button>`;
|
||||
this._remotePopup?.remove();
|
||||
this._remotePopup = new Popup({ closeButton: false, closeOnClick: true, className: "route-remote-popup" }).setLngLat(at).setDOMContent(el).addTo(this._map);
|
||||
el.querySelector("button").addEventListener("click", () => {
|
||||
this._remotePopup.remove();
|
||||
this._points.forEach((p) => p.marker.remove());
|
||||
this._points = [];
|
||||
before.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed }));
|
||||
this._itinerary = { ...beforeItinerary };
|
||||
this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || ""));
|
||||
this._changed();
|
||||
});
|
||||
clearTimeout(this._remoteTimer);
|
||||
this._remoteTimer = setTimeout(() => this._remotePopup?.remove(), 15000);
|
||||
}
|
||||
|
||||
// The Desktop artboard's list: a grip to drag the point to another place,
|
||||
// its letter (the same on its marker), name and role, then the leg to the
|
||||
// next one as a dashed line between them.
|
||||
_renderPoints() {
|
||||
this._list.innerHTML = "";
|
||||
const last = this._points.length - 1;
|
||||
const schedule = this._schedule();
|
||||
const days = schedule.at(-1)?.day ?? 0;
|
||||
this._points.forEach((point, index) => {
|
||||
const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`;
|
||||
point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index);
|
||||
if (days > 0 && (index === 0 || this._points[index - 1].night)) this._dayHeader(schedule[index].day, index, schedule);
|
||||
const letter = String.fromCharCode(65 + (index % 26));
|
||||
const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`;
|
||||
const icon = NPS_SYMBOLS[point.type];
|
||||
if (icon) point.marker.getElement().innerHTML = icon;
|
||||
else point.marker.getElement().textContent = letter;
|
||||
const leg = this._leg(index);
|
||||
if (index > 0) {
|
||||
// + inserts the next point added (map click, search, saved point, my position) here
|
||||
const row = Object.assign(document.createElement("li"), { className: "route-panel__leg" });
|
||||
const inserting = this._insertAt === index;
|
||||
row.append(
|
||||
Object.assign(document.createElement("span"), {
|
||||
textContent: inserting ? "Click the map, search or pick a saved point" : leg ? `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}` : "",
|
||||
}),
|
||||
this._pointButton(inserting ? "×" : "+", inserting ? "Cancel" : "Insert a stop here", true, () => {
|
||||
this._insertAt = inserting ? null : index;
|
||||
this._renderPoints();
|
||||
}),
|
||||
);
|
||||
row.classList.toggle("route-panel__leg--insert", inserting);
|
||||
this._list.appendChild(row);
|
||||
}
|
||||
const li = document.createElement("li");
|
||||
li.className = "route-panel__stop";
|
||||
li.classList.toggle("route-panel__passed", !!point.passed || this._behind(index));
|
||||
const grip = Object.assign(document.createElement("span"), { className: "route-panel__grip", textContent: "⋮⋮", title: "Drag to reorder" });
|
||||
li.draggable = true;
|
||||
li.addEventListener("dragstart", (event) => {
|
||||
this._dragging = point;
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
li.classList.add("route-panel__dragging");
|
||||
});
|
||||
li.addEventListener("dragend", () => li.classList.remove("route-panel__dragging"));
|
||||
li.addEventListener("dragover", (event) => event.preventDefault());
|
||||
li.addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
const from = this._points.indexOf(this._dragging);
|
||||
this._dragging = null;
|
||||
if (from < 0 || from === index) return;
|
||||
this._points.splice(index, 0, ...this._points.splice(from, 1));
|
||||
this._changed();
|
||||
});
|
||||
const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter, title: STOP_TYPES[point.type] || "" });
|
||||
if (icon) badge.innerHTML = icon;
|
||||
badge.classList.toggle("route-panel__badge--end", index === last && last > 0);
|
||||
const text = document.createElement("span");
|
||||
text.className = "route-panel__point";
|
||||
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
|
||||
const leg = this._leg(index);
|
||||
if (leg) text.append(Object.assign(document.createElement("small"), { className: "route-panel__leg", textContent: `+${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}` }));
|
||||
li.append(
|
||||
text,
|
||||
this._navButton(point, label),
|
||||
this._pointButton("↑", "Move up", index > 0, () => this._move(point, -1)),
|
||||
this._pointButton("↓", "Move down", index < this._points.length - 1, () => this._move(point, 1)),
|
||||
this._pointButton("×", "Remove", true, () => this._removePoint(point)),
|
||||
text.append(
|
||||
Object.assign(document.createElement("span"), { className: "route-panel__name", textContent: point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}` }),
|
||||
Object.assign(document.createElement("small"), { className: "route-panel__role", textContent: [point.night && index < last ? "☾ night" : role, point.stay && !point.night ? `stay ${formatDuration(point.stay * 60)}` : ""].filter(Boolean).join(" · ") }),
|
||||
);
|
||||
const { arrive, leave } = schedule[index];
|
||||
const time = Object.assign(document.createElement("span"), { className: "route-panel__time",
|
||||
textContent: [arrive, point.night ? null : leave].filter((t) => t != null).map(clock).join("–") });
|
||||
if (point.park) {
|
||||
text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__park",
|
||||
textContent: `${point.park.name || "Parking"} · ${walk(point)} walk` }));
|
||||
}
|
||||
if (point.note) text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__note", textContent: point.note }));
|
||||
const night = this._pointButton("☾", "Night stop: the day ends here", index > 0 && index < last, () => {
|
||||
point.night = point.night ? undefined : true;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
night.classList.toggle("route-panel__on", !!point.night);
|
||||
const edit = this._pointButton("✎", "Type, stay and note", true, () => {
|
||||
point.editingNote = !point.editingNote;
|
||||
this._renderPoints();
|
||||
});
|
||||
li.append(grip, badge, text, time, night, edit, this._navButton(point, role), this._pointButton("×", "Remove", true, () => this._removePoint(point)));
|
||||
// Hover/hold previews the point; a click on its name commits.
|
||||
wirePreview(this._map, text, () => ({ lngLat: point.lngLat }));
|
||||
text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) }));
|
||||
this._list.appendChild(li);
|
||||
if (point.editingNote) this._list.appendChild(this._noteEditor(point));
|
||||
});
|
||||
this._drawParking();
|
||||
this._renderCheck(schedule);
|
||||
this._renderCosts();
|
||||
this._stopListeners?.forEach((callback) => callback());
|
||||
this._editingNote.hidden = !this._editing;
|
||||
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
|
||||
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
|
||||
}
|
||||
|
||||
// The totals card: distance, time, climb (once the terrain's sampled),
|
||||
// arrival if leaving now.
|
||||
_renderTotals(route) {
|
||||
this._totals.hidden = !route;
|
||||
if (!route) return;
|
||||
const { distance_km: km, time_s: seconds } = route.properties;
|
||||
const arrive = new Date(Date.now() + seconds * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const cells = [
|
||||
[`${km.toFixed(km < 10 ? 1 : 0)} km`, "distance"],
|
||||
[formatDuration(seconds), "time"],
|
||||
[route.elevation ? `${Math.round(route.elevation.gain)} m` : "…", "climb"],
|
||||
[arrive, "arrive"],
|
||||
];
|
||||
this._totals.innerHTML = cells.map(([value, key]) => `<span><b>${value}</b><small>${key}</small></span>`).join("");
|
||||
if (route.elevation) {
|
||||
this._totals.insertAdjacentHTML("beforeend", `<span class="route-panel__totals-more">↓ ${Math.round(route.elevation.loss)} m · steepest ${route.elevation.maxGrade.toFixed(0)} %</span>`);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggles whether the point is saved into the route as a navigation
|
||||
// point (a course point on a Garmin); an unnamed one asks for a name.
|
||||
_navButton(point, label) {
|
||||
@@ -406,6 +655,231 @@ export class RoutePanelControl {
|
||||
return button;
|
||||
}
|
||||
|
||||
// Is the trip ready: [{ level: "bad" | "warn" | "info", what, index }]
|
||||
// (index: the stop it's about, or null), the worst first, then by day.
|
||||
_check(schedule) {
|
||||
const out = [];
|
||||
const last = this._points.length - 1;
|
||||
if (last < 1) return out;
|
||||
const days = (schedule.at(-1)?.day ?? 0) + 1;
|
||||
const dayName = (d) => (days > 1 ? `Day ${d + 1}: ` : "");
|
||||
if (!this._itinerary.start) out.push({ level: "info", what: "No leave time: the planned times are unknown", index: null, day: 0 });
|
||||
// driving per day
|
||||
const driving = new Array(days).fill(0);
|
||||
this._points.forEach((_, i) => { if (i > 0) driving[schedule[i - 1].day] += this._leg(i)?.s || 0; });
|
||||
driving.forEach((s, d) => { if (s > MAX_DAY_DRIVING_S) out.push({ level: "warn", what: `${dayName(d)}${formatDuration(s)} driving`, index: null, day: d }); });
|
||||
this._points.forEach((p, i) => {
|
||||
const name = p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`;
|
||||
const { arrive, day } = schedule[i];
|
||||
// a night spot reached after dark
|
||||
if ((p.night || i === last) && arrive != null && !p.passed) {
|
||||
const sunset = getTimes(new Date(arrive), p.lngLat[1], p.lngLat[0]).sunset;
|
||||
if (!Number.isNaN(sunset?.getTime()) && arrive > sunset.getTime()) {
|
||||
out.push({ level: "warn", what: `${dayName(day)}${name}: arriving ${clock(arrive)}, after sunset (${clock(sunset.getTime())})`, index: i, day });
|
||||
}
|
||||
}
|
||||
if (p.park && distanceM(p.park.lngLat, p.lngLat) * 1.25 > MAX_WALK_M) out.push({ level: "info", what: `${name}: ${walk(p)} from the parking`, index: i, day });
|
||||
});
|
||||
// motorways in a country the profile has no vignette / toll unit for
|
||||
for (const { code, motorway_km: motorway } of this._route?.properties.countries || []) {
|
||||
const pay = motorwayPayment(code, this._vehicle);
|
||||
if (pay.how && motorway > 0 && !pay.has) {
|
||||
out.push({ level: "warn", what: `${code}: ${motorway.toFixed(0)} km of motorway, ${pay.until ? `the ${pay.how} ended ${pay.until}` : `no ${pay.how} in the profile`}`, index: null, day: 0 });
|
||||
}
|
||||
}
|
||||
const rank = { bad: 0, warn: 1, info: 2 };
|
||||
return out.sort((a, b) => rank[a.level] - rank[b.level] || a.day - b.day);
|
||||
}
|
||||
|
||||
_renderCheck(schedule) {
|
||||
const fold = this._panel.querySelector(".route-panel__check");
|
||||
const items = this._check(schedule);
|
||||
fold.hidden = this._points.length < 2;
|
||||
const count = (level) => items.filter((x) => x.level === level).length;
|
||||
fold.querySelector(".route-panel__fold-meta").textContent =
|
||||
items.length ? [[count("bad"), "✗"], [count("warn"), "!"], [count("info"), "i"]].filter(([n]) => n).map(([n, m]) => `${n} ${m}`).join(" · ") : "ready ✓";
|
||||
fold.classList.toggle("route-panel__check--warn", count("bad") + count("warn") > 0);
|
||||
fold.querySelector("ul").replaceChildren(...items.map(({ level, what, index }) => {
|
||||
const li = Object.assign(document.createElement("li"), { className: `route-panel__check-${level}` });
|
||||
li.append(Object.assign(document.createElement("span"), { textContent: what }));
|
||||
if (index != null) {
|
||||
li.appendChild(this._pointButton("⌖", "Show it", true, () => this._map.easeTo({ center: this._points[index].lngLat, zoom: Math.max(this._map.getZoom(), 13) })));
|
||||
}
|
||||
return li;
|
||||
}));
|
||||
}
|
||||
|
||||
// Planned (the fuel from the route's km × the profile's consumption × the
|
||||
// trip's fuel price, each stop's costs) vs paid, against the budget.
|
||||
_renderCosts() {
|
||||
const fold = this._panel.querySelector(".route-panel__costs");
|
||||
fold.hidden = this._points.length < 2;
|
||||
const euro = (n) => `${n.toFixed(n < 100 ? 2 : 0)} €`;
|
||||
const rows = [];
|
||||
const km = this._route?.properties.distance_km;
|
||||
const uses = this._vehicle?.consumption;
|
||||
const price = Number(this._itinerary.fuel_price) || 0;
|
||||
let planned = 0;
|
||||
if (km && uses && price) {
|
||||
const fuel = (km * uses * price) / 100;
|
||||
planned += fuel;
|
||||
rows.push(["Fuel", `${km.toFixed(0)} km × ${uses} /100 km × ${price} €`, `≈ ${euro(fuel)}`]);
|
||||
} else if (km) {
|
||||
rows.push(["Fuel", uses ? "set the fuel price above" : "set the consumption in the profile", "–"]);
|
||||
}
|
||||
let paid = 0;
|
||||
this._points.forEach((p, i) => {
|
||||
if (p.cost == null && p.paid == null) return;
|
||||
planned += p.cost || 0;
|
||||
paid += p.paid || 0;
|
||||
rows.push([p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`, p.paid != null ? `paid ${euro(p.paid)}` : "planned", p.cost != null ? euro(p.cost) : "–"]);
|
||||
});
|
||||
const budget = Number(this._itinerary.budget) || 0;
|
||||
fold.querySelector(".route-panel__fold-meta").textContent = [planned && `≈ ${euro(planned)} planned`, paid && `${euro(paid)} paid`, budget && `${euro(budget - Math.max(planned, paid))} left`].filter(Boolean).join(" · ");
|
||||
fold.querySelector("ul").replaceChildren(...rows.map(([what, how, amount]) => {
|
||||
const li = document.createElement("li");
|
||||
li.append(...[what, how, amount].map((textContent) => Object.assign(document.createElement("span"), { textContent })));
|
||||
return li;
|
||||
}));
|
||||
}
|
||||
|
||||
// A day's header (into the list): its date (from when it leaves), km and
|
||||
// driving time, ✎ for the day's note, the note under it.
|
||||
_dayHeader(day, from, schedule) {
|
||||
let km = 0;
|
||||
let s = 0;
|
||||
for (let i = from + 1; i < this._points.length; i++) {
|
||||
const leg = this._leg(i);
|
||||
km += leg?.km || 0;
|
||||
s += leg?.s || 0;
|
||||
if (this._points[i].night) break;
|
||||
}
|
||||
const leaves = schedule[from].leave;
|
||||
const date = leaves != null ? new Date(leaves).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }) : `Day ${day + 1}`;
|
||||
const li = document.createElement("li");
|
||||
li.className = "route-panel__day";
|
||||
li.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
|
||||
li.innerHTML = `<b></b><span>${km ? `${km.toFixed(0)} km · ${formatDuration(s)}` : ""}${leaves != null ? ` · leave ${clock(leaves)}` : ""}</span>`;
|
||||
li.querySelector("b").textContent = date;
|
||||
// the day's note and avoids live on its first point (the one after the night spot)
|
||||
const point = this._points[from];
|
||||
if (point.avoid) {
|
||||
const avoided = Object.keys(AVOIDS).filter((k) => point.avoid[k]).map((k) => AVOIDS[k].toLowerCase());
|
||||
li.querySelector("span").append(` · ${avoided.length ? `avoids ${avoided.join(", ")}` : "avoids nothing"}`);
|
||||
}
|
||||
li.appendChild(this._pointButton("✎", "The day's note", true, () => {
|
||||
point.editingDay = !point.editingDay;
|
||||
this._renderPoints();
|
||||
}));
|
||||
this._list.appendChild(li);
|
||||
if (point.editingDay) {
|
||||
const editor = Object.assign(document.createElement("li"), { className: "route-panel__note-editor route-panel__day-note" });
|
||||
editor.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
|
||||
const text = Object.assign(document.createElement("textarea"), { rows: 2, maxLength: 500, placeholder: "The day's note", value: point.day_note || "" });
|
||||
text.addEventListener("change", () => {
|
||||
point.day_note = text.value.trim() || undefined;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
// the day's own avoids (routed apart by the server), else the trip's
|
||||
const avoid = document.createElement("span");
|
||||
avoid.className = "route-panel__day-avoid";
|
||||
const own = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!point.avoid });
|
||||
const boxes = Object.entries(AVOIDS).map(([key, label]) => {
|
||||
const box = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!(point.avoid || this._avoid)[key], disabled: !point.avoid });
|
||||
box.addEventListener("change", () => {
|
||||
point.avoid = { ...point.avoid, [key]: box.checked };
|
||||
this._changed();
|
||||
});
|
||||
const wrap = document.createElement("label");
|
||||
wrap.append(box, ` ${label}`);
|
||||
return wrap;
|
||||
});
|
||||
own.addEventListener("change", () => {
|
||||
point.avoid = own.checked ? Object.fromEntries(Object.keys(AVOIDS).map((k) => [k, !!this._avoid[k]])) : undefined;
|
||||
this._changed();
|
||||
});
|
||||
const ownLabel = document.createElement("label");
|
||||
ownLabel.append(own, " This day avoids:");
|
||||
avoid.append(ownLabel, ...boxes);
|
||||
editor.append(text, avoid);
|
||||
this._list.appendChild(editor);
|
||||
} else if (point.day_note) {
|
||||
const note = Object.assign(document.createElement("li"), { className: "route-panel__note route-panel__day-note", textContent: point.day_note });
|
||||
note.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
|
||||
this._list.appendChild(note);
|
||||
}
|
||||
}
|
||||
|
||||
// A stop's type, stay (minutes) and note, under it.
|
||||
_noteEditor(point) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "route-panel__note-editor";
|
||||
li.innerHTML = `<span><label>Type <select><option value="">—</option></select></label> <label>Stay <input type="number" min="0" step="15" placeholder="0"> min</label></span>
|
||||
<span class="route-panel__money"><label>Costs <input type="number" name="cost" min="0" step="0.5" placeholder="–"> €</label> <label>paid <input type="number" name="paid" min="0" step="0.5" placeholder="–"> €</label></span>
|
||||
<span class="route-panel__park-edit">Parking <button type="button" data-park="set"></button> <button type="button" data-park="clear" hidden>No parking</button></span>
|
||||
<textarea rows="2" maxlength="500" placeholder="Note"></textarea>`;
|
||||
li.querySelectorAll(".route-panel__money input").forEach((input) => {
|
||||
input.value = point[input.name] ?? "";
|
||||
input.addEventListener("change", () => {
|
||||
const value = Number(input.value);
|
||||
point[input.name] = input.value.trim() !== "" && value >= 0 ? Math.round(value * 100) / 100 : undefined;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
});
|
||||
const setPark = li.querySelector('[data-park="set"]');
|
||||
const clearPark = li.querySelector('[data-park="clear"]');
|
||||
setPark.textContent = this._parkFor === point ? "Click the map…" : point.park ? "Move: click the map" : "Set: click the map";
|
||||
clearPark.hidden = !point.park;
|
||||
setPark.addEventListener("click", () => {
|
||||
this._parkFor = this._parkFor === point ? null : point;
|
||||
this._renderPoints();
|
||||
});
|
||||
clearPark.addEventListener("click", () => {
|
||||
point.park = undefined;
|
||||
this._changed();
|
||||
});
|
||||
const [type, stay, note] = [li.querySelector("select"), li.querySelector("input"), li.querySelector("textarea")];
|
||||
type.append(...Object.entries(STOP_TYPES).map(([value, label]) => new Option(label, value)));
|
||||
type.value = point.type || "";
|
||||
type.addEventListener("change", () => {
|
||||
point.type = type.value || undefined;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
stay.value = point.stay || "";
|
||||
note.value = point.note || "";
|
||||
stay.addEventListener("change", () => {
|
||||
point.stay = Math.max(0, Math.round(Number(stay.value) || 0)) || undefined;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
note.addEventListener("change", () => {
|
||||
point.note = note.value.trim() || undefined;
|
||||
this._itineraryChanged();
|
||||
});
|
||||
return li;
|
||||
}
|
||||
|
||||
// The stops' parking spots: a P marker each (drag it to move), a dashed
|
||||
// line to the place — the walk.
|
||||
_drawParking() {
|
||||
this._parkMarkers?.forEach((m) => m.remove());
|
||||
const parked = this._points.filter((p) => p.park);
|
||||
this._parkMarkers = parked.map((point) => {
|
||||
const element = Object.assign(document.createElement("div"), { className: "route-park", textContent: "P", title: point.park.name || "Parking" });
|
||||
const marker = new Marker({ element, draggable: true }).setLngLat(point.park.lngLat).addTo(this._map);
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
point.park = { lngLat: [lng, lat] };
|
||||
this._changed();
|
||||
});
|
||||
return marker;
|
||||
});
|
||||
if (!this._map.isStyleLoaded() && !this._map.getSource(WALK_SOURCE)) return;
|
||||
const data = { type: "FeatureCollection", features: parked.map((p) => ({ type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [p.park.lngLat, p.lngLat] } })) };
|
||||
if (this._map.getSource(WALK_SOURCE)) return this._map.getSource(WALK_SOURCE).setData(data);
|
||||
this._map.addSource(WALK_SOURCE, { type: "geojson", data });
|
||||
this._map.addLayer({ id: WALK_SOURCE, type: "line", source: WALK_SOURCE, paint: { "line-color": "#1d4ed8", "line-width": 2.5, "line-dasharray": [1, 1.5] } });
|
||||
}
|
||||
|
||||
_pointButton(text, title, enabled, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
@@ -436,7 +910,7 @@ export class RoutePanelControl {
|
||||
const response = await fetch(ROUTE_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ locations: this._active().map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
|
||||
body: JSON.stringify({ locations: this._active().map((p) => p.park?.lngLat || p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
|
||||
});
|
||||
data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) error = data.error || `routing failed (${response.status})`;
|
||||
@@ -457,13 +931,14 @@ export class RoutePanelControl {
|
||||
this._directions.hidden = !route;
|
||||
this._profileButton.hidden = true;
|
||||
this._showCountries(route?.properties.countries);
|
||||
if (!route) {
|
||||
this._renderTotals(route);
|
||||
this._summary.textContent = message;
|
||||
return;
|
||||
}
|
||||
if (this._profileShown && this._profilePanel.shown === this._profileShown) this._profilePanel.hide();
|
||||
this._profileShown = null;
|
||||
if (!route) return;
|
||||
|
||||
const { distance_km: km, time_s: seconds, maneuvers } = route.properties;
|
||||
this._summary.textContent = `${km.toFixed(1)} km · ${formatDuration(seconds)}`;
|
||||
const { maneuvers } = route.properties;
|
||||
this._directions.querySelector(".route-panel__fold-meta").textContent = `${maneuvers.length} steps`;
|
||||
const list = this._directions.querySelector("ol");
|
||||
list.innerHTML = "";
|
||||
maneuvers.forEach(({ text, km: length }) => {
|
||||
@@ -481,8 +956,13 @@ export class RoutePanelControl {
|
||||
if (this._route !== route || !profile) return;
|
||||
|
||||
route.elevation = profile;
|
||||
this._summary.textContent += ` · ↑ ${Math.round(profile.gain)} m ↓ ${Math.round(profile.loss)} m · max ${profile.maxGrade.toFixed(0)} %`;
|
||||
this._renderTotals(route);
|
||||
this._profileButton.hidden = false;
|
||||
// the route's profile docked under the map while planning (not driving)
|
||||
if (!document.documentElement.classList.contains("driving")) {
|
||||
this._profileShown = this._profileProperties();
|
||||
this._profilePanel.show(this._profileShown);
|
||||
}
|
||||
}
|
||||
|
||||
// What TrackProfilePanel (and a library track) reads.
|
||||
@@ -553,6 +1033,15 @@ export class RoutePanelControl {
|
||||
return;
|
||||
}
|
||||
this._map.addSource(SOURCE, { type: "geojson", data, lineMetrics: true }); // line-progress for _showProgress
|
||||
// the part behind while navigated: thin and dashed, under the line, which goes clear there (_showProgress)
|
||||
this._map.addLayer({
|
||||
id: `${SOURCE}-behind`,
|
||||
type: "line",
|
||||
source: SOURCE,
|
||||
filter: ["==", ["geometry-type"], "LineString"],
|
||||
layout: { "line-join": "round", visibility: "none" },
|
||||
paint: { "line-color": getComputedStyle(document.documentElement).getPropertyValue("--ui-muted").trim() || "#6b6b66", "line-width": 2.5, "line-dasharray": [2, 2] },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: `${SOURCE}-casing`,
|
||||
type: "line",
|
||||
@@ -577,21 +1066,25 @@ export class RoutePanelControl {
|
||||
});
|
||||
}
|
||||
|
||||
// Navigated (km along the route, docs/design.adoc): the driven part
|
||||
// dimmed, the rest magenta (--route-active); null: the planned blue.
|
||||
// Navigated (km along the route, docs/design.adoc): the part behind thin
|
||||
// and dashed, the rest magenta (--route-active); null: the planned blue.
|
||||
_showProgress(km) {
|
||||
if (!this._map.getLayer(`${SOURCE}-line`)) return;
|
||||
const total = this._route?.properties.distance_km;
|
||||
if (km == null || !total) {
|
||||
const navigated = km != null && !!total;
|
||||
this._map.setLayoutProperty(`${SOURCE}-behind`, "visibility", navigated ? "visible" : "none");
|
||||
if (!navigated) {
|
||||
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", undefined);
|
||||
this._map.setPaintProperty(`${SOURCE}-casing`, "line-gradient", undefined);
|
||||
return;
|
||||
}
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
const active = css.getPropertyValue("--route-active").trim() || "#a21caf";
|
||||
const driven = css.getPropertyValue("--ui-muted").trim() || "#6b6b66";
|
||||
const active = getComputedStyle(document.documentElement).getPropertyValue("--route-active").trim() || "#a21caf";
|
||||
const clear = "rgba(0, 0, 0, 0)";
|
||||
const fraction = Math.min(1, Math.max(0, km / total));
|
||||
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient",
|
||||
fraction > 0 ? ["step", ["line-progress"], driven, fraction, active] : ["step", ["line-progress"], active, 1, active]);
|
||||
// behind the car the line and its casing go clear: the dashed layer under them shows, the log's track over it
|
||||
const ahead = (color) => (fraction > 0 ? ["step", ["line-progress"], clear, fraction, color] : ["step", ["line-progress"], color, 1, color]);
|
||||
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", ahead(active));
|
||||
this._map.setPaintProperty(`${SOURCE}-casing`, "line-gradient", ahead("#fff"));
|
||||
}
|
||||
|
||||
// A route item in the library ("Routes" folder), keeping its points and
|
||||
@@ -638,7 +1131,7 @@ export class RoutePanelControl {
|
||||
notifyGpxStoreChanged(path);
|
||||
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
|
||||
this._renderPoints();
|
||||
this._summary.textContent += " · saved";
|
||||
this._summary.textContent = "Saved to the library";
|
||||
}
|
||||
|
||||
// The route's points marked 📍 as points inside the route item (marked
|
||||
@@ -712,15 +1205,28 @@ export class RoutePanelControl {
|
||||
});
|
||||
}
|
||||
|
||||
// Where the route needs a vignette or pays tolls, country by country.
|
||||
// Country by country on the route: the profile's limits there (motorway /
|
||||
// outside towns / in towns), how its motorways are paid and whether the
|
||||
// profile has it (a vignette, or a toll unit over 3.5 t), the km driven.
|
||||
// Motorway km in a vignette country count whole: the vignette isn't
|
||||
// reliably tagged as toll in OSM.
|
||||
_showCountries(countries) {
|
||||
const rows = (countries || []).flatMap(({ code, motorway_km: motorway, toll_km: toll }) => {
|
||||
if (VIGNETTE_COUNTRIES.has(code) && motorway > 0) {
|
||||
return [`${code}: vignette, ${motorway.toFixed(0)} km motorway${toll > 0 ? ` (${toll.toFixed(0)} km tolled)` : ""}`];
|
||||
}
|
||||
return toll > 0 ? [`${code}: toll, ${toll.toFixed(0)} km`] : [];
|
||||
this._lastCountries = countries;
|
||||
const v = this._vehicle;
|
||||
const sign = (limit) => `<span class="route-panel__sign">${limit ?? "–"}</span>`;
|
||||
const rows = (countries || []).map(({ code, km, motorway_km: motorway, toll_km: toll }) => {
|
||||
const row = SPEED_LIMITS[code]?.[isHeavy(v) ? "heavy" : "car"];
|
||||
const pay = motorwayPayment(code, v);
|
||||
const pays = pay.how && motorway > 0
|
||||
? `${pay.how} ${pay.has ? "✓" : pay.has === false && pay.until ? `ended ${pay.until}` : "—"}`
|
||||
: toll > 0 ? `toll, ${toll.toFixed(0)} km` : "";
|
||||
const li = document.createElement("li");
|
||||
li.classList.toggle("route-panel__country--missing", pay.how != null && motorway > 0 && !pay.has);
|
||||
li.innerHTML = `<b>${code}</b><span>${km.toFixed(0)} km${pays ? ` · ${pays}` : ""}</span>` +
|
||||
(row ? `<span class="route-panel__signs" title="motorway · outside towns · in towns">${[row[0], row[2], row[3]].map(sign).join("")}</span>` : "");
|
||||
return li;
|
||||
});
|
||||
this._countries.replaceChildren(...rows.map((text) => Object.assign(document.createElement("li"), { textContent: text })));
|
||||
this._countries.replaceChildren(...rows);
|
||||
this._countries.hidden = rows.length === 0;
|
||||
}
|
||||
|
||||
@@ -745,30 +1251,104 @@ export class RoutePanelControl {
|
||||
|
||||
// --- vehicle --------------------------------------------------------------
|
||||
|
||||
// Profiles (Car, Camper, ...) are shared and edited only when logged in;
|
||||
// which one is in use is this browser's own choice. A change re-routes.
|
||||
// Profiles (Car, Camper, Bicycle, ...) are shared and edited only when
|
||||
// logged in, in a dialog (the Design canvas' Vehicle); which one is in use
|
||||
// is this browser's own choice (or the shared trip's), picked from the chip
|
||||
// in the map's bottom-left corner. A change re-routes.
|
||||
async _setupVehicle() {
|
||||
const select = this._panel.querySelector(".route-panel__vehicle-select");
|
||||
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
|
||||
const fieldset = this._panel.querySelector(".route-panel__vehicle");
|
||||
const inputs = [...fieldset.querySelectorAll("input, select")];
|
||||
const dialog = document.querySelector("dialog.profiles");
|
||||
const fieldset = dialog.querySelector(".profiles__form");
|
||||
const inputs = [...fieldset.querySelectorAll(":scope > label input, :scope > label select")];
|
||||
const list = dialog.querySelector(".profiles__list ul");
|
||||
const vignetteList = dialog.querySelector(".profiles__vignettes ul");
|
||||
const avoidRow = this._panel.querySelector(".route-panel__avoid");
|
||||
try {
|
||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
let editId = null; // the profile open in the dialog, apart from the one in use
|
||||
const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0];
|
||||
const fill = () => {
|
||||
select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id)));
|
||||
this._vehicle = current();
|
||||
this._vehicleId = select.value = this._vehicle.id;
|
||||
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
|
||||
// No type: a car (profiles saved before bicycle/foot existed).
|
||||
const type = (fieldset.querySelector('[name="type"]').value = this._vehicle.type || "car");
|
||||
if (type === "bicycle" && !this._vehicle.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid";
|
||||
const edited = () => this._vehicles.find((v) => v.id === editId) || current();
|
||||
const typeOf = (v) => v.type || "car";
|
||||
|
||||
const chip = document.createElement("div");
|
||||
chip.className = "maplibregl-ctrl profile-chip";
|
||||
chip.innerHTML = `<ul class="profile-chip__list" hidden></ul><button type="button" class="profile-chip__button" aria-haspopup="true"></button>`;
|
||||
const chipButton = chip.querySelector(".profile-chip__button");
|
||||
const chipList = chip.querySelector(".profile-chip__list");
|
||||
this._map.addControl({ onAdd: () => chip, onRemove: () => chip.remove() }, "bottom-left");
|
||||
const row = (v, onPick) => {
|
||||
const li = document.createElement("li");
|
||||
const button = Object.assign(document.createElement("button"), { type: "button" });
|
||||
button.innerHTML = `<span>${PROFILE_ICONS[typeOf(v)]}</span><b></b><small></small>`;
|
||||
button.querySelector("b").textContent = v.name;
|
||||
button.querySelector("small").textContent = profileMeta(v);
|
||||
button.addEventListener("click", () => onPick(v));
|
||||
li.appendChild(button);
|
||||
return li;
|
||||
};
|
||||
|
||||
const fillForm = () => {
|
||||
const v = edited();
|
||||
list.replaceChildren(...this._vehicles.map((p) => {
|
||||
const li = row(p, (picked) => { editId = picked.id; fillForm(); });
|
||||
li.classList.toggle("is-open", p === v);
|
||||
return li;
|
||||
}));
|
||||
inputs.forEach((input) => (input.value = v[input.name] ?? ""));
|
||||
const type = (fieldset.querySelector('[name="type"]').value = typeOf(v));
|
||||
if (type === "bicycle" && !v.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid";
|
||||
fieldset.querySelectorAll("[data-for]").forEach((el) => (el.hidden = !el.dataset.for.split(" ").includes(type)));
|
||||
avoidRow.hidden = type !== "car"; // tolls/motorways: a car's choice
|
||||
vignetteList.replaceChildren(...(v.vignettes || []).map((vignette, i) => {
|
||||
const li = document.createElement("li");
|
||||
li.innerHTML = `<input name="country" maxlength="2" placeholder="SK" aria-label="Country">
|
||||
<select name="kind" aria-label="Kind"><option value="vignette">vignette</option><option value="toll">toll unit (over 3.5 t)</option></select>
|
||||
<input name="until" type="date" aria-label="Valid until"><button type="button" aria-label="Remove">✕</button>`;
|
||||
li.querySelector('[name="country"]').value = vignette.country || "";
|
||||
li.querySelector('[name="kind"]').value = vignette.kind || "vignette";
|
||||
li.querySelector('[name="until"]').value = vignette.until || "";
|
||||
li.querySelectorAll("input, select").forEach((el) => el.addEventListener("change", () => {
|
||||
const value = el.value.trim();
|
||||
if (value) vignette[el.name] = el.name === "country" ? value.toUpperCase() : value;
|
||||
else delete vignette[el.name];
|
||||
if (vignette.country?.length === 2) save();
|
||||
}));
|
||||
li.querySelector("button").addEventListener("click", () => {
|
||||
v.vignettes.splice(i, 1);
|
||||
save();
|
||||
});
|
||||
return li;
|
||||
}));
|
||||
};
|
||||
const fill = () => {
|
||||
this._vehicle = current();
|
||||
this._vehicleId = this._vehicle.id;
|
||||
chipButton.innerHTML = `<span>${PROFILE_ICONS[typeOf(this._vehicle)]}</span> <span></span> ▴`;
|
||||
chipButton.children[1].textContent = [this._vehicle.name, typeOf(this._vehicle) === "car" ? profileMeta(this._vehicle) : ""].filter(Boolean).join(" · ");
|
||||
chipList.replaceChildren(...this._vehicles.map((v) => {
|
||||
const li = row(v, (picked) => {
|
||||
chipList.hidden = true;
|
||||
this._selectVehicle(picked.id);
|
||||
this._fetchRoute();
|
||||
});
|
||||
li.classList.toggle("is-current", v === this._vehicle);
|
||||
return li;
|
||||
}));
|
||||
if (isLoggedIn()) {
|
||||
const edit = Object.assign(document.createElement("button"), { type: "button", className: "profile-chip__edit", textContent: "Edit profiles…" });
|
||||
edit.addEventListener("click", () => {
|
||||
chipList.hidden = true;
|
||||
editId = this._vehicleId;
|
||||
fillForm();
|
||||
dialog.showModal();
|
||||
});
|
||||
chipList.appendChild(Object.assign(document.createElement("li"), { className: "profile-chip__edit-row" })).appendChild(edit);
|
||||
}
|
||||
avoidRow.hidden = typeOf(this._vehicle) !== "car"; // tolls/motorways: a car's choice
|
||||
if (this._lastCountries) this._showCountries(this._lastCountries);
|
||||
if (dialog.open) fillForm();
|
||||
notifyVehicle(this._vehicle);
|
||||
};
|
||||
this._selectVehicle = (id) => {
|
||||
this._vehicleId = id;
|
||||
@@ -783,11 +1363,11 @@ export class RoutePanelControl {
|
||||
if (response.ok) {
|
||||
this._vehicles = data;
|
||||
} else {
|
||||
window.alert(data.error || "Could not save the vehicles.");
|
||||
window.alert(data.error || "Could not save the profiles.");
|
||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||
}
|
||||
fill();
|
||||
this._fetchRoute();
|
||||
if (edited() === current()) this._fetchRoute();
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -795,33 +1375,35 @@ export class RoutePanelControl {
|
||||
this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY);
|
||||
} catch {}
|
||||
fill();
|
||||
select.addEventListener("change", () => {
|
||||
this._selectVehicle(select.value);
|
||||
this._fetchRoute();
|
||||
});
|
||||
|
||||
editButton.hidden = !isLoggedIn();
|
||||
editButton.addEventListener("click", () => (fieldset.hidden = !fieldset.hidden));
|
||||
chipButton.addEventListener("click", () => (chipList.hidden = !chipList.hidden));
|
||||
document.addEventListener("click", (e) => !chip.contains(e.target) && (chipList.hidden = true));
|
||||
dialog.querySelector(".profiles__close").addEventListener("click", () => dialog.close());
|
||||
inputs.forEach((input) =>
|
||||
input.addEventListener("change", () => {
|
||||
const value = input.value.trim();
|
||||
if (input.name === "name") current().name = value;
|
||||
else if (value === "") delete current()[input.name];
|
||||
else if (input.name === "type" || input.name === "bicycle_type") current()[input.name] = value;
|
||||
else current()[input.name] = value;
|
||||
if (input.name === "name") edited().name = value;
|
||||
else if (value === "") delete edited()[input.name];
|
||||
else edited()[input.name] = value;
|
||||
save();
|
||||
}),
|
||||
);
|
||||
fieldset.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => {
|
||||
dialog.querySelector('[data-action="vignette-add"]').addEventListener("click", () => {
|
||||
(edited().vignettes ||= []).push({ country: "", kind: "vignette" });
|
||||
fillForm();
|
||||
vignetteList.lastElementChild?.querySelector("input")?.focus();
|
||||
});
|
||||
dialog.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => {
|
||||
const id = `v${Date.now().toString(36)}`;
|
||||
this._vehicles.push({ ...current(), id, name: "New vehicle" });
|
||||
this._selectVehicle(id);
|
||||
this._vehicles.push({ ...edited(), id, name: "New profile" });
|
||||
editId = id;
|
||||
save();
|
||||
});
|
||||
fieldset.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => {
|
||||
if (this._vehicles.length < 2 || !window.confirm(`Delete the vehicle "${current().name}"?`)) return;
|
||||
this._vehicles = this._vehicles.filter((v) => v !== current());
|
||||
this._selectVehicle(this._vehicles[0].id);
|
||||
dialog.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => {
|
||||
if (this._vehicles.length < 2 || !window.confirm(`Delete the profile "${edited().name}"?`)) return;
|
||||
const gone = edited();
|
||||
this._vehicles = this._vehicles.filter((v) => v !== gone);
|
||||
editId = null;
|
||||
if (gone === current()) this._selectVehicle(this._vehicles[0].id);
|
||||
save();
|
||||
});
|
||||
}
|
||||
@@ -873,6 +1455,13 @@ function distanceM([lon1, lat1], [lon2, lat2]) {
|
||||
return 12742000 * Math.asin(Math.sqrt(a));
|
||||
}
|
||||
|
||||
// Parking → the place, straight (the real path ~ a quarter longer).
|
||||
// ponytail: straight line ×1.25, a foot route from Valhalla if it misleads
|
||||
function walk(point) {
|
||||
const m = distanceM(point.park.lngLat, point.lngLat) * 1.25;
|
||||
return m < 1000 ? `${Math.round(m / 10) * 10} m` : `${(m / 1000).toFixed(1)} km`;
|
||||
}
|
||||
|
||||
export function formatDuration(seconds) {
|
||||
const minutes = Math.round(seconds / 60);
|
||||
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
|
||||
|
||||
@@ -120,6 +120,23 @@ export class SearchControl {
|
||||
return;
|
||||
}
|
||||
|
||||
// A pasted link (Google Maps, park4night, a page with coordinates):
|
||||
// the server reads the place from it (lib/maptool/link_place.rb)
|
||||
if (/^(https?:\/\/|geo:)\S+$/i.test(query)) {
|
||||
this._renderResults([], true);
|
||||
try {
|
||||
const response = await fetch(`/api/link?${new URLSearchParams({ url: query })}`);
|
||||
const place = await response.json();
|
||||
if (!response.ok) throw new Error(response.status === 401 ? "log in to read links" : place.error);
|
||||
let where = "From the link";
|
||||
try { where = `From ${new URL(place.url || query).hostname}`; } catch { /* geo: */ }
|
||||
this._renderResults([{ name: place.name || `${place.lat.toFixed(5)}, ${place.lng.toFixed(5)}`, where, lat: place.lat, lng: place.lng }]);
|
||||
} catch (err) {
|
||||
this._renderResults([{ status: `That link: ${err.message}` }]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Every source answers on its own; the list re-renders (nearest first
|
||||
// across all of them) as each one comes in.
|
||||
const searchId = (this._searchId = (this._searchId || 0) + 1);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// The countries' general speed limits (km/h) for a car / a vehicle up to
|
||||
// 3.5 t and for a motorhome over 3.5 t: [motorway, expressway, outside towns,
|
||||
// in towns]; null = no general limit. What a road's own sign says wins when
|
||||
// it's lower (dashboard.js), these fill in what a vehicle may not exceed.
|
||||
//
|
||||
// Sources (read 2026-12-03; both are camping guides built on ADAC's tables,
|
||||
// not the laws themselves — check before relying on a figure):
|
||||
// W = womoly.app/wohnmobil-ratgeber/tempolimits-europa (Stand Oktober 2026)
|
||||
// C = copilot.travel/maps/caravan-speed-limits (read up to 2026-10-31)
|
||||
// CZ, HU, PL, SK only from C (a secondary source). Left out where the two
|
||||
// disagree or depend on the registration: ES, SE, NO, BE, LU, and countries
|
||||
// neither covers (RO, BG, GR).
|
||||
// ponytail: one figure per road class; night/rain limits, Germany's 100 only for a
|
||||
// registered Wohnmobil up to 7.5 t, France's 80/90 by département not modelled
|
||||
export const SPEED_LIMITS = {
|
||||
AT: { car: [130, 100, 100, 50], heavy: [80, 80, 70, 50], src: "W, C" },
|
||||
CH: { car: [120, 100, 80, 50], heavy: [100, 100, 80, 50], src: "W, C" },
|
||||
CZ: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "C" },
|
||||
DE: { car: [null, 100, 100, 50], heavy: [100, 100, 80, 50], src: "W, C; 100 only registered as Wohnmobil, else 80" },
|
||||
DK: { car: [130, 80, 80, 50], heavy: [80, 80, 80, 50], src: "W, C" },
|
||||
FR: { car: [130, 110, 80, 50], heavy: [110, 100, 80, 50], src: "W, C" },
|
||||
HR: { car: [130, 110, 90, 50], heavy: [90, 80, 80, 50], src: "W, C" },
|
||||
HU: { car: [130, 110, 90, 50], heavy: [80, 70, 70, 50], src: "C" },
|
||||
IT: { car: [130, 110, 90, 50], heavy: [100, 80, 80, 50], src: "W, C" },
|
||||
NL: { car: [100, 100, 80, 50], heavy: [80, 80, 80, 50], src: "W, C; 130 at night on some motorways" },
|
||||
PL: { car: [140, 120, 90, 50], heavy: [80, 80, 70, 50], src: "C" },
|
||||
PT: { car: [120, 100, 90, 50], heavy: [100, 90, 80, 50], src: "W, C" },
|
||||
SI: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "W, C" },
|
||||
SK: { car: [130, 130, 90, 50], heavy: [90, 90, 90, 50], src: "C" },
|
||||
};
|
||||
|
||||
// Motorways paid by a time-based vignette (a car up to 3.5 t); over 3.5 t
|
||||
// these countries charge by distance (a toll unit) instead.
|
||||
export const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
|
||||
|
||||
export const COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
|
||||
|
||||
// Over 3.5 t: a car profile heavier than that.
|
||||
export const isHeavy = (vehicle) => (vehicle?.type || "car") === "car" && (vehicle?.weight ?? 0) > 3.5;
|
||||
|
||||
// The column of the four for a Valhalla road class.
|
||||
const column = (roadClass) => (roadClass === "motorway" ? 0 : roadClass === "trunk" ? 1 : 2);
|
||||
|
||||
// The vehicle's limit on this road: the general one for its class and road
|
||||
// class (outside towns: Valhalla doesn't say where a town starts, a town's
|
||||
// own 50 is the road's sign), or null where none is known.
|
||||
export function vehicleLimit(code, roadClass, vehicle) {
|
||||
const row = SPEED_LIMITS[code];
|
||||
return row ? row[isHeavy(vehicle) ? "heavy" : "car"][column(roadClass)] : null;
|
||||
}
|
||||
|
||||
// The lower of the road's sign (a number, "unlimited" or null) and the
|
||||
// vehicle's own limit there. Only for a heavy vehicle: a car's general limit
|
||||
// is what the road's sign already says, or unknown.
|
||||
export function effectiveLimit(sign, code, roadClass, vehicle) {
|
||||
const own = isHeavy(vehicle) ? vehicleLimit(code, roadClass, vehicle) : null;
|
||||
if (own == null) return sign;
|
||||
return typeof sign === "number" ? Math.min(sign, own) : own;
|
||||
}
|
||||
|
||||
// How the motorways are paid there, and whether the profile has it:
|
||||
// { how: "vignette" | "toll unit" | null, has: true | false | null, until }.
|
||||
export function motorwayPayment(code, vehicle, today = new Date().toISOString().slice(0, 10)) {
|
||||
const heavy = isHeavy(vehicle);
|
||||
const how = VIGNETTE_COUNTRIES.has(code) ? (heavy ? "toll unit" : "vignette") : null;
|
||||
if (!how) return { how: null, has: null };
|
||||
const kind = heavy ? "toll" : "vignette";
|
||||
const owned = (vehicle?.vignettes || []).find((v) => v.country === code && (v.kind || "vignette") === kind);
|
||||
if (!owned) return { how, has: false };
|
||||
return { how, has: !owned.until || owned.until >= today, until: owned.until || null };
|
||||
}
|
||||
@@ -45,11 +45,18 @@ export class TrackProfilePanel {
|
||||
this._stats = this._panel.querySelector(".profile-panel__stats");
|
||||
this._chartsContainer = this._panel.querySelector(".profile-panel__charts");
|
||||
this._panel.querySelector(".profile-panel__close").addEventListener("click", () => this.hide());
|
||||
// Docked under the map (the Design canvas' Desktop): the map gives up
|
||||
// the profile's height instead of being covered by it.
|
||||
new ResizeObserver(() => {
|
||||
const height = this._panel.hidden ? 0 : this._panel.offsetHeight;
|
||||
document.documentElement.style.setProperty("--profile-h", `${height}px`);
|
||||
}).observe(this._panel);
|
||||
}
|
||||
|
||||
show(properties) {
|
||||
const profile = properties.profile;
|
||||
if (!profile || profile.length === 0) return;
|
||||
this.shown = properties; // whose profile this is (route.js hides its own)
|
||||
|
||||
this._profile = profile.map((point) => ({ ...point, speed_kmh: typeof point.speed_mps === "number" ? point.speed_mps * 3.6 : null }));
|
||||
addMovingTime(this._profile);
|
||||
@@ -204,7 +211,9 @@ export class TrackProfilePanel {
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.shown = null;
|
||||
this._panel.hidden = true;
|
||||
document.documentElement.style.setProperty("--profile-h", "0px");
|
||||
this._plots?.removeEventListener("pointermove", this._onPointerMove);
|
||||
this._plots?.removeEventListener("pointerleave", this._onPointerLeave);
|
||||
this._marker.remove();
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* MapLibre GL JS
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.20.0/LICENSE.txt
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.21.0/LICENSE.txt
|
||||
*/
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));function l(e,t){this.x=e,this.y=t}l.prototype={clone(){return new l(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:l},l.convert=function(e){if(e instanceof l)return e;if(Array.isArray(e))return new l(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new l(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function u(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let d;function f(){return d??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,d}let p;function m(){if(p==null&&(p=!1,f())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){p=!0;break}}}return p||!1}var h=typeof Float32Array<`u`?Float32Array:Array;function g(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function _(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function v(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],p=t[10],m=t[11],h=t[12],g=t[13],_=t[14],v=t[15],y=n[0],b=n[1],x=n[2],S=n[3];return e[0]=y*r+b*s+x*d+S*h,e[1]=y*i+b*c+x*f+S*g,e[2]=y*a+b*l+x*p+S*_,e[3]=y*o+b*u+x*m+S*v,y=n[4],b=n[5],x=n[6],S=n[7],e[4]=y*r+b*s+x*d+S*h,e[5]=y*i+b*c+x*f+S*g,e[6]=y*a+b*l+x*p+S*_,e[7]=y*o+b*u+x*m+S*v,y=n[8],b=n[9],x=n[10],S=n[11],e[8]=y*r+b*s+x*d+S*h,e[9]=y*i+b*c+x*f+S*g,e[10]=y*a+b*l+x*p+S*_,e[11]=y*o+b*u+x*m+S*v,y=n[12],b=n[13],x=n[14],S=n[15],e[12]=y*r+b*s+x*d+S*h,e[13]=y*i+b*c+x*f+S*g,e[14]=y*a+b*l+x*p+S*_,e[15]=y*o+b*u+x*m+S*v,e}function y(e,t,n){var r=n[0],i=n[1],a=n[2],o,s,c,l,u,d,f,p,m,h,g,_;return t===e?(e[12]=t[0]*r+t[4]*i+t[8]*a+t[12],e[13]=t[1]*r+t[5]*i+t[9]*a+t[13],e[14]=t[2]*r+t[6]*i+t[10]*a+t[14],e[15]=t[3]*r+t[7]*i+t[11]*a+t[15]):(o=t[0],s=t[1],c=t[2],l=t[3],u=t[4],d=t[5],f=t[6],p=t[7],m=t[8],h=t[9],g=t[10],_=t[11],e[0]=o,e[1]=s,e[2]=c,e[3]=l,e[4]=u,e[5]=d,e[6]=f,e[7]=p,e[8]=m,e[9]=h,e[10]=g,e[11]=_,e[12]=o*r+u*i+m*a+t[12],e[13]=s*r+d*i+h*a+t[13],e[14]=c*r+f*i+g*a+t[14],e[15]=l*r+p*i+_*a+t[15]),e}function b(Line truncated
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(let c of r(i))!a.call(e,c)&&c!==o&&(s=n(i,c),t(e,c,{get:s&&s.get&&!s.configurable?s.get:()=>i[c],enumerable:!s||s.enumerable}));return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));function l(e,t){this.x=e,this.y=t}l.prototype={clone(){return new l(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:l},l.convert=function(e){if(e instanceof l)return e;if(Array.isArray(e))return new l(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new l(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function u(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let d;function f(){return d??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,d}let p;function m(){if(p==null&&(p=!1,f())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){p=!0;break}}}return p||!1}var h=typeof Float32Array<`u`?Float32Array:Array;function g(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function _(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function v(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],p=t[10],m=t[11],h=t[12],g=t[13],_=t[14],v=t[15],y=n[0],b=n[1],x=n[2],S=n[3];return e[0]=y*r+b*s+x*d+S*h,e[1]=y*i+b*c+x*f+S*g,e[2]=y*a+b*l+x*p+S*_,e[3]=y*o+b*u+x*m+S*v,y=n[4],b=n[5],x=n[6],S=n[7],e[4]=y*r+b*s+x*d+S*h,e[5]=y*i+b*c+x*f+S*g,e[6]=y*a+b*l+x*p+S*_,e[7]=y*o+b*u+x*m+S*v,y=n[8],b=n[9],x=n[10],S=n[11],e[8]=y*r+b*s+x*d+S*h,e[9]=y*i+b*c+x*f+S*g,e[10]=y*a+b*l+x*p+S*_,e[11]=y*o+b*u+x*m+S*v,y=n[12],b=n[13],x=n[14],S=n[15],e[12]=y*r+b*s+x*d+S*h,e[13]=y*i+b*c+x*f+S*g,e[14]=y*a+b*l+x*p+S*_,e[15]=y*o+b*u+x*m+S*v,e}function y(e,t,n){var r=n[0],i=n[1],a=n[2],o,s,c,l,u,d,f,p,m,h,g,_;return t===e?(e[12]=t[0]*r+t[4]*i+t[8]*a+t[12],e[13]=t[1]*r+t[5]*i+t[9]*a+t[13],e[14]=t[2]*r+t[6]*i+t[10]*a+t[14],e[15]=t[3]*r+t[7]*i+t[11]*a+t[15]):(o=t[0],s=t[1],c=t[2],l=t[3],u=t[4],d=t[5],f=t[6],p=t[7],m=t[8],h=t[9],g=t[10],_=t[11],e[0]=o,e[1]=s,e[2]=c,e[3]=l,e[4]=u,e[5]=d,e[6]=f,e[7]=p,e[8]=m,e[9]=h,e[10]=g,e[11]=_,e[12]=o*r+u*i+m*a+t[12],e[13]=s*r+d*i+h*a+t[13],e[14]=c*r+f*i+g*a+t[14],e[15]=l*r+p*i+_*a+t[15]),e}function b(e,t,n){vaLine truncated
|
||||
/* @vite-ignore */
|
||||
e);return}let t=await fetch(e,{credentials:`same-origin`});if(!t.ok)throw Error(`Failed to load ${e}: ${t.status}`);let n=await t.text();if(/^[ \t]*(import|export)\s/m.test(n)){let e=URL.createObjectURL(new Blob([n],{type:`text/javascript`}));try{await import(
|
||||
/* @vite-ignore */
|
||||
e)}finally{URL.revokeObjectURL(e)}}else globalThis.eval(n)}var jT=class{constructor(e){this.self=e,this.actor=new ws(e),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=/* @__PURE__ */ new Map,this.importedScripts=/* @__PURE__ */ new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t},this.self.addProtocol=is,this.self.removeProtocol=as,this.self.registerRTLTextPlugin=e=>{Sg.setMethods(e)},this.self.makeRequest=fs,this.self.setProjectionHandler=xT,this.actor.registerMessageHandler(`LDT`,(e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t)),this.actor.registerMessageHandler(`RDT`,async(e,t)=>{this._getDEMWorkerSource(e,t.source).removeTile(t)}),this.actor.registerMessageHandler(`GCEZ`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterExpansionZoom(t)),this.actor.registerMessageHandler(`GCC`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterChildren(t)),this.actor.registerMessageHandler(`GCL`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterLeaves(t)),this.actor.registerMessageHandler(`LD`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t)),this.actor.registerMessageHandler(`LT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t)),this.actor.registerMessageHandler(`RT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t)),this.actor.registerMessageHandler(`AT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t)),this.actor.registerMessageHandler(`RMT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t)),this.actor.registerMessageHandler(`RS`,async(e,t)=>{if(!this.workerSources[e]?.[t.type]?.[t.source])return;let n=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],n.removeSource!==void 0&&n.removeSource(t)}),this.actor.registerMessageHandler(`RM`,async e=>{delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e],this.globalStates.delete(e)}),this.actor.registerMessageHandler(`SR`,async(e,t)=>{this.referrer=t}),this.actor.registerMessageHandler(`PI`,async()=>{}),this.actor.registerMessageHandler(`SRPS`,(e,t)=>this._syncRTLPluginState(e,t)),this.actor.registerMessageHandler(`IS`,(e,t)=>this._importScript(t)),this.actor.registerMessageHandler(`SI`,(e,t)=>this._setImages(e,t)),this.actor.registerMessageHandler(`UL`,async(e,t)=>{this._getLayerIndex(e).update(t.layers,t.removedIds,this._getGlobalState(e))}),this.actor.registerMessageHandler(`UGS`,async(e,t)=>{let n=this._getGlobalState(e);for(let e in t)n[e]=t[e]}),this.actor.registerMessageHandler(`SL`,async(e,t)=>{this._getLayerIndex(e).replace(t,this._getGlobalState(e))})}async _importScript(e){let t=this.importedScripts.get(e);if(t)return t;let n=AT(e);this.importedScripts.set(e,n);try{await n}catch(t){throw this.importedScripts.delete(e),t}}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}async _setImages(e,t){this.availableImages[e]=t;for(let n in this.workerSources[e]){let r=this.workerSources[e][n];for(let e in r)r[e].availableImages=t}}async _syncRTLPluginState(e,t){return await Sg.syncState(t,e=>this._importScript(e))}_getAvailableImages(e){let t=this.availableImages[e];return t||=[],t}_getLayerIndex(e){let t=this.layerIndexes[e];return t||=this.layerIndexes[e]=new rT,t}_getWorkerSource(e,t,n){if(this.workerSources[e]||={},this.workerSources[e][t]||={},!this.workerSources[e][t][n]){let r={sendAsync:(t,n)=>(t.targetMapId=e,this.actor.sendAsync(t,n))};switch(t){case`vector`:this.workerSources[e][t][n]=new mT(r,this._getLayerIndex(e),this._getAvailableImages(e));break;case`geojson`:this.workerSources[e][t][n]=new DT(r,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][n]=new this.externalWorkerSourceTypes[t](r,this._getLayerIndex(e),this._getAvailableImages(e))}}return this.workerSources[e][t][n]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||={},this.demWorkerSources[e][t]||=new hT,this.demWorkerSources[e][t]}};ke(self)&&(self.worker=new jT(self));export{jT as default};
|
||||
e)}finally{URL.revokeObjectURL(e)}}else globalThis.eval(n)}var f3=class{constructor(e){this.self=e,this.actor=new Do(e),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=/* @__PURE__ */ new Map,this.importedScripts=/* @__PURE__ */ new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t},this.self.addProtocol=oo,this.self.removeProtocol=so,this.self.registerRTLTextPlugin=e=>{ch.setMethods(e)},this.self.makeRequest=ho,this.self.setProjectionHandler=n3,this.actor.registerMessageHandler(`LDT`,(e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t)),this.actor.registerMessageHandler(`RDT`,async(e,t)=>{this._getDEMWorkerSource(e,t.source).removeTile(t)}),this.actor.registerMessageHandler(`GCEZ`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterExpansionZoom(t)),this.actor.registerMessageHandler(`GCC`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterChildren(t)),this.actor.registerMessageHandler(`GCL`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterLeaves(t)),this.actor.registerMessageHandler(`LD`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t)),this.actor.registerMessageHandler(`LT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t)),this.actor.registerMessageHandler(`RT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t)),this.actor.registerMessageHandler(`AT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t)),this.actor.registerMessageHandler(`RMT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t)),this.actor.registerMessageHandler(`RS`,async(e,t)=>{if(!this.workerSources[e]?.[t.type]?.[t.source])return;let n=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],n.removeSource!==void 0&&n.removeSource(t)}),this.actor.registerMessageHandler(`RM`,async e=>{delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e],this.globalStates.delete(e)}),this.actor.registerMessageHandler(`SR`,async(e,t)=>{this.referrer=t}),this.actor.registerMessageHandler(`PI`,async()=>{}),this.actor.registerMessageHandler(`SRPS`,(e,t)=>this._syncRTLPluginState(e,t)),this.actor.registerMessageHandler(`IS`,(e,t)=>this._importScript(t)),this.actor.registerMessageHandler(`SI`,(e,t)=>this._setImages(e,t)),this.actor.registerMessageHandler(`UL`,async(e,t)=>{this._getLayerIndex(e).update(t.layers,t.removedIds,this._getGlobalState(e))}),this.actor.registerMessageHandler(`UGS`,async(e,t)=>{let n=this._getGlobalState(e);for(let e in t)n[e]=t[e]}),this.actor.registerMessageHandler(`SL`,async(e,t)=>{this._getLayerIndex(e).replace(t,this._getGlobalState(e))})}async _importScript(e){let t=this.importedScripts.get(e);if(t)return t;let n=d3(e);this.importedScripts.set(e,n);try{await n}catch(t){throw this.importedScripts.delete(e),t}}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}async _setImages(e,t){this.availableImages[e]=t;for(let n in this.workerSources[e]){let r=this.workerSources[e][n];for(let e in r)r[e].availableImages=t}}async _syncRTLPluginState(e,t){return await ch.syncState(t,e=>this._importScript(e))}_getAvailableImages(e){let t=this.availableImages[e];return t||=[],t}_getLayerIndex(e){let t=this.layerIndexes[e];return t||=this.layerIndexes[e]=new I4,t}_getWorkerSource(e,t,n){if(this.workerSources[e]||={},this.workerSources[e][t]||={},!this.workerSources[e][t][n]){let r={sendAsync:(t,n)=>(t.targetMapId=e,this.actor.sendAsync(t,n))};switch(t){case`vector`:this.workerSources[e][t][n]=new q4(r,this._getLayerIndex(e),this._getAvailableImages(e));break;case`geojson`:this.workerSources[e][t][n]=new c3(r,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][n]=new this.externalWorkerSourceTypes[t](r,this._getLayerIndex(e),this._getAvailableImages(e))}}return this.workerSources[e][t][n]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||={},this.demWorkerSources[e][t]||=new X4,this.demWorkerSources[e][t]}};ke(self)&&(self.worker=new f3(self));export{f3 as default};
|
||||
//# sourceMappingURL=maplibre-gl-worker.mjs.map
|
||||
+36
-36
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* MapLibre GL JS
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.20.0/LICENSE.txt
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.21.0/LICENSE.txt
|
||||
*/
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=`6.20.0`;function u(e,t){this.x=e,this.y=t}u.prototype={clone(){return new u(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:u},u.convert=function(e){if(e instanceof u)return e;if(Array.isArray(e))return new u(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new u(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function d(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let f;function p(){return f??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,f}let m;function h(){if(m==null&&(m=!1,p())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){m=!0;break}}}return m||!1}var g=typeof Float32Array<`u`?Float32Array:Array;function _(){var e=new g(4);return g!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function v(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n*a-i*r;return o?(o=1/o,e[0]=a*o,e[1]=-r*o,e[2]=-i*o,e[3]=n*o,e):null}function y(e){return e[0]*e[3]-e[2]*e[1]}function b(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=Math.sin(n),c=Math.cos(n);return e[0]=r*c+a*s,e[1]=i*c+o*s,e[2]=r*-s+a*c,e[3]=i*-s+o*c,e}function x(){var e=new g(9);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function S(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*(l*a-o*c)+n*(-l*i+o*s)+r*(c*i-a*s)}function C(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[2]=0,e[3]=-n,e[4]=r,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function w(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n+n,s=r+r,c=i+i,l=n*o,u=r*o,d=r*s,f=i*o,p=i*s,m=i*c,h=a*o,g=a*s,_=a*c;return e[0]=1-d-m,e[3]=u-_,e[6]=f+g,e[1]=u+_,e[4]=1-l-m,e[7]=p-h,e[2]=f-g,e[5]=p+h,e[8]=1-l-d,e}function T(){var e=new g(16);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function E(e){var t=new g(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function D(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5]Line truncated
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(let c of r(i))!a.call(e,c)&&c!==o&&(s=n(i,c),t(e,c,{get:s&&s.get&&!s.configurable?s.get:()=>i[c],enumerable:!s||s.enumerable}));return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=`6.21.0`;function u(e,t){this.x=e,this.y=t}u.prototype={clone(){return new u(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:u},u.convert=function(e){if(e instanceof u)return e;if(Array.isArray(e))return new u(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new u(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function d(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let f;function p(){return f??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,f}let m;function h(){if(m==null&&(m=!1,p())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){m=!0;break}}}return m||!1}var g=typeof Float32Array<`u`?Float32Array:Array;function _(){var e=new g(4);return g!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function v(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n*a-i*r;return o?(o=1/o,e[0]=a*o,e[1]=-r*o,e[2]=-i*o,e[3]=n*o,e):null}function y(e){return e[0]*e[3]-e[2]*e[1]}function b(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=Math.sin(n),c=Math.cos(n);return e[0]=r*c+a*s,e[1]=i*c+o*s,e[2]=r*-s+a*c,e[3]=i*-s+o*c,e}function x(){var e=new g(9);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function S(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*(l*a-o*c)+n*(-l*i+o*s)+r*(c*i-a*s)}function C(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[2]=0,e[3]=-n,e[4]=r,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function w(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n+n,s=r+r,c=i+i,l=n*o,u=r*o,d=r*s,f=i*o,p=i*s,m=i*c,h=a*o,g=a*s,_=a*c;return e[0]=1-d-m,e[3]=u-_,e[6]=f+g,e[1]=u+_,e[4]=1-l-m,e[7]=p-h,e[2]=f-g,e[5]=p+h,e[8]=1-l-d,e}function T(){var e=new g(16);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function E(e){var t=new g(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function D(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6Line truncated
|
||||
precision mediump float;
|
||||
#else
|
||||
#if !defined(lowp)
|
||||
@@ -15,7 +15,7 @@ precision mediump float;
|
||||
#define highp
|
||||
#endif
|
||||
#endif
|
||||
out highp vec4 fragColor;layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,XA=`#ifdef GL_ES
|
||||
out highp vec4 fragColor;layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,t9=`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#else
|
||||
#if !defined(lowp)
|
||||
@@ -63,15 +63,15 @@ return 0.0;
|
||||
#endif
|
||||
}const float PI=3.141592653589793;
|
||||
#define PROJECTION_UBO
|
||||
layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,ZA=`uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;
|
||||
layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,n9=`uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,QA=`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`,$A=`uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;
|
||||
}`,r9=`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`,i9=`uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,ej=`uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}`,tj=`in vec3 v_data;in float v_visibility;
|
||||
}`,a9=`uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}`,o9=`in vec3 v_data;in float v_visibility;
|
||||
#pragma maplibre: define highp vec4 color
|
||||
#pragma maplibre: define mediump float radius
|
||||
#pragma maplibre: define lowp float blur
|
||||
@@ -91,7 +91,7 @@ vec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_bl
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,nj=`uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;out float v_visibility;
|
||||
}`,s9=`uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;out float v_visibility;
|
||||
#pragma maplibre: define highp vec4 color
|
||||
#pragma maplibre: define mediump float radius
|
||||
#pragma maplibre: define lowp float blur
|
||||
@@ -123,15 +123,15 @@ vec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVectorOffset(circl
|
||||
#else
|
||||
gl_Position=projectTileWithElevation(corner_position,ele);
|
||||
#endif
|
||||
} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}`,rj=`void main() {fragColor=vec4(1.0);}`;const ij={prelude:aj(YA,XA),projectionMercator:aj(`
|
||||
void clipAntimeridian() {}`,`float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}`),projectionGlobe:aj(`in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian !=0 && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}`,`#define GLOBE_RADIUS 6371008.8
|
||||
} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}`,c9=`void main() {fragColor=vec4(1.0);}`;const l9={prelude:u9(e9,t9),projectionMercator:u9(`
|
||||
void clipAntimeridian() {}`,`float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}`),projectionGlobe:u9(`in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian !=0 && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}`,`#define GLOBE_RADIUS 6371008.8
|
||||
#ifndef PROJECTION_UBO
|
||||
uniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp vec4 u_projection_tile_origin;uniform highp vec2 u_projection_tile_origin_position;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;
|
||||
#endif
|
||||
out highp float v_projection_tile_x;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos
|
||||
);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float t=exp(PI-(mercator_pos_y*PI*2.0));return (2.0*t)/(t*t+1.0);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY);if (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;float spherical_x=mercator_pos.x*PI*2.0+PI;float t=exp(PI-(mercator_pos.y*PI*2.0));float t2=t*t;float denom=t2+1.0;float sin_sy=(t2-1.0)/denom;float cos_sy=(2.0*t)/denom;vec3 pos=vec3(sin(spherical_x)*cos_sy,sin_sy,cos(spherical_x)*cos_sy
|
||||
);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeSinSmall(float x) {float x2=x*x;return x*(1.0-x2/6.0*(1.0-x2/20.0*(1.0-x2/42.0*(1.0-x2/72.0*(1.0-x2/110.0*(1.0-x2/156.0))))));}float globeTanSmall(float x) {if (abs(x) >=0.5) {return tan(x);}float s=globeSinSmall(x);return s/sqrt(1.0-s*s);}float globeExpm1Small(float x) {if (abs(x) >=0.5) {return exp(x)-1.0;}return x*(1.0+x/2.0*(1.0+x/3.0*(1.0+x/4.0*(1.0+x/5.0*(1.0+x/6.0*(1.0+x/7.0*(1.0+x/8.0)))))));}vec3 globeTileOrigin() {if (u_projection_tile_origin.w < 0.5) {return vec3(0.0);}float t=u_projection_tile_origin.z;float denom=t*t+1.0;float cos_sy=2.0*t/denom;return vec3(u_projection_tile_origin.x*cos_sy,(t*t-1.0)/denom,u_projection_tile_origin.y*cos_sy);}vec2 globeAnglesFromTileOrigin(vec2 translatedPos) {return u_projection_tile_mercator_coords.zw*(translatedPos-u_projection_tile_origin_position)*(PI*2.0);}bool globeIsNearTileOrigin(vec2 translatedPos) {if (u_projection_tile_origin.w < 0.5) {return false;}vec2 delta=abs(globeAnglesFromTileOrigin(translatedPos));return delta.x <=PI*0.5 && delta.y <=PI*0.5;}vec3 projectToSphereOffset(vec2 translatedPos,vec2 rawPos) {if (!globeIsNearTileOrigin(translatedPos)) {return projectToSphere(translatedPos,rawPos)-globeTileOrigin();}if (rawPos.y <-32767.5) {return vec3(0.0,1.0,0.0)-globeTileOrigin();}if (rawPos.y > 32766.5) {return vec3(0.0,-1.0,0.0)-globeTileOrigin();}vec2 delta=globeAnglesFromTileOrigin(translatedPos);float sin_x0=u_projection_tile_origin.x;float cos_x0=u_projection_tile_origin.y;float t0=u_projection_tile_origin.z;float t0_2=t0*t0;float e=globeExpm1Small(-delta.y);float t=t0+t0*e;float denom=(t*t+1.0)*(t0_2+1.0);float d_sin_sy=2.0*t0_2*e*(2.0+e)/denom;float d_cos_sy=2.0*t0*e*(1.0-t*t0)/denom;float cos_sy=2.0*t0/(t0_2+1.0)+d_cos_sy;float sin_dx=globeSinSmall(delta.x);float half_sin_dx=globeSinSmall(delta.x*0.5);float cos_dx_minus_one=-2.0*half_sin_dx*half_sin_dx;float d_sin_x=sin_x0*cos_dx_minus_one+cos_x0*sin_dx;float d_cos_x=cos_x0*cos_dx_minus_one-sin_x0*sin_dx;return vec3(sin_x0*d_cos_sy+d_sin_x*cos_sy,d_sin_sy,cos_x0*d_cos_sy+d_cos_x*cos_sy
|
||||
);}vec3 projectToSphereOffset(vec2 posInTile) {return projectToSphereOffset(posInTile,vec2(0.0,0.0));}vec3 globeRotateVectorOffset(vec2 posInTile,vec3 offset,vec2 angles) {if (!globeIsNearTileOrigin(posInTile)) {return globeRotateVector(projectToSphere(posInTile),angles)-globeTileOrigin();}vec3 vec=globeTileOrigin()+offset;mat3 axes=globeGetRotationMatrix(vec);vec3 d=axes[0]*globeTanSmall(angles.x)+axes[1]*globeTanSmall(angles.y);float len=sqrt(1.0+dot(d,d));return offset+(d-vec*(dot(d,d)/(1.0+len)))/len;}float globeComputeClippingZ(vec3 spherePos) {return (1.0-min(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w,0.5));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 origin=globeTileOrigin();vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+origin*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+globeTileOrigin()*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphereOffset(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}`),background:aj(ZA,QA),backgroundPattern:aj($A,ej),circle:aj(tj,nj),clippingMask:aj(rj,`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`),heatmap:aj(`uniform highp float u_intensity;in vec2 v_extrude;
|
||||
);}vec3 projectToSphereOffset(vec2 posInTile) {return projectToSphereOffset(posInTile,vec2(0.0,0.0));}vec3 globeRotateVectorOffset(vec2 posInTile,vec3 offset,vec2 angles) {if (!globeIsNearTileOrigin(posInTile)) {return globeRotateVector(projectToSphere(posInTile),angles)-globeTileOrigin();}vec3 vec=globeTileOrigin()+offset;mat3 axes=globeGetRotationMatrix(vec);vec3 d=axes[0]*globeTanSmall(angles.x)+axes[1]*globeTanSmall(angles.y);float len=sqrt(1.0+dot(d,d));return offset+(d-vec*(dot(d,d)/(1.0+len)))/len;}float globeComputeClippingZ(vec3 spherePos) {return (1.0-min(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w,0.5));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 origin=globeTileOrigin();vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+origin*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+globeTileOrigin()*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphereOffset(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}`),background:u9(n9,r9),backgroundPattern:u9(i9,a9),circle:u9(o9,s9),clippingMask:u9(c9,`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`),heatmap:u9(`uniform highp float u_intensity;in vec2 v_extrude;
|
||||
#pragma maplibre: define highp float weight
|
||||
#define GAUSS_COEF 0.3989422804014327
|
||||
void main() {
|
||||
@@ -154,11 +154,11 @@ vec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToS
|
||||
#else
|
||||
gl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));
|
||||
#endif
|
||||
}`),heatmapTexture:aj(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;
|
||||
}`),heatmapTexture:u9(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(0.0);
|
||||
#endif
|
||||
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world_size,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}`),collisionBox:aj(`in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}`,`layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}`),collisionCircle:aj(`in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}`,`layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),colorRelief:aj(`#ifdef GL_ES
|
||||
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world_size,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}`),collisionBox:u9(`in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}`,`layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}`),collisionCircle:u9(`in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}`,`layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),colorRelief:u9(`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#endif
|
||||
uniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {vec4 data=texelFetch(u_elevation_stops,ivec2(stop,0),0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else
|
||||
@@ -166,13 +166,13 @@ uniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_st
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,`uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=2.0/u_dimension;float scale=(u_dimension.x-4.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),debug:aj(`uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}`,`layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}`),depth:aj(rj,`layout(location=0) in vec2 a_pos;void main() {
|
||||
}`,`uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=2.0/u_dimension;float scale=(u_dimension.x-4.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),debug:u9(`uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}`,`layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}`),depth:u9(c9,`layout(location=0) in vec2 a_pos;void main() {
|
||||
#ifdef GLOBE
|
||||
gl_Position=projectTileFor3D(a_pos,0.0);
|
||||
#else
|
||||
gl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);
|
||||
#endif
|
||||
}`),fill:aj(`#pragma maplibre: define highp vec4 color
|
||||
}`),fill:u9(`#pragma maplibre: define highp vec4 color
|
||||
#pragma maplibre: define lowp float opacity
|
||||
void main() {
|
||||
#pragma maplibre: initialize highp vec4 color
|
||||
@@ -187,7 +187,7 @@ fragColor=vec4(1.0);
|
||||
void main() {
|
||||
#pragma maplibre: initialize highp vec4 color
|
||||
#pragma maplibre: initialize lowp float opacity
|
||||
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}`),fillOutline:aj(`in vec2 v_pos;
|
||||
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}`),fillOutline:u9(`in vec2 v_pos;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -216,7 +216,7 @@ if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=pr
|
||||
#ifdef GLOBE
|
||||
v_depth=gl_Position.z/gl_Position.w;
|
||||
#endif
|
||||
}`),fillOutlinePattern:aj(`uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;uniform bool u_sdf_pattern;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;
|
||||
}`),fillOutlinePattern:u9(`uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;uniform bool u_sdf_pattern;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -257,7 +257,7 @@ if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_t
|
||||
#ifdef GLOBE
|
||||
v_depth=gl_Position.z/gl_Position.w;
|
||||
#endif
|
||||
}`),fillPattern:aj(`#ifdef GL_ES
|
||||
}`),fillPattern:u9(`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#endif
|
||||
uniform vec2 u_texsize;uniform float u_fade;uniform bool u_sdf_pattern;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;
|
||||
@@ -288,7 +288,7 @@ void main() {
|
||||
#pragma maplibre: initialize mediump vec4 pattern_to
|
||||
#pragma maplibre: initialize lowp float pixel_ratio_from
|
||||
#pragma maplibre: initialize lowp float pixel_ratio_to
|
||||
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}`),fillExtrusion:aj(`in vec4 v_color;void main() {fragColor=v_color;
|
||||
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}`),fillExtrusion:u9(`in vec4 v_color;void main() {fragColor=v_color;
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
@@ -322,7 +322,7 @@ float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0
|
||||
#ifdef GLOBE
|
||||
mat3 rotMatrix=globeGetRotationMatrix(globeTileOrigin()+spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);
|
||||
#endif
|
||||
directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=opacity;}`),fillExtrusionPattern:aj(`uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;
|
||||
directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=opacity;}`),fillExtrusionPattern:u9(`uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;
|
||||
#pragma maplibre: define lowp float base
|
||||
#pragma maplibre: define lowp float height
|
||||
#pragma maplibre: define lowp vec4 pattern_from
|
||||
@@ -377,14 +377,14 @@ gl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);
|
||||
#endif
|
||||
vec2 pos=a_normal_ed.x==1 && a_normal_ed.y==0 && a_normal_ed.z==16384
|
||||
? a_pos
|
||||
: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=opacity;}`),hillshadePrepare:aj(`#ifdef GL_ES
|
||||
: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=opacity;}`),hillshadePrepare:u9(`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#endif
|
||||
uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;uniform float u_log2_world_width;float getElevation(ivec2 texel) {vec4 data=texelFetch(u_image,texel,0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {ivec2 pos=ivec2(gl_FragCoord.xy)+ivec2(1);float tileSize=u_dimension.x-4.0;float a=getElevation(pos+ivec2(-1,-1));float b=getElevation(pos+ivec2(0,-1));float c=getElevation(pos+ivec2(1,-1));float d=getElevation(pos+ivec2(-1,0));float e=getElevation(pos);float f=getElevation(pos+ivec2(1,0));float g=getElevation(pos+ivec2(-1,1));float h=getElevation(pos+ivec2(0,1));float i=getElevation(pos+ivec2(1,1));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(3.0+u_log2_world_width-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+128.0/255.0,deriv.y/8.0+128.0/255.0,1.0,1.0),0.0,1.0);
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,`uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}`),hillshade:aj(`uniform sampler2D u_image;in highp vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];
|
||||
}`,`uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}`),hillshade:u9(`uniform sampler2D u_image;in highp vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];
|
||||
#define PI 3.141592653589793
|
||||
#define STANDARD 0
|
||||
#define COMBINED 1
|
||||
@@ -397,7 +397,7 @@ float get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),line:aj(`in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;
|
||||
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),line:u9(`in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -443,7 +443,7 @@ v_gamma_scale=1.0;
|
||||
#else
|
||||
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
|
||||
#endif
|
||||
v_width2=vec2(outset,inset);}`),lineGradient:aj(`uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;
|
||||
v_width2=vec2(outset,inset);}`),lineGradient:u9(`uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -485,7 +485,7 @@ v_gamma_scale=1.0;
|
||||
#else
|
||||
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
|
||||
#endif
|
||||
v_width2=vec2(outset,inset);}`),linePattern:aj(`#ifdef GL_ES
|
||||
v_width2=vec2(outset,inset);}`),linePattern:u9(`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#endif
|
||||
uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;
|
||||
@@ -549,7 +549,7 @@ v_gamma_scale=1.0;
|
||||
#else
|
||||
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
|
||||
#endif
|
||||
v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}`),lineSDF:aj(`uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;
|
||||
v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}`),lineSDF:u9(`uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -610,7 +610,7 @@ v_gamma_scale=1.0;
|
||||
#else
|
||||
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
|
||||
#endif
|
||||
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),lineGradientSDF:aj(`uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;
|
||||
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),lineGradientSDF:u9(`uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;
|
||||
#ifdef GLOBE
|
||||
in float v_depth;
|
||||
#endif
|
||||
@@ -667,7 +667,7 @@ v_gamma_scale=1.0;
|
||||
#else
|
||||
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
|
||||
#endif
|
||||
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),layerComposite:aj(`uniform sampler2D u_image;uniform float u_opacity;
|
||||
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),layerComposite:u9(`uniform sampler2D u_image;uniform float u_opacity;
|
||||
#ifdef LAYER_BLEND
|
||||
uniform sampler2D u_backdrop;uniform highp vec2 u_backdrop_offset;
|
||||
#ifdef LAYER_BLEND_NONSEPARABLE
|
||||
@@ -744,7 +744,7 @@ vec4 dst=texelFetch(u_backdrop,texel-ivec2(u_backdrop_offset),0);fragColor=compo
|
||||
fragColor=src;
|
||||
#endif
|
||||
#endif
|
||||
}`,`layout(location=0) in vec2 a_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);}`),raster:aj(`uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);
|
||||
}`,`layout(location=0) in vec2 a_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);}`),raster:u9(`uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
@@ -752,7 +752,7 @@ fragColor=vec4(1.0);
|
||||
#ifdef GLOBE
|
||||
if (a_pos.y <-32767.5) {texturePos.y=0.0;}if (a_pos.y > 32766.5) {texturePos.y=1.0;}
|
||||
#endif
|
||||
float perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}`),symbolIcon:aj(`uniform sampler2D u_texture;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;
|
||||
float perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}`),symbolIcon:u9(`uniform sampler2D u_texture;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;
|
||||
#ifdef OVERDRAW_INSPECTOR
|
||||
fragColor=vec4(1.0);
|
||||
#endif
|
||||
@@ -766,7 +766,7 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
|
||||
#ifdef GLOBE
|
||||
if(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
|
||||
#endif
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}`),symbolSDF:aj(`#define SDF_PX 8.0
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}`),symbolSDF:u9(`#define SDF_PX 8.0
|
||||
uniform bool u_is_halo;uniform bool u_is_plain;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;
|
||||
#pragma maplibre: define highp vec4 fill_color
|
||||
#pragma maplibre: define highp vec4 halo_color
|
||||
@@ -799,7 +799,7 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
|
||||
#ifdef GLOBE
|
||||
if(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
|
||||
#endif
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}`),symbolTextAndIcon:aj(`#define SDF_PX 8.0
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}`),symbolTextAndIcon:u9(`#define SDF_PX 8.0
|
||||
#define SDF 1.0
|
||||
#define ICON 0.0
|
||||
uniform bool u_is_halo;uniform bool u_is_text;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;in vec4 v_data0;in vec3 v_data1;in float v_is_sdf;
|
||||
@@ -838,11 +838,11 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
|
||||
#ifdef GLOBE
|
||||
if(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
|
||||
#endif
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}`),terrain:aj(`uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && u_fog_ground_blend_opacity > 0.0 && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}`,`layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}`),terrainDepth:aj(`in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}`),terrainHeight:aj(`in highp float v_elevation;void main() {fragColor=vec4(v_elevation,0.0,0.0,1.0);}`,`layout(location=0) in vec3 a_pos3d;uniform vec4 u_tile_bounds;out highp float v_elevation;void main() {v_elevation=get_elevation(a_pos3d.xy);vec2 position=u_tile_bounds.xy+a_pos3d.xy/8192.0*u_tile_bounds.zw;gl_Position=vec4(position.x*2.0-1.0,1.0-position.y*2.0,0.0,1.0);}`),atmosphere:aj(`#ifdef GL_ES
|
||||
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}`),terrain:u9(`uniform sampler2D u_texture;in vec2 v_texture_pos;void main() {fragColor=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;invariant gl_Position;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}`),terrainDepth:u9(`in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}`),terrainHeight:u9(`in highp float v_elevation;void main() {fragColor=vec4(v_elevation,0.0,0.0,1.0);}`,`layout(location=0) in vec3 a_pos3d;uniform vec4 u_tile_bounds;out highp float v_elevation;void main() {v_elevation=get_elevation(a_pos3d.xy);vec2 position=u_tile_bounds.xy+a_pos3d.xy/8192.0*u_tile_bounds.zw;gl_Position=vec4(position.x*2.0-1.0,1.0-position.y*2.0,0.0,1.0);}`),atmosphere:u9(`#ifdef GL_ES
|
||||
precision highp float;
|
||||
#endif
|
||||
in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758
|
||||
);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}`),sky:aj(`uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;in vec3 v_view_direction;const float ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS=100000.0/6371000.0;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;float opacity=1.0;if (u_sky_blend > 0.0) {vec3 ray=normalize(v_view_direction);float globe_distance=length(u_globe_position);float angle_to_globe_center=acos(clamp(dot(ray,u_globe_position)/globe_distance,-1.0,1.0));float horizon_angle=asin(min(u_globe_radius/globe_distance,1.0));blend=mix(blend,((angle_to_globe_center-horizon_angle)*u_camera_to_center_distance+1.0)*u_device_pixel_ratio,u_sky_blend);float closest_approach=max(dot(ray,u_globe_position),0.0);float lowest_altitude=sqrt(max(globe_distance*globe_distance-closest_approach*closest_approach,0.0))-u_globe_radius;float atmosphere_height=u_globe_radius*ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;float inside_atmosphere=1.0-smoothstep(atmosphere_height,10.0*atmosphere_height,globe_distance-u_globe_radius);float through_atmosphere=1.0-smoothstep(0.0,atmosphere_height,lowest_altitude);opacity=inside_atmosphere*through_atmosphere*(1.0-u_atmosphere_blend);}if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor*=mix(1.0,opacity,u_sky_blend);}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 v_view_direction;void main() {v_view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,1.0,1.0);}`)};function aj(e,t){let n=/#pragma maplibre: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),i=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=a?a.concat(i):i,s=r?r.length:0,c={};return e=e.replace(n,(e,t,n,r,i)=>(c[i]=!0,t===`define`?`
|
||||
);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}`),sky:u9(`uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;in vec3 v_view_direction;const float ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS=100000.0/6371000.0;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;float opacity=1.0;if (u_sky_blend > 0.0) {vec3 ray=normalize(v_view_direction);float globe_distance=length(u_globe_position);float angle_to_globe_center=acos(clamp(dot(ray,u_globe_position)/globe_distance,-1.0,1.0));float horizon_angle=asin(min(u_globe_radius/globe_distance,1.0));blend=mix(blend,((angle_to_globe_center-horizon_angle)*u_camera_to_center_distance+1.0)*u_device_pixel_ratio,u_sky_blend);float closest_approach=max(dot(ray,u_globe_position),0.0);float lowest_altitude=sqrt(max(globe_distance*globe_distance-closest_approach*closest_approach,0.0))-u_globe_radius;float atmosphere_height=u_globe_radius*ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;float inside_atmosphere=1.0-smoothstep(atmosphere_height,10.0*atmosphere_height,globe_distance-u_globe_radius);float through_atmosphere=1.0-smoothstep(0.0,atmosphere_height,lowest_altitude);opacity=inside_atmosphere*through_atmosphere*(1.0-u_atmosphere_blend);}if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor*=mix(1.0,opacity,u_sky_blend);}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 v_view_direction;void main() {v_view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,1.0,1.0);}`),fog:u9(`uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;in vec2 v_fog_pos;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {float fog_depth=v_fog_pos.x/v_fog_pos.y*0.5+0.5;if (fog_depth <=u_fog_ground_blend) {discard;}float blend_color=u_horizon_fog_blend < 1.0 ? smoothstep(u_horizon_fog_blend,1.0,fog_depth) : 0.0;vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=clamp((fog_depth-u_fog_ground_blend)/(1.0-u_fog_ground_blend),0.0,1.0);fragColor=linearToGamma(fog_horizon_color_linear)*pow(factor_fog,2.0)*u_fog_ground_blend_opacity;}`,`layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_fog_pos;invariant gl_Position;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_fog_pos=(u_fog_matrix*vec4(a_pos3d.xy,ele,1.0)).zw;}`)};function u9(e,t){let n=/#pragma maplibre: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),i=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=a?a.concat(i):i,s=r?r.length:0,c={};return e=e.replace(n,(e,t,n,r,i)=>(c[i]=!0,t===`define`?`
|
||||
#ifndef HAS_UNIFORM_u_${i}
|
||||
in ${n} ${r} ${i};
|
||||
#else
|
||||
@@ -891,7 +891,7 @@ uniform ${n} ${r} u_${i};
|
||||
#else
|
||||
${n} ${r} ${i} = u_${i};
|
||||
#endif
|
||||
`}),{fragmentSource:e,vertexSource:t,staticAttributes:r,staticUniforms:o}}const oj=`#define PROJECTION_MERCATOR`,sj=`mercator`;var cj=class{constructor(e=_p){this._cachedMesh=null,this._worldCoordinateHelper=e}get name(){return this._worldCoordinateHelper.name}get worldCoordinateHelper(){return this._worldCoordinateHelper}get useSubdivision(){return!1}get shaderVariantName(){return sj}get shaderDefine(){return oj}get shaderPreludeCode(){return ij.projectionMercator}get vertexShaderPreludeCode(){return ij.projectionMercator.vertexSource}get subdivisionGranularity(){return T_.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}destroy(){}getMeshFromTileID(e,t,n,r,i){if(this._cachedMesh)return this._cachedMesh;let a=new jd;a.emplaceBack(0,0),a.emplaceBack(N,0),a.emplaceBack(0,N),a.emplaceBack(N,N);let o=e.createVertexBuffer(a,tw.members),s=ef.simpleSegment(0,0,4,2),c=new Yd;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);let l=e.createIndexBuffer(c);return this._cachedMesh=new ew(o,l,s),this._cachedMesh}recalculate(){}hasTransition(){return!1}};let lj;const uj=()=>lj||=new Pu({type:new q(R.projection.type,`type`)}),dj=new T_({fill:new w_(128,2),line:new w_(512,0),tile:new w_(128,32),stencil:new w_(128,1),circle:3});var fj=class{constructor(){this._tileMeshCache={}}get name(){return`vertical-perspective`}get worldCoordinateHelper(){return _p}get transitionState(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return ij.projectionGlobe}get vertexShaderPreludeCode(){return ij.projectionMercator.vertexSource}get subdivisionGranularity(){return dj}get useGlobeControls(){return!0}destroy(){}_getMeshKey(e){return`${e.granularity.toString(36)}_${e.generateBorders?`b`:``}${e.extendToNorthPole?`n`:``}${e.extendToSouthPole?`s`:``}`}getMeshFromTileID(e,t,n,r,i){let a=(i===`stencil`?dj.stencil:dj.tile).getGranularityForZoomLevel(t.z),o=t.y===0&&r,s=t.y===(1<<t.z)-1&&r;return this._getMesh(e,{granularity:a,generateBorders:n,extendToNorthPole:o,extendToSouthPole:s})}_getMesh(e,t){let n=this._getMeshKey(t);if(n in this._tileMeshCache)return this._tileMeshCache[n];let r=nw(e,t);return this._tileMeshCache[n]=r,r}recalculate(e){}hasTransition(){return!1}},pj=class extends $n{constructor(e,t){super(),this._transitionable=new Cu(uj(),`projection`,t),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new bu(0)),this._mercatorProjection=new cj,this._verticalPerspectiveProjection=new fj}get transitionState(){let e=this.properties.get(`type`);if(typeof e==`string`&&e===`mercator`)return 0;if(typeof e==`string`&&e===`vertical-perspective`)return 1;if(e instanceof Yi){if(e.from===e.to)return e.from===`mercator`?0:1;if(e.from===`vertical-perspective`&&e.to===`mercator`)return 1-e.transition;if(e.from===`mercator`&&e.to===`vertical-perspective`)return e.transition}return 1}get useGlobeRendering(){return this.transitionState>0}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get worldCoordinateHelper(){return this.currentProjection.worldCoordinateHelper}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}};function mj(e,t){if(Array.isArray(e)){let n=hj(e);return n&&F(`Projection expressions cannot use the registered projection "${n}", which only works as a plain name. Falling back to the globe projection.`),{projection:new pj({type:e},t),cameraProjection:`globe`}}let n=WC(e);if(n)return{projection:new cj(new BC(n)),cameraProjection:`mercator`};switch(e){case`mercator`:return{projection:new cj,cameraProjection:`mercator`};case`globe`:return{projection:new pj({type:[`interpolate`,[`linear`],[`zoom`],11,`vertical-perspective`,12,`mercator`]},{}),cameraProjection:`globe`};case`vertical-perspective`:return{projection:new fj,cameraProjection:`vertical-perspective`};default:return F(`Unknown projection name: ${e}. Falling back to mercator projection.`),{pro
Line truncated
|
||||
`),b=v.concat(ij.prelude.vertexSource,o.vertexSource,t.vertexSource).join(`
|
||||
`),x=l.createShader(l.FRAGMENT_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(x,y),l.compileShader(x),l.attachShader(this.program,x);let S=l.createShader(l.VERTEX_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(S,b),l.compileShader(S),l.attachShader(this.program,S),this.attributes={};let C={};if(this.numAttributes=f.length,l.linkProgram(this.program),!l.getProgramParameter(this.program,l.LINK_STATUS)){if(l.isContextLost()||l.getProgramParameter(this.program,l.ATTACHED_SHADERS)===0){this.failedToCreate=!0;return}throw l.getShaderParameter(x,l.COMPILE_STATUS)?l.getShaderParameter(S,l.COMPILE_STATUS)?Error(`Program failed to link: ${l.getProgramInfoLog(this.program)}`):Error(`Could not compile vertex shader: ${l.getShaderInfoLog(S)}`):Error(`Could not compile fragment shader: ${l.getShaderInfoLog(x)}`)}oM(l,this.program);let w=LM(l,this.program);for(let e of f){if(!e)continue;let t=l.getAttribLocation(this.program,e);t>=0&&(this.attributes[e]={location:t,isInteger:w.has(e)})}l.deleteShader(S),l.deleteShader(x);for(let e of _)if(e&&!C[e]){let t=l.getUniformLocation(this.program,e);t&&(C[e]=t)}this.fixedUniforms=r(e,C),this.terrainUniforms=kM(e,C),this.binderUniforms=n?n.getUniforms(e,C):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.terrainUniformBuffer.bind(),e.frameUniformBuffer.bind(),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,s.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e]);TM(e.terrainUniformBuffer,s)}if(mM(e,c),o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let b=0;switch(t){case y.LINES:b=2;break;case y.TRIANGLES:b=3;break;case y.LINE_STRIP:b=1}for(let n of f.get())n.vaos||={},n.vaos[l]||=new OM,n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),y.drawElements(t,n.primitiveLength*b,y.UNSIGNED_SHORT,n.primitiveOffset*b*2)}};function zM(e,t,n){let r=1/rt(n,1,t.tileZoom),i=2**n.tileID.overscaledZ,a=n.tileSize*2**t.tileZoom/i,o=a*(n.tileID.canonical.x+n.tileID.wrap*i),s=a*n.tileID.canonical.y;return{u_image:0,u_texsize:n.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[o>>16,s>>16],u_pixel_coord_lower:[o&65535,s&65535]}}function BM(e,t,n,r,i){let a=n.getPattern(e.from.toString()),o=n.getPattern(e.to.toString()),{width:s,height:c}=n.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:t.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:t.fromScale,u_scale_b:t.toScale,u_tile_units_to_pixels:1/rt(i,1,r.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[d&65535,f&65535]}}const VM=(e,t)=>({u_lightpos:new pf(e,t.u_lightpos),u_lightpos_globe:new pf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new pf(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_fill_translate:new Z(e,t.u_fill_translate)}),HM=(e,t)=>({u_lightpos:new pf(e,t.u_lightpos),u_lightpos_globe:new pf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new pf(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_height_factor:new X(e,t.u_height_factor),u_fill_translate:new Z(e,t.u_fill_translate),u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new pf(e,t.u_scale),u_fade:new X(e,t.u_fade)}),UM=(e,t,n,r)=>{let i=Vt(t.position),a=x();t.anchor===`viewport`&&C(a,e.bearingInRadians),Ee(i,i,a);let o=$(e).transformLightDirection(e,i),s=t.color;return{u_lightpos:i,u_lightpos_globe:o,u_lightintensity:t.intensity,u_lightcolor:[s.r,s.g,s.b],u_vertical_gradient:+n,u_fill_translate:r}},WM=(e,t,n,r,i,a,o)=>({...UM(e,t,n,r),...zM(a,e,o),u_height_factor:-(2**i.overscaledZ)/o.tileSize/8}),GM=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),KM=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new pf(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pattern),u_fill_translate:new Z(e,t.u_fill_translate)}),qM=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),JM=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new pf(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pat
Line truncated
|
||||
`}),{fragmentSource:e,vertexSource:t,staticAttributes:r,staticUniforms:o}}const d9=`#define PROJECTION_MERCATOR`,f9=`mercator`;var p9=class{constructor(e=zp){this._cachedMesh=null,this._worldCoordinateHelper=e}get name(){return this._worldCoordinateHelper.name}get worldCoordinateHelper(){return this._worldCoordinateHelper}getTransitionStateForZoom(){return 0}get useSubdivision(){return!1}get shaderVariantName(){return f9}get shaderDefine(){return d9}get shaderPreludeCode(){return l9.projectionMercator}get vertexShaderPreludeCode(){return l9.projectionMercator.vertexSource}get subdivisionGranularity(){return y_.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}destroy(){}getMeshFromTileID(e,t,n,r,i){if(this._cachedMesh)return this._cachedMesh;let a=new $d;a.emplaceBack(0,0),a.emplaceBack(N,0),a.emplaceBack(0,N),a.emplaceBack(N,N);let o=e.createVertexBuffer(a,i3.members),s=Cf.simpleSegment(0,0,4,2),c=new vf;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);let l=e.createIndexBuffer(c);return this._cachedMesh=new r3(o,l,s),this._cachedMesh}recalculate(){}hasTransition(){return!1}};let m9;const h9=()=>m9||=new Ou({type:new q(R.projection.type,`type`)}),g9=new y_({fill:new v_(128,2),line:new v_(512,0),tile:new v_(128,32),stencil:new v_(128,1),circle:3});var _9=class{constructor(){this._tileMeshCache={}}get name(){return`vertical-perspective`}get worldCoordinateHelper(){return zp}get transitionState(){return 1}getTransitionStateForZoom(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return l9.projectionGlobe}get vertexShaderPreludeCode(){return l9.projectionMercator.vertexSource}get subdivisionGranularity(){return g9}get useGlobeControls(){return!0}destroy(){}_getMeshKey(e){return`${e.granularity.toString(36)}_${e.generateBorders?`b`:``}${e.extendToNorthPole?`n`:``}${e.extendToSouthPole?`s`:``}`}getMeshFromTileID(e,t,n,r,i){let a=(i===`stencil`?g9.stencil:g9.tile).getGranularityForZoomLevel(t.z),o=t.y===0&&r,s=t.y===(1<<t.z)-1&&r;return this._getMesh(e,{granularity:a,generateBorders:n,extendToNorthPole:o,extendToSouthPole:s})}_getMesh(e,t){let n=this._getMeshKey(t);if(n in this._tileMeshCache)return this._tileMeshCache[n];let r=a3(e,t);return this._tileMeshCache[n]=r,r}recalculate(e){}hasTransition(){return!1}},v9=class extends $n{constructor(e,t){super(),this._transitionable=new _u(h9(),`projection`,t),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new mu(0)),this._mercatorProjection=new p9,this._verticalPerspectiveProjection=new _9}get transitionState(){return this._getTransitionState(this.properties.get(`type`))}getTransitionStateForZoom(e){return this._getTransitionState(this._transitioning.possiblyEvaluate(new mu(e,{now:bn()})).get(`type`))}_getTransitionState(e){if(typeof e==`string`&&e===`mercator`)return 0;if(typeof e==`string`&&e===`vertical-perspective`)return 1;if(e instanceof Yi){if(e.from===e.to)return e.from===`mercator`?0:1;if(e.from===`vertical-perspective`&&e.to===`mercator`)return 1-e.transition;if(e.from===`mercator`&&e.to===`vertical-perspective`)return e.transition}return 1}get useGlobeRendering(){return this.transitionState>0}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get worldCoordinateHelper(){return this.currentProjection.worldCoordinateHelper}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}};function y9(e,t){if(Array.isArray(e)){let n=b9(e);return n&&F(`Projection expressions cannot use the registered projection "${n}", which only works as a plain name. Falling back to the globe projection.`),{projection:new v9({type:e},t),cameraProjection:`globe`}}let n=q4(e);if(n)return{projection:new p9(new U4(n)),cameraProjection:`mercator`};switch(e){case`mercator`:return{projection:new p9,cameraProjection:`mercator`};case`globe`:return{projection:new v9({type:[`interpolate`,[`linear`],[`zoom`],
Line truncated
|
||||
`),b=v.concat(l9.prelude.vertexSource,o.vertexSource,t.vertexSource).join(`
|
||||
`),x=l.createShader(l.FRAGMENT_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(x,y),l.compileShader(x),l.attachShader(this.program,x);let S=l.createShader(l.VERTEX_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(S,b),l.compileShader(S),l.attachShader(this.program,S),this.attributes={};let C={};if(this.numAttributes=f.length,l.linkProgram(this.program),!l.getProgramParameter(this.program,l.LINK_STATUS)){if(l.isContextLost()||l.getProgramParameter(this.program,l.ATTACHED_SHADERS)===0){this.failedToCreate=!0;return}throw l.getShaderParameter(x,l.COMPILE_STATUS)?l.getShaderParameter(S,l.COMPILE_STATUS)?Error(`Program failed to link: ${l.getProgramInfoLog(this.program)}`):Error(`Could not compile vertex shader: ${l.getShaderInfoLog(S)}`):Error(`Could not compile fragment shader: ${l.getShaderInfoLog(x)}`)}dS(l,this.program);let w=HS(l,this.program);for(let e of f){if(!e)continue;let t=l.getAttribLocation(this.program,e);t>=0&&(this.attributes[e]={location:t,isInteger:w.has(e)})}l.deleteShader(S),l.deleteShader(x);for(let e of _)if(e&&!C[e]){let t=l.getUniformLocation(this.program,e);t&&(C[e]=t)}this.fixedUniforms=r(e,C),this.terrainUniforms=PS(e,C),this.binderUniforms=n?n.getUniforms(e,C):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.terrainUniformBuffer.bind(),e.frameUniformBuffer.bind(),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,s.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e]);AS(e.terrainUniformBuffer,s)}if(yS(e,c),o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let b=0;switch(t){case y.LINES:b=2;break;case y.TRIANGLES:b=3;break;case y.LINE_STRIP:b=1}for(let n of f.get())n.vaos||={},n.vaos[l]||=new NS,n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),y.drawElements(t,n.primitiveLength*b,y.UNSIGNED_SHORT,n.primitiveOffset*b*2)}};function WS(e,t,n){let r=1/rt(n,1,t.tileZoom),i=2**n.tileID.overscaledZ,a=n.tileSize*2**t.tileZoom/i,o=a*(n.tileID.canonical.x+n.tileID.wrap*i),s=a*n.tileID.canonical.y;return{u_image:0,u_texsize:n.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[o>>16,s>>16],u_pixel_coord_lower:[o&65535,s&65535]}}function GS(e,t,n,r,i){let a=n.getPattern(e.from.toString()),o=n.getPattern(e.to.toString()),{width:s,height:c}=n.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:t.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:t.fromScale,u_scale_b:t.toScale,u_tile_units_to_pixels:1/rt(i,1,r.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[d&65535,f&65535]}}const KS=(e,t)=>({u_lightpos:new Ff(e,t.u_lightpos),u_lightpos_globe:new Ff(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new Ff(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_fill_translate:new Z(e,t.u_fill_translate)}),qS=(e,t)=>({u_lightpos:new Ff(e,t.u_lightpos),u_lightpos_globe:new Ff(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new Ff(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_height_factor:new X(e,t.u_height_factor),u_fill_translate:new Z(e,t.u_fill_translate),u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade)}),JS=(e,t,n,r)=>{let i=Vt(t.position),a=x();t.anchor===`viewport`&&C(a,e.bearingInRadians),Ee(i,i,a);let o=$(e).transformLightDirection(e,i),s=t.color;return{u_lightpos:i,u_lightpos_globe:o,u_lightintensity:t.intensity,u_lightcolor:[s.r,s.g,s.b],u_vertical_gradient:+n,u_fill_translate:r}},YS=(e,t,n,r,i,a,o)=>({...JS(e,t,n,r),...WS(a,e,o),u_height_factor:-(2**i.overscaledZ)/o.tileSize/8}),XS=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),ZS=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pattern),u_fill_translate:new Z(e,t.u_fill_translate)}),QS=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),$S=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pat
Line truncated
|
||||
//# sourceMappingURL=maplibre-gl.mjs.map
|
||||
+66
-2
@@ -191,7 +191,29 @@ class AppTest < Minitest::Test
|
||||
def test_can_requires_login_and_is_off_without_a_config
|
||||
assert_equal 401, request.get("/api/can").status
|
||||
assert_equal 409, request.post("/api/can/actions/0", **logged_in_env).status
|
||||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [] }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [], "time" => nil }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
end
|
||||
|
||||
# The keypads' bindings: the profile's until this car saves its own, checked on the way in.
|
||||
def test_keypad_bindings_saved_over_the_profile
|
||||
assert_equal 401, request.get("/api/keypad/bindings").status
|
||||
body = json_body(request.get("/api/keypad/bindings", **logged_in_env))
|
||||
refute body["saved"]
|
||||
assert body["bindings"].any? { |b| b["input"] == "pad.K1" }
|
||||
own = [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => "2", "led" => "red", "junk" => 1 }]
|
||||
body = json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: own), **logged_in_env))
|
||||
assert_equal [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => 2.0, "led" => "red" }], body["bindings"]
|
||||
assert_equal body["bindings"], Maptool::App.bindings
|
||||
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "mode" => "blink" }]), **logged_in_env).status
|
||||
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "led" => "pink" }]), **logged_in_env).status
|
||||
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K2", "mode" => "positions", "output" => "relays.1" }]), **logged_in_env).status
|
||||
pos = [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"], "output" => "relays.1" }]
|
||||
assert_equal [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"] }],
|
||||
json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: pos), **logged_in_env))["bindings"]
|
||||
refute json_body(request.delete("/api/keypad/bindings", **logged_in_env))["saved"]
|
||||
assert Maptool::App.bindings.size > 1
|
||||
ensure
|
||||
FileUtils.rm_f(Maptool::App::BINDINGS_PATH)
|
||||
end
|
||||
|
||||
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
|
||||
@@ -499,7 +521,7 @@ class AppTest < Minitest::Test
|
||||
def test_plugins_lists_whatever_is_on_disk
|
||||
response = request.get("/api/plugins")
|
||||
assert_equal 200, response.status
|
||||
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin" }], json_body(response)
|
||||
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin", "route" => false, "settings" => [], "set" => [] }], json_body(response)
|
||||
end
|
||||
|
||||
def test_plugins_run_imports_the_output_into_a_folder_of_its_own
|
||||
@@ -516,6 +538,22 @@ class AppTest < Minitest::Test
|
||||
assert_equal "Test POI", saved["features"][0]["properties"]["name"]
|
||||
end
|
||||
|
||||
# Along the trip's route: what lies further off than the corridor dropped.
|
||||
def test_plugins_run_along_the_route_keeps_the_corridor
|
||||
store = Maptool::App::TRIP_STORE
|
||||
saved = store.instance_variable_get(:@trip)
|
||||
run = lambda do |line|
|
||||
store.instance_variable_set(:@trip, saved.merge(route: { geometry: { coordinates: line } }))
|
||||
json_body(request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env))["count"]
|
||||
end
|
||||
assert_equal 1, run.([[17.0, 47.99], [17.1, 47.99]]) # the POI ~1.1 km off
|
||||
assert_equal 0, run.([[17.0, 47.95], [17.1, 47.95]]) # ~5.6 km off
|
||||
store.instance_variable_set(:@trip, saved.merge(route: nil))
|
||||
assert_equal 422, request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env).status
|
||||
ensure
|
||||
store.instance_variable_set(:@trip, saved)
|
||||
end
|
||||
|
||||
def test_plugins_run_requires_a_bbox
|
||||
response = request.post("/api/plugins/test-plugin/run", **logged_in_env)
|
||||
assert_equal 400, response.status
|
||||
@@ -696,6 +734,32 @@ class AppTest < Minitest::Test
|
||||
latest.clear
|
||||
end
|
||||
|
||||
# The recording's days and its export: a GPX with a track per day, or a .zip.
|
||||
def test_trip_log_days_and_export
|
||||
log = Maptool::App::TRIP_LOG
|
||||
log.stop
|
||||
assert_equal 200, request.post("/api/trip/log", input: JSON.generate(name: "Export test"), "CONTENT_TYPE" => "application/json", **logged_in_env).status
|
||||
t0 = Time.new(2026, 12, 1, 10).to_f
|
||||
10.times { |i| log.record(17.0, 48.0 + i * 0.001, 100.0, t0 + i * 60) }
|
||||
10.times { |i| log.record(17.0, 48.1 + i * 0.001, 100.0, t0 + 10 * 3600 + i * 60) } # stood 10 h
|
||||
log.record(17.0, 48.2, 100.0, t0 + 11 * 3600)
|
||||
|
||||
days = json_body(request.get("/api/trip/log/days?track=1", **logged_in_env))
|
||||
assert_equal [true, 2, "auto"], [days["active"], days["days"].size, days["days"][0]["cut"]["kind"]]
|
||||
assert_equal 21, days["track"].size
|
||||
gpx = request.get("/api/trip/log/export?pauses=1", **logged_in_env)
|
||||
assert_equal 2, gpx.body.scan("<trk>").size
|
||||
assert_includes gpx.body, "Stood "
|
||||
one = request.get("/api/trip/log/export?days=2", **logged_in_env).body
|
||||
assert_equal 1, one.scan("<trk>").size
|
||||
zip = request.get("/api/trip/log/export?per_day=1", **logged_in_env)
|
||||
assert_equal "application/zip", zip.content_type
|
||||
assert_equal 200, request.post("/api/trip/log/days", input: JSON.generate(join: days["track"][10][2]), "CONTENT_TYPE" => "application/json", **logged_in_env).status
|
||||
assert_equal 1, json_body(request.get("/api/trip/log/days", **logged_in_env))["days"].size
|
||||
ensure
|
||||
log.stop
|
||||
end
|
||||
|
||||
# A tunnel: no fix for a while, the position carried along the trip's
|
||||
# route — at the average speed it was entered at, by the CAN speed when there is one.
|
||||
def test_no_fix_on_the_route_is_dead_reckoned_along_it
|
||||
|
||||
@@ -119,4 +119,15 @@ class CanTest < Minitest::Test
|
||||
assert_raises(Errno::ENOENT) { Maptool::Can::Recorder.new(dir, [], binary: "/nonexistent").start }
|
||||
end
|
||||
end
|
||||
|
||||
def test_the_recorder_drops_segments_older_than_it_keeps
|
||||
Dir.mktmpdir do |dir|
|
||||
old, fresh = %w[20261201-100000.mf4 20261203-100000.mf4].map { |name| File.join(dir, name).tap { |p| File.write(p, "x") } }
|
||||
File.utime(Time.now - 25 * 3600, Time.now - 25 * 3600, old)
|
||||
File.write(File.join(dir, "notes.txt"), "kept: not a segment")
|
||||
assert_equal ["20261203-100000.mf4"], Maptool::Can::Recorder.new(dir, [], keep: 24 * 3600).files.map { |f| f[:name] }
|
||||
refute File.exist?(old)
|
||||
assert File.exist?(fresh) && File.exist?(File.join(dir, "notes.txt"))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,28 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/corridor"
|
||||
|
||||
class CorridorTest < Minitest::Test
|
||||
C = Maptool::Corridor
|
||||
# 30 km east along 48° N, as a vertex every ~0.75 km
|
||||
LINE = (0..40).map { |i| [17.0 + i * 0.01, 48.0] }
|
||||
|
||||
def test_circles_cover_the_corridor_with_no_gap
|
||||
circles = C.circles(LINE, 2.0)
|
||||
assert_in_delta 2.5, circles.first[1], 1e-9
|
||||
# every point 2 km off the line, all along it, inside a circle
|
||||
(0..300).each do |i|
|
||||
lon = 17.0 + i * 0.4 / 300
|
||||
edge = [lon, 48.0 + 2.0 / C::KM_PER_DEG]
|
||||
assert circles.any? { |center, r| C.km(center, edge) <= r + 1e-6 }, "gap at #{lon}"
|
||||
end
|
||||
assert_operator circles.size, :<=, (C.km(LINE.first, LINE.last) / 3.0).ceil + 2
|
||||
end
|
||||
|
||||
def test_distance_to_the_line_and_thinning
|
||||
assert_in_delta 1.0, C.distance_km([17.2, 48.0 + 1.0 / C::KM_PER_DEG], LINE), 1e-3
|
||||
assert_in_delta C.km([16.99, 48.0], LINE.first), C.distance_km([16.99, 48.0], LINE), 1e-9 # past an end: to the end
|
||||
thin = C.thin(LINE, 2.0)
|
||||
assert_equal [LINE.first, LINE.last], [thin.first, thin.last]
|
||||
assert thin.each_cons(2).to_a[0..-2].all? { |a, b| C.km(a, b) >= 2.0 }
|
||||
end
|
||||
end
|
||||
@@ -22,6 +22,19 @@ class GnssSimTest < Minitest::Test
|
||||
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
|
||||
|
||||
# A track replayed at its own pace: 100 m in 10 s (10 m/s), a stop of an
|
||||
# hour cut to MAX_GAP_S, another 100 m in 20 s; ends at its end.
|
||||
def test_replays_a_track_at_its_own_speed
|
||||
fixes = []
|
||||
step = 100.0 / 111_320
|
||||
track = [[17.0, 48.0, 1000], [17.0, 48.0 + step, 1010], [17.0, 48.0 + step, 4610], [17.0, 48.0 + 2 * step, 4630]]
|
||||
Maptool::GnssSim.new("http://valhalla", sleep: ->(_s) {}).replay(track) { |fix| fixes << fix }
|
||||
assert_in_delta 10.0, fixes.first[:speed], 0.01
|
||||
assert_in_delta 5.0, fixes.last[:speed], 0.01
|
||||
assert_in_delta 48.0 + 2 * step, fixes.last[:lat], 1e-9
|
||||
assert_in_delta (10 + Maptool::GnssSim::MAX_GAP_S + 20) / Maptool::GnssSim::TICK_S, fixes.size, 2
|
||||
end
|
||||
|
||||
# Started with the trip's route: from its start along it, before any random trip.
|
||||
def test_starts_along_a_given_route
|
||||
fixes = Queue.new
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
require_relative "test_helper"
|
||||
require_relative "../lib/maptool/link_place"
|
||||
|
||||
class LinkPlaceTest < Minitest::Test
|
||||
def test_coordinates_in_the_link
|
||||
place = Maptool::LinkPlace.from_url("https://www.google.com/maps/place/Hallstatt/@47.5622,13.6493,15z/data=!3m1!4b1!4m6!3m5!1s0x0:0x0!8m2!3d47.5622!4d13.6493")
|
||||
assert_equal({ name: "Hallstatt", lat: 47.5622, lng: 13.6493, url: place[:url] }, place)
|
||||
assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("https://maps.google.com/?q=48.15,17.11").values_at(:lat, :lng)
|
||||
assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("geo:48.15,17.11").values_at(:lat, :lng)
|
||||
assert_nil Maptool::LinkPlace.from_url("https://park4night.com/en/place/313577")
|
||||
end
|
||||
|
||||
def test_coordinates_in_the_page
|
||||
meta = %(<title>x</title><meta property="og:title" content="Stellplatz & See"><meta property="place:location:latitude" content="47.7395"><meta property="place:location:longitude" content="13.4482">)
|
||||
assert_equal({ name: "Stellplatz & See", lat: 47.7395, lng: 13.4482 }, Maptool::LinkPlace.from_html(meta))
|
||||
ld = %(<title> Camp </title><script type="application/ld+json">{"geo":{"latitude": 46.1, "longitude": 14.2}}</script>)
|
||||
assert_equal({ name: "Camp", lat: 46.1, lng: 14.2 }, Maptool::LinkPlace.from_html(ld))
|
||||
link = %(<a href="https://www.google.com/maps?daddr=45.5,13.7">go</a>)
|
||||
assert_equal [45.5, 13.7], Maptool::LinkPlace.from_html(link).values_at(:lat, :lng)
|
||||
assert_nil Maptool::LinkPlace.from_html("<p>nothing</p>")
|
||||
end
|
||||
|
||||
def test_no_private_addresses
|
||||
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://127.0.0.1/") }
|
||||
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://192.168.1.1/") }
|
||||
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("file:///etc/passwd") }
|
||||
end
|
||||
end
|
||||
@@ -120,4 +120,9 @@ class OverpassPoisTest < Minitest::Test
|
||||
assert_includes query, %(["amenity"="drinking_water"])
|
||||
assert_includes query, %(["natural"="spring"])
|
||||
end
|
||||
|
||||
def test_build_query_along_a_line_uses_around
|
||||
query = Maptool::OverpassPois.build_query(nil, around: [5000.0, [[17.1, 48.1], [17.2, 48.15]]])
|
||||
assert_includes query, %(node["amenity"="drinking_water"](around:5000,48.1,17.1,48.15,17.2);)
|
||||
end
|
||||
end
|
||||
+21
-3
@@ -18,7 +18,7 @@ class PluginsTest < Minitest::Test
|
||||
end
|
||||
|
||||
def test_list_finds_plugins_by_their_manifest
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello" }], Maptool::Plugins.list(@dir)
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], Maptool::Plugins.list(@dir)
|
||||
end
|
||||
|
||||
def test_list_is_empty_for_a_directory_with_no_plugins
|
||||
@@ -76,7 +76,7 @@ class PluginsTest < Minitest::Test
|
||||
|
||||
plugins = Maptool::Plugins.list([@dir, other_dir])
|
||||
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello" }, { "name" => "private", "label" => "Private" }], plugins
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }, { "name" => "private", "label" => "Private", "route" => false, "settings" => [] }], plugins
|
||||
ensure
|
||||
FileUtils.remove_entry(other_dir)
|
||||
end
|
||||
@@ -88,7 +88,7 @@ class PluginsTest < Minitest::Test
|
||||
|
||||
plugins = Maptool::Plugins.list([@dir, other_dir])
|
||||
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello" }], plugins
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], plugins
|
||||
ensure
|
||||
FileUtils.remove_entry(other_dir)
|
||||
end
|
||||
@@ -97,4 +97,22 @@ class PluginsTest < Minitest::Test
|
||||
result = Maptool::Plugins.run([Dir.mktmpdir, @dir], "hello", [1, 2, 3, 4])
|
||||
assert_equal({ "type" => "FeatureCollection", "features" => [] }, result)
|
||||
end
|
||||
|
||||
# A route and settings: --route/--corridor-km and the settings as env vars,
|
||||
# only the keys the plugin.json declares saved.
|
||||
def test_route_args_and_saved_settings_reach_the_command
|
||||
File.write(File.join(@plugin_dir, "plugin.json"), JSON.generate(label: "Hello", command: "./run.sh", route: true,
|
||||
settings: [{ key: "TOKEN", label: "Token" }, { key: "bad key" }]))
|
||||
File.write(File.join(@plugin_dir, "run.sh"), "#!/bin/sh\necho \"{\\\"type\\\":\\\"FeatureCollection\\\",\\\"features\\\":[],\\\"args\\\":\\\"$5 $6\\\",\\\"token\\\":\\\"$TOKEN\\\"}\"\n")
|
||||
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => true, "settings" => [{ "key" => "TOKEN", "label" => "Token" }] }], Maptool::Plugins.list(@dir)
|
||||
|
||||
path = File.join(@dir, "settings.json")
|
||||
assert_equal ["TOKEN"], Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => " abc ", "OTHER" => "x" })
|
||||
assert_equal 0o600, File.stat(path).mode & 0o777
|
||||
env = Maptool::Plugins.saved_settings(path)["hello"]
|
||||
result = Maptool::Plugins.run(@dir, "hello", [1, 2, 3, 4], route: "/tmp/r.geojson", corridor_km: 5.0, env: env)
|
||||
assert_equal "--route=/tmp/r.geojson --corridor-km=5.0", result["args"]
|
||||
assert_equal "abc", result["token"]
|
||||
assert_empty Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => "" })
|
||||
end
|
||||
end
|
||||
+32
-5
@@ -113,6 +113,20 @@ class RoutingTest < Minitest::Test
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) }
|
||||
end
|
||||
|
||||
def test_a_car_keeps_its_fuel_euro_class_stickers_and_vignettes
|
||||
Maptool::Routing.save_vehicles(@data, [{ "id" => "van", "name" => "Van", "fuel" => "diesel", "euro" => "6d", "stickers" => " DE green ",
|
||||
"wheelbase" => "3.45", "track" => 1.75, "ramps" => "9, 3 6,5",
|
||||
"vignettes" => [{ "country" => "sk", "until" => "2027-01-31" }, { "country" => "AT", "kind" => "toll" }] },
|
||||
{ "id" => "b", "name" => "B", "type" => "bicycle", "fuel" => "diesel" }])
|
||||
assert_equal({ id: "van", name: "Van", type: "car", fuel: "diesel", euro: "6d", stickers: "DE green", wheelbase: 3.45, track: 1.75, ramps: "3 6.5 9",
|
||||
vignettes: [{ country: "SK", kind: "vignette", until: "2027-01-31" }, { country: "AT", kind: "toll" }] }, Maptool::Routing.vehicle(@data, "van"))
|
||||
assert_equal({ id: "b", name: "B", type: "bicycle" }, Maptool::Routing.vehicle(@data, "b")) # a bike burns nothing
|
||||
[{ "fuel" => "coal" }, { "euro" => "7" }, { "vignettes" => [{ "country" => "Slovakia" }] }, { "vignettes" => [{ "country" => "SK", "until" => "soon" }] },
|
||||
{ "vignettes" => [{ "country" => "SK", "kind" => "sticker" }] }, { "ramps" => "3 60" }, { "track" => "5" }].each do |bad|
|
||||
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", **bad }]) }
|
||||
end
|
||||
end
|
||||
|
||||
def test_the_old_single_vehicle_becomes_the_camper
|
||||
File.write(File.join(@data, "vehicle.json"), JSON.generate(height: 3.3, width: 2.3, length: 7, weight: 3.5))
|
||||
assert_equal 3.3, Maptool::Routing.vehicle(@data, "camper")[:height]
|
||||
@@ -126,12 +140,12 @@ class RoutingTest < Minitest::Test
|
||||
def test_route_picks_the_costing_by_weight_and_returns_a_line
|
||||
shape = "wdg|xA{ubdQc@w@"
|
||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
|
||||
legs: [{ shape: shape, summary: { length: 1.5, time: 90 }, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"] }] }] })
|
||||
legs: [{ shape: shape, summary: { length: 1.5, time: 90 }, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"], verbal_pre_transition_instruction: "Drive north on Main." }] }] })
|
||||
# The per-country lookup failing (400) leaves the route as it is.
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url|
|
||||
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1])
|
||||
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
|
||||
assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main" }, route[:properties][:maneuvers][0])
|
||||
assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main", say: "Drive north on Main." }, route[:properties][:maneuvers][0])
|
||||
assert_equal [[1.5], [90]], route[:properties].values_at(:legs_km, :legs_s) # each leg's km and time, for the stops
|
||||
end
|
||||
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
|
||||
@@ -156,20 +170,33 @@ class RoutingTest < Minitest::Test
|
||||
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], properties[:countries]
|
||||
assert_equal [[0.0, 130], [1.0, nil], [1.5, 130]], properties[:speed_limits]
|
||||
assert_equal [[9.521034, 47.140974, 1.5]], properties[:signals]
|
||||
assert_equal [[0.0, "motorway", "AT"], [1.0, "primary", "AT"], [1.5, "motorway", "SK"]], properties[:roads]
|
||||
end
|
||||
assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}})
|
||||
assert_includes request, "/trace_attributes"
|
||||
end
|
||||
|
||||
def test_the_road_driven_is_the_last_matched_edge
|
||||
reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited" }])
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]]))
|
||||
reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }])
|
||||
no_route = "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}" # the signals ahead: none
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", no_route) do |url|
|
||||
assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]]))
|
||||
end
|
||||
assert_includes request, %("shape_match":"map_snap")
|
||||
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.road("http://x", [[17.1, 48.1]]) }
|
||||
end
|
||||
|
||||
def test_the_road_gives_the_signals_ahead_from_a_route_straight_on
|
||||
http = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
|
||||
road = JSON.generate(edges: [{ names: ["B"], road_class: "primary" }])
|
||||
route = JSON.generate(trip: { legs: [{ shape: "wdg|xA{ubdQc@w@" }] })
|
||||
along = JSON.generate(admins: [{ country_code: "SK" }], edges: [{ length: 0.4, end_shape_index: 1, end_node: { traffic_signal: true, admin_index: 0 } }])
|
||||
request = serve_once(http[road], http[route], http[along]) do |url|
|
||||
assert_equal [0.4], Maptool::Routing.road(url, [[17.1, 48.1], [17.1, 48.2]])[:signals].map(&:last)
|
||||
end
|
||||
assert_includes request, %("heading":0,"heading_tolerance":45)
|
||||
end
|
||||
|
||||
def test_bicycle_and_foot_use_their_own_costing_without_the_country_lookup
|
||||
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
|
||||
@@ -55,6 +55,13 @@ class SearchTest < Minitest::Test
|
||||
assert_empty search(" ")
|
||||
end
|
||||
|
||||
def test_blank_query_with_a_center_lists_the_library_nearest_first
|
||||
results = search("", center: [48.72, 21.26])
|
||||
assert_equal "Kemp Košice", results.first[:name]
|
||||
assert(results.all? { |r| r[:source] == "layers" })
|
||||
assert_empty search("", center: [48.72, 21.26], sources: ["hiking_trails"])
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def search(text, **opts)
|
||||
|
||||
@@ -26,6 +26,52 @@ class TripTest < Minitest::Test
|
||||
end
|
||||
end
|
||||
|
||||
def test_the_itinerary_keeps_nights_stays_notes_and_the_start_without_routing_again
|
||||
Dir.mktmpdir do |dir|
|
||||
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
|
||||
calls = 0
|
||||
router = ->(*) { calls += 1; { type: "Feature" } }
|
||||
points = [{ lngLat: [17.1, 48.1] }, { lngLat: [17.2, 48.2] }]
|
||||
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
|
||||
points[1] = { lngLat: [17.2, 48.2], night: true, stay: "90", note: " call ahead ", type: "campground", day_note: "" }
|
||||
points[0] = { lngLat: [17.1, 48.1], day_note: "leave early" }
|
||||
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, name: "Alps", start: "2026-12-12T08:00", day_start: "09:30", note: " chains ", &router)
|
||||
assert_equal 1, calls # an itinerary change isn't a route change
|
||||
assert_equal({ lngLat: [17.2, 48.2], name: nil, nav: false, passed: false, night: true, stay: 90, note: "call ahead", type: "campground" }.compact, trip[:points][1])
|
||||
assert_equal "leave early", trip[:points][0][:day_note]
|
||||
assert_equal ["Alps", "2026-12-12T08:00", "09:30", "chains"], trip.values_at(:name, :start, :day_start, :note)
|
||||
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], type: "<b>" }], vehicle: nil, avoid: {}, editing: nil, &router) }
|
||||
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], cost: "-1" }], vehicle: nil, avoid: {}, editing: nil, &router) }
|
||||
trip = store.update(points: [{ lngLat: [1, 2], cost: "32", paid: "" }], vehicle: nil, avoid: {}, editing: nil, budget: "250", fuel_price: "1.619", &router)
|
||||
assert_equal [32.0, nil, 250.0, 1.62], [trip[:points][0][:cost], trip[:points][0][:paid], trip[:budget], trip[:fuel_price]]
|
||||
# a parking spot: the route goes there instead of the place
|
||||
seen = nil
|
||||
points[1] = points[1].merge(park: { lngLat: [17.21, 48.19], name: "P2" })
|
||||
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { |locations, *| seen = locations; { type: "Feature" } }
|
||||
assert_equal [[17.1, 48.1], [17.21, 48.19]], seen
|
||||
assert_equal({ lngLat: [17.21, 48.19], name: "P2" }, trip[:points][1][:park])
|
||||
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], stay: "-5" }], vehicle: nil, avoid: {}, editing: nil, &router) }
|
||||
assert_raises(ArgumentError) { store.update(points: points, vehicle: nil, avoid: {}, editing: nil, start: "tomorrow", &router) }
|
||||
end
|
||||
end
|
||||
|
||||
# A day with avoids of its own: its legs routed apart, joined into one route.
|
||||
def test_a_days_own_avoids_route_it_apart
|
||||
points = [{ lngLat: [0, 0] }, { lngLat: [1, 0], night: true }, { lngLat: [2, 0], avoid: { highways: true } }, { lngLat: [3, 0] }]
|
||||
assert_equal [[[[0, 0], [1, 0]], { tolls: true }], [[[1, 0], [2, 0], [3, 0]], { highways: true }]], Maptool::TripStore.pieces(points, { tolls: true })
|
||||
assert_equal [[[[0, 0], [1, 0], [2, 0], [3, 0]], {}]], Maptool::TripStore.pieces(points.map { |p| p.except(:avoid) }, {})
|
||||
|
||||
part = ->(from, to) { { type: "Feature", geometry: { coordinates: [[from, 0], [to, 0]] },
|
||||
properties: { distance_km: 10.0, time_s: 600, legs_km: [10.0], legs_s: [600], maneuvers: [{ km: 10 }],
|
||||
roads: [[0.0, "motorway", "AT"]], signals: [[from, 0, 5.0]], countries: [{ code: "AT", km: 10.0, motorway_km: 10.0, toll_km: 0.0 }] } } }
|
||||
route = Maptool::Routing.merge([part.(0, 1), part.(1, 2)])
|
||||
assert_equal [[0, 0], [1, 0], [2, 0]], route[:geometry][:coordinates]
|
||||
assert_equal [20.0, 1200, [10.0, 10.0]], route[:properties].values_at(:distance_km, :time_s, :legs_km)
|
||||
assert_equal [[0.0, "motorway", "AT"], [10.0, "motorway", "AT"]], route[:properties][:roads]
|
||||
assert_equal [[0, 0, 5.0], [1, 0, 15.0]], route[:properties][:signals]
|
||||
assert_equal [{ code: "AT", km: 20.0, motorway_km: 20.0, toll_km: 0.0 }], route[:properties][:countries]
|
||||
end
|
||||
|
||||
# Off the route while driving for 3 fixes: routed again from the position
|
||||
# to the points not reached yet (the first via passed: dropped).
|
||||
def test_following_reroutes_from_the_position_off_the_route
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/trip_days"
|
||||
|
||||
class TripDaysTest < Minitest::Test
|
||||
D = Maptool::TripDays
|
||||
|
||||
# A drive: a point a minute from `start` (local time), `n` of them, going north.
|
||||
def drive(start, n, lat0 = 48.0)
|
||||
t0 = Time.new(*start).to_f
|
||||
(0...n).map { |i| [17.0, lat0 + i * 0.01, 100.0 + i, t0 + i * 60] }
|
||||
end
|
||||
|
||||
def test_a_night_stood_cuts_a_day_and_a_night_drive_cuts_at_three
|
||||
points = drive([2026, 12, 1, 18, 0], 60) + drive([2026, 12, 2, 8, 0], 30, 49.0) # stood 13 h
|
||||
assert_equal [[60, "auto"]], D.cuts(points)
|
||||
night = drive([2026, 12, 1, 23, 0], 300) # through the night, no stop
|
||||
assert_equal [[240, "night"]], D.cuts(night) # 23:00 + 240 min = 03:00
|
||||
end
|
||||
|
||||
def test_cuts_by_hand_and_joined
|
||||
points = drive([2026, 12, 1, 10, 0], 60) + drive([2026, 12, 1, 20, 0], 10, 49.0)
|
||||
hand = points[30][3] - 20 # between two points: the day starts at the next one
|
||||
cuts = D.cuts(points, hand: [hand])
|
||||
assert_equal [[30, "hand"], [60, "auto"]], cuts
|
||||
assert_equal [[30, "hand"]], D.cuts(points, hand: [hand], joined: [points[60][3]])
|
||||
|
||||
days = D.days(points, cuts)
|
||||
assert_equal [1, 2, 3], days.map { |d| d[:index] }
|
||||
assert_equal [0, 30, 60], days.map { |d| d[:from] }
|
||||
assert_equal "auto", days[1][:cut][:kind]
|
||||
assert_equal 9 * 3600 + 60, days[1][:cut][:stood_s] # from 10:59 to 20:00
|
||||
assert_in_delta 29 * 60, days[0][:driving_s], 1
|
||||
assert_nil days.last[:cut]
|
||||
end
|
||||
|
||||
def test_gpx_has_a_track_per_piece_with_times_and_pauses
|
||||
points = drive([2026, 12, 1, 10, 0], 3) + drive([2026, 12, 1, 11, 0], 3, 48.1)
|
||||
gpx = D.gpx([["Day 1", points.first(3)], ["Day 2", points.last(3)]], D.pauses(points))
|
||||
assert_equal 2, gpx.scan("<trk>").size
|
||||
assert_includes gpx, "<time>#{Time.at(points[0][3]).utc.iso8601}</time>"
|
||||
assert_includes gpx, "Stood 58 min"
|
||||
end
|
||||
end
|
||||
@@ -65,4 +65,27 @@ class TripLogTest < Minitest::Test
|
||||
refute Maptool::TripLog.new(log_dir, library: lib).active? # ended stays ended
|
||||
end
|
||||
end
|
||||
|
||||
# The days' cuts by hand and the joins go into the journal — while it
|
||||
# runs and after it ended — and a restart doesn't take them for a trip.
|
||||
def test_cuts_and_joins_are_journaled_running_or_ended
|
||||
Dir.mktmpdir do |dir|
|
||||
log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir))
|
||||
assert_nil log.recording
|
||||
log.start("Days", now: Time.utc(2026, 12, 1, 8))
|
||||
log.record(17.0, 48.0, nil, 1000)
|
||||
log.record(17.001, 48.0, nil, 1010)
|
||||
log.mark(:cut, 1005)
|
||||
rec = log.recording
|
||||
assert rec[:active]
|
||||
assert_equal [[1005.0], 2], [rec[:hand], rec[:points].size]
|
||||
log.stop
|
||||
log.mark(:join, 1010)
|
||||
rec = log.recording
|
||||
refute rec[:active]
|
||||
assert_equal [[1005.0], [1010.0], "Trips/2026-12-01 Days"], rec.values_at(:hand, :joined, :folder)
|
||||
refute Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir)).active?
|
||||
assert_raises(ArgumentError) { log.mark(:other, 1) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -7,7 +7,7 @@
|
||||
.debug-nav .map { margin-left: auto; }
|
||||
</style>
|
||||
<nav class="debug-nav">
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/keypad.html", "Keypad"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<a href="<%= href %>"<%= ' aria-current="page"' if request.path == href %>><%= label %></a>
|
||||
<% end %>
|
||||
<a class="map" href="/" target="maptool">The map ↗</a>
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@
|
||||
const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent);
|
||||
const shown = notice && notice.until > Date.now() ? notice : null;
|
||||
status.className = silent.length || shown?.bad ? "bad" : "";
|
||||
status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + (last.time ? `TIME: ${last.time.sending ? "maptool sends it" : "another node sends it"} · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
} catch (e) {
|
||||
status.textContent = `can't reach the server: ${e.message}`;
|
||||
} finally {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/driving.js": "/js/driving.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/drive_menus.js": "/js/drive_menus.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",
|
||||
@@ -39,6 +40,7 @@
|
||||
"/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/speed_limits.js": "/js/speed_limits.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/sun.js": "/js/sun.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/track_profile.js": "/js/track_profile.js?v=<%= ASSET_VERSION %>",
|
||||
"/vendor/maplibre-gl/maplibre-gl.mjs": "/vendor/maplibre-gl/maplibre-gl.mjs?v=<%= ASSET_VERSION %>",
|
||||
|
||||
+163
-86
@@ -2,13 +2,11 @@
|
||||
<header class="topbar">
|
||||
<span class="topbar__brand" title="rev <%= revision %>">MapTool</span>
|
||||
<div class="topbar__search"></div>
|
||||
<span class="topbar__center">
|
||||
<span class="topbar__sun" title="Sun & moon" hidden></span>
|
||||
</span>
|
||||
<span class="topbar__center"></span>
|
||||
<div class="sun-chart" hidden></div>
|
||||
<span class="topbar__offline-status" hidden></span>
|
||||
<button type="button" class="topbar__update" hidden></button>
|
||||
<button type="button" class="topbar__night"></button>
|
||||
<button type="button" class="topbar__night" hidden></button> <!-- the cycle On the map's Theme row and drive mode use; no place of its own in the bar -->
|
||||
<div class="topbar__auth">
|
||||
<% if logged_in %>
|
||||
<span><%= user %></span>
|
||||
@@ -28,8 +26,8 @@
|
||||
<span class="statusbar__coords"></span>
|
||||
<span class="statusbar__cursor"></span>
|
||||
<span class="statusbar__zoom"></span>
|
||||
<span class="statusbar__scale"></span>
|
||||
<span class="statusbar__rev">rev <%= revision %></span>
|
||||
<span class="statusbar__sun" title="Sun & moon" hidden></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -47,29 +45,9 @@
|
||||
<div class="trail-panel__body"></div>
|
||||
</div>
|
||||
|
||||
<div id="basemap-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Base map</strong>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<div class="basemap-panel__list basemap-panel__sources">
|
||||
<button type="button" class="basemap-panel__option" data-style="online">
|
||||
<span>Online</span>
|
||||
<span class="basemap-panel__check">✓</span>
|
||||
</button>
|
||||
<button type="button" class="basemap-panel__option" data-style="offline">
|
||||
<span>Offline</span>
|
||||
<span class="basemap-panel__check">✓</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="basemap-panel__list">
|
||||
<a class="basemap-panel__link" href="/symbols.html" target="_blank">Legend & symbols ↗</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="gpx-panel" class="gpx-panel" hidden<%= " data-sync-client" if sync_client %>>
|
||||
<div class="gpx-panel__header">
|
||||
<strong>Tracks & Points</strong>
|
||||
<strong>Library</strong>
|
||||
<div class="gpx-panel__actions">
|
||||
<button type="button" class="gpx-panel__action" data-action="new-folder" title="New folder" aria-label="New folder"></button>
|
||||
<button type="button" class="gpx-panel__action" data-action="upload" title="Upload GPX/FIT/TCX/GeoJSON file" aria-label="Upload GPX/FIT/TCX/GeoJSON file"></button>
|
||||
@@ -80,15 +58,54 @@
|
||||
<input type="file" class="gpx-file-input" accept=".gpx,.fit,.tcx,.geojson,.zip" multiple hidden>
|
||||
<p class="gpx-upload__status" hidden></p>
|
||||
|
||||
<!-- Find first (the Design canvas' Library): filled by GpxPanelControl. -->
|
||||
<div class="lib-find">
|
||||
<input type="search" class="lib-find__input" placeholder="Find a point, track, folder…" aria-label="Find in the library">
|
||||
<div class="lib-find__kinds" role="group" aria-label="What"></div>
|
||||
<div class="lib-find__bar">
|
||||
<button type="button" class="lib-chip" data-find="shown" aria-pressed="false">Shown on the map</button>
|
||||
<span class="lib-seg" role="group" aria-label="View">
|
||||
<button type="button" data-mode="folders" aria-pressed="true">Folders</button>
|
||||
<button type="button" data-mode="list" aria-pressed="false">List</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lib-crumb" hidden></div>
|
||||
<div class="gpx-tree"></div>
|
||||
<div class="gpx-legend" hidden></div>
|
||||
<div class="lib-foot">
|
||||
<span class="lib-foot__text"></span>
|
||||
<button type="button" data-action="hide-all">Hide all</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="overlays-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Overlays</strong>
|
||||
<strong>On the map</strong>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<!-- On the map (the Design canvas): the map itself first — online or the
|
||||
offline one (LayerToggleControl, map.js) — then the overlays. -->
|
||||
<div class="onthemap-map">
|
||||
<div class="overlays-panel__group">Map</div>
|
||||
<div class="onthemap-row">
|
||||
<span class="onthemap-row__icon" aria-hidden="true">▦</span>
|
||||
<span class="onthemap-row__text"><b>Map</b><small>online or this server's offline map</small></span>
|
||||
<span class="basemap-panel__sources onthemap-seg" role="group" aria-label="Map">
|
||||
<button type="button" class="basemap-panel__option" data-style="online">Online</button>
|
||||
<button type="button" class="basemap-panel__option" data-style="offline">Offline</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="onthemap-row">
|
||||
<span class="onthemap-row__icon" aria-hidden="true">◑</span>
|
||||
<span class="onthemap-row__text"><b>Theme</b><small>day / dusk / night, auto by the sun</small></span>
|
||||
<button type="button" class="onthemap-theme"></button>
|
||||
</div>
|
||||
<div class="onthemap-row">
|
||||
<span class="onthemap-row__icon" aria-hidden="true">?</span>
|
||||
<a class="onthemap-row__text basemap-panel__link" href="/symbols.html" target="_blank"><b>Legend & symbols ↗</b><small>what the map's colours and symbols mean</small></a>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Each item is a live layer refetched/toggled from its own source as
|
||||
the map moves, not a file to add/remove/reorder — a plain on/off
|
||||
list, no upload/new-folder actions the way Tracks & Points has.
|
||||
@@ -133,41 +150,107 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="route-panel" class="basemap-panel" hidden>
|
||||
<div id="route-panel" class="basemap-panel route-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Route</strong>
|
||||
<!-- Icons are added by RoutePanelControl (public/js/icons.js). -->
|
||||
<span class="route-panel__head-actions">
|
||||
<button type="button" data-action="reverse">Reverse</button>
|
||||
<button type="button" data-action="clear">Clear</button>
|
||||
</span>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<!-- Filled by RoutePanelControl (public/js/route.js). -->
|
||||
<!-- Filled by RoutePanelControl (public/js/route.js), laid out after the
|
||||
Design canvas' Desktop artboard: the points with their legs, adding
|
||||
one, the totals, the vehicle and what to avoid, the long parts folded,
|
||||
saving at the bottom. -->
|
||||
<div class="route-panel__body">
|
||||
<!-- The order of the Design canvas' Desktop artboard: the points
|
||||
with their legs, adding one, the totals, the vehicle and what to avoid,
|
||||
then the long parts folded; editing the whole route at the bottom. -->
|
||||
<p class="route-panel__editing" hidden></p>
|
||||
<!-- the itinerary (the Design canvas' Itinerary): the shared trip's name,
|
||||
when it leaves; a day after a night stop starts at "Days start"; its note -->
|
||||
<div class="route-panel__trip">
|
||||
<input type="text" name="name" maxlength="80" placeholder="Trip name" aria-label="Trip name">
|
||||
<label>Leave <input type="datetime-local" name="start"></label>
|
||||
<label>Days start <input type="time" name="day_start" placeholder="09:00"></label>
|
||||
<label>Fuel <input type="number" name="fuel_price" min="0" max="10" step="0.01" placeholder="–"> €/l</label>
|
||||
<label>Budget <input type="number" name="budget" min="0" max="1000000" step="10" placeholder="–"> €</label>
|
||||
<textarea name="note" rows="1" maxlength="2000" placeholder="The trip's note" aria-label="The trip's note"></textarea>
|
||||
</div>
|
||||
<!-- is the trip ready (the canvas' Plan, Check): each problem with its stop -->
|
||||
<details class="route-panel__fold route-panel__check" hidden>
|
||||
<summary>Check <span class="route-panel__fold-meta"></span></summary>
|
||||
<ul></ul>
|
||||
</details>
|
||||
<!-- the money (the canvas' Plan, Costs): planned from the route and the stops vs paid -->
|
||||
<details class="route-panel__fold route-panel__costs" hidden>
|
||||
<summary>Costs <span class="route-panel__fold-meta"></span></summary>
|
||||
<ul></ul>
|
||||
</details>
|
||||
<ol class="route-panel__points"></ol>
|
||||
<!-- Icons are added by RoutePanelControl (public/js/icons.js). -->
|
||||
<div class="route-panel__buttons">
|
||||
<button type="button" data-action="position">My position</button>
|
||||
<button type="button" data-action="saved-point">Saved point</button>
|
||||
<div class="route-panel__add">
|
||||
<button type="button" class="route-panel__chip route-panel__chip--add" data-action="search">+ Search</button>
|
||||
<button type="button" class="route-panel__chip" data-action="saved-point">Saved point</button>
|
||||
<button type="button" class="route-panel__chip" data-action="position">My position</button>
|
||||
<span class="route-panel__hint">or click the map</span>
|
||||
</div>
|
||||
<div class="route-panel__saved" hidden>
|
||||
<input type="search" placeholder="Search saved points" aria-label="Search saved points">
|
||||
<ul></ul>
|
||||
</div>
|
||||
<p class="route-panel__hint">Add a point: below, "+" on a search result or a library point, or click the map; drag a marker to move it.</p>
|
||||
<div class="route-panel__totals" hidden></div>
|
||||
<p class="route-panel__summary"></p>
|
||||
<ul class="route-panel__countries" hidden></ul>
|
||||
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
|
||||
<div class="route-panel__vehicle-row">
|
||||
<label>Vehicle <select class="route-panel__vehicle-select"></select></label>
|
||||
<button type="button" data-action="vehicle-edit" hidden>Edit</button>
|
||||
<div class="route-panel__row route-panel__avoid">
|
||||
<span class="route-panel__label">Avoid</span>
|
||||
<label class="route-panel__chip"><input type="checkbox" name="tolls"> Tolls</label>
|
||||
<label class="route-panel__chip"><input type="checkbox" name="highways"> Motorways</label>
|
||||
<label class="route-panel__chip"><input type="checkbox" name="ferries"> Ferries</label>
|
||||
<label class="route-panel__chip"><input type="checkbox" name="unpaved"> Unpaved</label>
|
||||
</div>
|
||||
<div class="route-panel__avoid">
|
||||
Avoid
|
||||
<label><input type="checkbox" name="tolls"> tolls</label>
|
||||
<label><input type="checkbox" name="highways"> motorways</label>
|
||||
<details class="route-panel__fold route-panel__directions" hidden>
|
||||
<summary>Directions <span class="route-panel__fold-meta"></span></summary>
|
||||
<ol></ol>
|
||||
</details>
|
||||
<details class="route-panel__fold">
|
||||
<summary>Reach <span class="route-panel__fold-meta">30 min · 1 h · 2 h</span></summary>
|
||||
<div class="route-panel__reach">
|
||||
<span>Reach in</span>
|
||||
<select>
|
||||
<option value="30">30 min</option>
|
||||
<option value="60" selected>1 h</option>
|
||||
<option value="120">2 h</option>
|
||||
<option value="30,60,120">30 min · 1 h · 2 h</option>
|
||||
</select>
|
||||
<button type="button" data-action="reach">Show</button>
|
||||
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
||||
</div>
|
||||
<fieldset class="route-panel__vehicle" hidden>
|
||||
<p class="route-panel__reach-status" hidden></p>
|
||||
</details>
|
||||
</div>
|
||||
<div class="route-panel__footer">
|
||||
<button type="button" class="route-panel__primary" data-action="save" hidden>Save to library</button>
|
||||
<button type="button" class="route-panel__secondary route-panel__profile" hidden>Elevation profile</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="offline-data-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Offline data</strong>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<!-- Two rows (map data / terrain data), each its own status text +
|
||||
"Regenerate for current view" button — built by
|
||||
OfflineDataControl#mount (public/js/offline_data.js), same
|
||||
"control owns its content" story as the Overlays panel. -->
|
||||
<div class="offline-data-panel__body"></div>
|
||||
</div>
|
||||
|
||||
<!-- Profiles (cars and activities): set once, rarely opened again (the
|
||||
Design canvas' Vehicle). The map's bottom-left chip picks one (route.js). -->
|
||||
<dialog class="profiles" aria-label="Profiles">
|
||||
<div class="profiles__head"><h2>Profiles</h2><button type="button" class="profiles__close" aria-label="Close">✕</button></div>
|
||||
<div class="profiles__list"><ul></ul><button type="button" data-action="vehicle-add">+ New profile</button></div>
|
||||
<fieldset class="profiles__form">
|
||||
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
|
||||
<label>Type
|
||||
<select name="type">
|
||||
@@ -181,6 +264,10 @@
|
||||
<label data-for="car">Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
|
||||
<label data-for="car">Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
|
||||
<label data-for="car">Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
|
||||
<label data-for="car">Wheelbase <input type="number" name="wheelbase" step="0.01" min="1" max="10" placeholder="–"> m</label>
|
||||
<label data-for="car">Track <input type="number" name="track" step="0.01" min="1" max="3" placeholder="–" title="Between the wheels' centres, side to side"> m</label>
|
||||
<label data-for="car">Uses <input type="number" name="consumption" step="0.1" min="1" max="100" placeholder="–" title="Per 100 km: litres (kWh for an electric car), for the trip's costs"> /100 km</label>
|
||||
<label data-for="car">Ramps <input type="text" name="ramps" maxlength="30" placeholder="3 6 9" title="The levelling ramps' steps, cm"> cm</label>
|
||||
<label data-for="bicycle">Bike
|
||||
<select name="bicycle_type">
|
||||
<option value="Road">Road</option>
|
||||
@@ -207,46 +294,36 @@
|
||||
<option value="6">T6 difficult alpine</option>
|
||||
</select>
|
||||
</label>
|
||||
<label data-for="car">Fuel
|
||||
<select name="fuel">
|
||||
<option value="">–</option>
|
||||
<option value="petrol">Petrol</option>
|
||||
<option value="diesel">Diesel</option>
|
||||
<option value="lpg">LPG</option>
|
||||
<option value="cng">CNG</option>
|
||||
<option value="electric">Electric</option>
|
||||
<option value="hybrid">Hybrid</option>
|
||||
</select>
|
||||
</label>
|
||||
<label data-for="car">Euro
|
||||
<select name="euro">
|
||||
<option value="">–</option>
|
||||
<option value="3">Euro 3</option>
|
||||
<option value="4">Euro 4</option>
|
||||
<option value="5">Euro 5</option>
|
||||
<option value="6">Euro 6</option>
|
||||
<option value="6d">Euro 6d</option>
|
||||
</select>
|
||||
</label>
|
||||
<label data-for="car" class="profiles__wide">Stickers <input type="text" name="stickers" maxlength="80" placeholder="DE green 4 · FR Crit'Air 2"></label>
|
||||
<div data-for="car" class="profiles__wide profiles__vignettes">
|
||||
<span>Vignettes & toll units</span>
|
||||
<ul></ul>
|
||||
<button type="button" data-action="vignette-add">+ Add</button>
|
||||
</div>
|
||||
<p class="route-panel__vehicle-hint" data-for="car">Empty: no limit. Over 3.5 t routes as a truck.</p>
|
||||
<p class="route-panel__vehicle-hint" data-for="bicycle foot">Empty speed: the usual one for the bike or walking.</p>
|
||||
<button type="button" data-action="vehicle-add">+ New vehicle</button>
|
||||
<button type="button" data-action="vehicle-delete">Delete</button>
|
||||
<button type="button" data-action="vehicle-delete" class="profiles__delete">Delete this profile</button>
|
||||
</fieldset>
|
||||
<details class="route-panel__directions" hidden>
|
||||
<summary>Directions</summary>
|
||||
<ol></ol>
|
||||
</details>
|
||||
<details class="route-panel__fold">
|
||||
<summary>Reach</summary>
|
||||
<div class="route-panel__reach">
|
||||
<span>Reach in</span>
|
||||
<select>
|
||||
<option value="30">30 min</option>
|
||||
<option value="60" selected>1 h</option>
|
||||
<option value="120">2 h</option>
|
||||
<option value="30,60,120">30 min · 1 h · 2 h</option>
|
||||
</select>
|
||||
<button type="button" data-action="reach">Show</button>
|
||||
<button type="button" data-action="reach-clear" hidden>Hide</button>
|
||||
</div>
|
||||
<p class="route-panel__reach-status" hidden></p>
|
||||
</details>
|
||||
<div class="route-panel__buttons">
|
||||
<button type="button" data-action="reverse">Reverse</button>
|
||||
<button type="button" data-action="clear">Clear</button>
|
||||
<button type="button" data-action="save" hidden>Save to library</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="offline-data-panel" class="basemap-panel" hidden>
|
||||
<div class="basemap-panel__header">
|
||||
<strong>Offline data</strong>
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</div>
|
||||
<!-- Two rows (map data / terrain data), each its own status text +
|
||||
"Regenerate for current view" button — built by
|
||||
OfflineDataControl#mount (public/js/offline_data.js), same
|
||||
"control owns its content" story as the Overlays panel. -->
|
||||
<div class="offline-data-panel__body"></div>
|
||||
</div>
|
||||
<div class="profiles__foot">Stored on this server for every screen; changes save as you go.</div>
|
||||
</dialog>
|
||||
@@ -0,0 +1,268 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Keypad bindings</title>
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; --sel: #546619; }
|
||||
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
|
||||
h1 { font-size: 1.2rem; margin: 0; }
|
||||
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 8px; }
|
||||
main { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); align-items: start; }
|
||||
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
|
||||
.pad { display: inline-grid; gap: 10px; padding: 18px; border-radius: 20px; background: #111; margin-bottom: 12px; }
|
||||
.pad button { width: 76px; height: 76px; border-radius: 14px; border: 4px solid var(--led, #333); background: #1c1c1c; color: #e8e6df; font: inherit; font-size: 12px; font-weight: 700;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; box-shadow: 0 0 12px color-mix(in srgb, var(--led, #000) 35%, transparent); overflow: hidden; }
|
||||
.pad button small { font-weight: 400; font-size: 10px; color: #9b988d; max-width: 68px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pad .knob { border-radius: 50%; }
|
||||
.pad .press { width: 76px; height: 30px; border-radius: 8px; border-width: 2px; font-size: 10px; flex-direction: row; }
|
||||
.pad button[aria-pressed="true"] { outline: 3px solid #fff; outline-offset: 4px; }
|
||||
.pad button.hit { background: #3a3a35; }
|
||||
.knobs { display: flex; gap: 10px; }
|
||||
.knobs > div { display: flex; flex-direction: column; gap: 6px; }
|
||||
label, fieldset { display: flex; flex-direction: column; gap: 4px; margin: 0 0 12px; padding: 0; border: none; }
|
||||
label > span, legend { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
select, input, button { font-size: 1rem; padding: 8px 12px; border-radius: 8px; }
|
||||
.modes { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.modes button[aria-pressed="true"] { background: var(--sel); color: #fff; border-color: var(--sel); }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.primary { background: var(--sel); color: #fff; border: 1px solid var(--sel); font-weight: 600; }
|
||||
.hint { color: var(--muted); font-size: 0.85rem; }
|
||||
.bad { color: var(--bad); } .on { color: var(--ok); }
|
||||
a { color: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<%= erb :_debug_nav, layout: false %>
|
||||
<header>
|
||||
<h1>Keypad bindings</h1>
|
||||
<span id="state">loading…</span>
|
||||
</header>
|
||||
<main>
|
||||
<section>
|
||||
<h2>Keypads</h2>
|
||||
<div id="pads"></div>
|
||||
<p class="hint">Tap a key or knob, or press it on the keypad. The ring is the key LED's colour.</p>
|
||||
</section>
|
||||
<section id="editor" hidden>
|
||||
<h2 id="title"></h2>
|
||||
<label><span>Drives</span><select id="drives"></select></label>
|
||||
<fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div>
|
||||
<span class="hint" id="mode-hint"></span></fieldset>
|
||||
<fieldset id="positions-box"><legend>Positions — a press steps off → 1 → 2 → … → off, a knob turns up and down</legend>
|
||||
<ol id="positions" style="margin: 0; padding-left: 1.5em; display: flex; flex-direction: column; gap: 6px"></ol>
|
||||
<div class="actions" style="margin-top: 6px"><button type="button" id="add-position">+ Position</button></div></fieldset>
|
||||
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
|
||||
<label id="period-box"><span>Strobe period (on + off), s</span><input id="period" type="number" min="0.2" step="0.1" value="1"></label>
|
||||
<label id="step-box"><span>Dimmer step per knob click, %</span><input id="step" type="number" min="1" max="100" step="1" value="10"></label>
|
||||
<label><span>In an open menu</span><select id="menu"></select></label>
|
||||
<div class="row" id="led-box">
|
||||
<label><span>LED</span><select id="led"></select></label>
|
||||
<label><span>LED while on</span><select id="led_on"></select></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="button" id="remove">Remove</button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<p class="actions" style="margin-top: 16px">
|
||||
<button type="button" class="primary" id="save" disabled>Save</button>
|
||||
<button type="button" id="reset">Back to the profile's</button>
|
||||
<span class="hint" id="source"></span>
|
||||
</p>
|
||||
|
||||
<script>
|
||||
// The keypads' bindings (GET/PUT/DELETE /api/keypad/bindings): a key or knob
|
||||
// picked, what it drives — a screen key's action or an output — how, and its LEDs.
|
||||
// Edits stay here until Save; drive mode takes them when it next loads.
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const LED = { red: "#e8453a", green: "#34b545", blue: "#3b82f6", yellow: "#f0a020", cyan: "#22c3d6", magenta: "#b45bd0", white: "#e8e6df" };
|
||||
const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"];
|
||||
const MENU = ["rows", "enter", "close"];
|
||||
const MODE_HINT = { toggle: "each press switches it", on: "a press switches it on", off: "a press switches it off",
|
||||
hold: "on while held — off when let go or the keypad goes silent", pulse: "on for the time below",
|
||||
positions: "one output per position, the last off before the next on", strobe: "a press starts or stops it blinking",
|
||||
dimmer: "a knob sets the level, a press switches it on or off; only a dimmable module dims, a relay just switches" };
|
||||
const KNOB_MODES = ["positions", "dimmer"]; // what a turn does; the other modes take presses
|
||||
let info = null, bindings = [], screenActions = [], selected = null, dirty = false;
|
||||
|
||||
const json = async (url, options) => {
|
||||
const response = await fetch(url, { cache: "no-store", ...options });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
|
||||
return body;
|
||||
};
|
||||
const binding = (input) => bindings.find((b) => b.input === input);
|
||||
const isKnob = (input) => /\.E\d+$/.test(input);
|
||||
const outs = (b) => b?.outputs || (b?.output ? [b.output] : []);
|
||||
const what = (b) => (!b ? "" : b.outputs ? `${b.mode}: ${b.outputs.join(", ")}` : b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}${b.mode && b.mode !== "toggle" ? ` · ${b.mode}` : ""}` : b.action || (b.menu ? `menu: ${b.menu}` : ""));
|
||||
const outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || "";
|
||||
|
||||
function key(input, label, cls = "") {
|
||||
const b = binding(input);
|
||||
const led = b?.led ? `--led: ${LED[b.led]}` : "";
|
||||
return `<button type="button" class="${cls}" data-input="${esc(input)}" style="${led}" aria-pressed="${input === selected}">${esc(label)}<small>${esc(what(b) || "—")}</small></button>`;
|
||||
}
|
||||
function renderPads() {
|
||||
$("pads").innerHTML = info.keypads.map((d) => {
|
||||
const ch = d.channels;
|
||||
const keys = ch.filter((c) => !/^E\d+( press)?$/.test(c));
|
||||
const knobs = ch.filter((c) => /^E\d+$/.test(c));
|
||||
const cols = keys.length > 6 ? Math.ceil(keys.length / 2) : Math.max(keys.length, 1);
|
||||
return `<h2>${esc(d.name)}${d.protocol ? ` · ${esc(d.protocol.toUpperCase())} node 0x${d.node.toString(16).padStart(2, "0")}` : ""}</h2>` +
|
||||
(keys.length ? `<div class="pad" style="grid-template-columns: repeat(${cols}, 76px)">${keys.map((c) => key(`${d.name}.${c}`, c)).join("")}</div>` : "") +
|
||||
(knobs.length ? `<div class="pad knobs">${knobs.map((c) => `<div>${key(`${d.name}.${c}`, c, "knob")}${ch.includes(`${c} press`) ? key(`${d.name}.${c} press`, "⏎", "press") : ""}</div>`).join("")}</div>` : "");
|
||||
}).join("") || '<p class="hint">No keypads in data/can.json ("keypads").</p>';
|
||||
}
|
||||
const options = (list, value, none = "— nothing —") => `<option value="">${none}</option>` + list.map(([v, l]) => `<option value="${esc(v)}"${v === value ? " selected" : ""}>${esc(l)}</option>`).join("");
|
||||
|
||||
function renderEditor() {
|
||||
$("editor").hidden = !selected;
|
||||
if (!selected) return;
|
||||
const b = binding(selected) || {};
|
||||
const knob = isKnob(selected);
|
||||
const pkpKey = /\.K\d+$/.test(selected) && info.keypads.find((d) => selected.startsWith(`${d.name}.`))?.protocol === "pkp";
|
||||
$("title").textContent = `${selected}${knob ? " · turning" : selected.endsWith(" press") ? " · pressing the knob" : ""}`;
|
||||
const actions = [...(knob ? KNOB_ACTIONS : []), ...screenActions];
|
||||
const first = outs(b)[0];
|
||||
const drives = first ? `output:${first}` : b.action ? `action:${b.action}` : "";
|
||||
$("drives").innerHTML = `<option value="">— nothing —</option>` +
|
||||
`<optgroup label="Screen">${actions.map((a) => `<option value="action:${esc(a)}"${`action:${a}` === drives ? " selected" : ""}>${esc(a)}</option>`).join("")}</optgroup>` +
|
||||
`<optgroup label="Output">${outputOptions(drives.slice(7))}</optgroup>`;
|
||||
const isOut = !!first;
|
||||
const mode = b.mode || (knob ? "dimmer" : "toggle");
|
||||
$("mode-box").hidden = !isOut;
|
||||
$("modes").innerHTML = info.modes.filter((m) => !knob || KNOB_MODES.includes(m)).map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
|
||||
$("mode-hint").textContent = MODE_HINT[mode] || "";
|
||||
$("positions-box").hidden = !isOut || mode !== "positions";
|
||||
$("positions").innerHTML = (b.outputs || []).map((o, i) => `<li><span class="actions"><select data-position="${i}">${outputOptions(o)}</select>${i ? `<button type="button" data-drop="${i}" aria-label="Remove position ${i + 1}">✕</button>` : ""}</span></li>`).join("");
|
||||
$("pulse-box").hidden = !isOut || mode !== "pulse";
|
||||
$("pulse").value = b.pulse_s ?? 1;
|
||||
$("period-box").hidden = !isOut || mode !== "strobe";
|
||||
$("period").value = b.period_s ?? 1;
|
||||
$("step-box").hidden = !isOut || mode !== "dimmer";
|
||||
$("step").value = b.step ?? 10;
|
||||
$("menu").innerHTML = options([...(knob ? ["rows"] : MENU.slice(1)).map((m) => [m, m]), ...screenActions.map((a) => [a, a])], b.menu, "— the same —");
|
||||
$("led-box").hidden = !pkpKey;
|
||||
const colors = info.colors.map((c) => [c, c]);
|
||||
$("led").innerHTML = options(colors, b.led, "off");
|
||||
$("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green");
|
||||
}
|
||||
const outputOptions = (value) => info.outputs.map((o) => `<option value="${esc(o.output)}"${o.output === value ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}${o.dimmable ? " · dimmable" : ""}</option>`).join("");
|
||||
function render() {
|
||||
renderPads();
|
||||
renderEditor();
|
||||
$("save").disabled = !dirty;
|
||||
$("source").textContent = dirty ? "unsaved changes" : info.saved ? "this car's own (data/drive/bindings.json)" : "the profile's (public/drive/road.json)";
|
||||
}
|
||||
|
||||
// a field changed: into the selected input's binding (made, or dropped when empty)
|
||||
function change(fields) {
|
||||
let b = binding(selected);
|
||||
if (!b) bindings.push((b = { input: selected }));
|
||||
Object.assign(b, fields);
|
||||
for (const k of Object.keys(b)) if (b[k] === "" || b[k] == null) delete b[k];
|
||||
if (!b.action && !b.output && !b.outputs && !b.menu) bindings = bindings.filter((x) => x !== b);
|
||||
dirty = true;
|
||||
render();
|
||||
}
|
||||
$("pads").addEventListener("click", (e) => {
|
||||
const el = e.target.closest("button[data-input]");
|
||||
if (el) { selected = el.dataset.input; render(); }
|
||||
});
|
||||
$("drives").addEventListener("change", (e) => {
|
||||
const [kind, value] = [e.target.value.slice(0, e.target.value.indexOf(":")), e.target.value.slice(e.target.value.indexOf(":") + 1)];
|
||||
const b = binding(selected);
|
||||
if (kind === "output" && b?.outputs) change({ outputs: [value, ...b.outputs.slice(1)] });
|
||||
else if (kind === "output") change({ output: value, action: null, mode: isKnob(selected) ? "dimmer" : b?.mode });
|
||||
else change({ action: kind === "action" ? value : null, output: null, outputs: null, mode: null, pulse_s: null, period_s: null, step: null });
|
||||
});
|
||||
$("modes").addEventListener("click", (e) => {
|
||||
const m = e.target.closest("button[data-mode]")?.dataset.mode;
|
||||
if (!m) return;
|
||||
const list = outs(binding(selected));
|
||||
change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null,
|
||||
period_s: m === "strobe" ? binding(selected)?.period_s ?? 1 : null, step: m === "dimmer" ? binding(selected)?.step ?? 10 : null,
|
||||
outputs: m === "positions" ? list : null, output: m === "positions" ? null : list[0] });
|
||||
});
|
||||
$("positions").addEventListener("change", (e) => {
|
||||
const i = Number(e.target.dataset.position);
|
||||
change({ outputs: binding(selected).outputs.map((o, k) => (k === i ? e.target.value : o)) });
|
||||
});
|
||||
$("positions").addEventListener("click", (e) => {
|
||||
const i = e.target.dataset.drop;
|
||||
if (i != null) change({ outputs: binding(selected).outputs.filter((_, k) => k !== Number(i)) });
|
||||
});
|
||||
$("add-position").addEventListener("click", () => {
|
||||
const list = binding(selected).outputs;
|
||||
const next = info.outputs.find((o) => !list.includes(o.output))?.output || list[list.length - 1];
|
||||
change({ outputs: [...list, next] });
|
||||
});
|
||||
$("period").addEventListener("change", (e) => change({ period_s: Number(e.target.value) || 1 }));
|
||||
$("step").addEventListener("change", (e) => change({ step: Number(e.target.value) || 10 }));
|
||||
$("pulse").addEventListener("change", (e) => change({ pulse_s: Number(e.target.value) || 1 }));
|
||||
$("menu").addEventListener("change", (e) => change({ menu: e.target.value }));
|
||||
$("led").addEventListener("change", (e) => change({ led: e.target.value }));
|
||||
$("led_on").addEventListener("change", (e) => change({ led_on: e.target.value }));
|
||||
$("remove").addEventListener("click", () => { bindings = bindings.filter((b) => b.input !== selected); dirty = true; render(); });
|
||||
$("save").addEventListener("click", async () => {
|
||||
try {
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bindings }) }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
$("state").innerHTML = '<span class="on">saved</span> — drive mode takes them when it next loads';
|
||||
render();
|
||||
} catch (e) { $("state").innerHTML = `<span class="bad">${esc(e.message)}</span>`; }
|
||||
});
|
||||
$("reset").addEventListener("click", async () => {
|
||||
if (!confirm("Drop this car's bindings and go back to the profile's?")) return;
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "DELETE" }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
render();
|
||||
});
|
||||
window.addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); });
|
||||
|
||||
// a key pressed on the keypad picks it (GET /api/keypad, a long poll)
|
||||
async function listen() {
|
||||
let since = null;
|
||||
for (;;) {
|
||||
try {
|
||||
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
|
||||
if (response.status === 404) return;
|
||||
const answer = await response.json();
|
||||
if (since != null) for (const e of answer.events) {
|
||||
if (e.input.endsWith(" up")) continue;
|
||||
selected = e.input.replace(/ [⟳⟲]$/, "");
|
||||
render();
|
||||
document.querySelector(`[data-input="${CSS.escape(selected)}"]`)?.classList.add("hit");
|
||||
setTimeout(() => document.querySelector(".hit")?.classList.remove("hit"), 300);
|
||||
}
|
||||
$("state").innerHTML = answer.present.length ? `<span class="on">● ${answer.present.map((p) => esc(p.name)).join(", ")} on the bus</span>` : "no keypad on the bus";
|
||||
since = answer.seq;
|
||||
} catch { await new Promise((r) => setTimeout(r, 3000)); }
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const [i, profile] = await Promise.all([json("/api/keypad/bindings"), json("/drive/road.json")]);
|
||||
info = i;
|
||||
bindings = structuredClone(info.bindings);
|
||||
screenActions = profile.cells.filter((c) => c.widget === "key").map((c) => c.action);
|
||||
selected = info.keypads[0] ? `${info.keypads[0].name}.${info.keypads[0].channels[0]}` : null;
|
||||
render();
|
||||
listen();
|
||||
} catch (e) {
|
||||
$("state").innerHTML = `<span class="bad">${esc(e.message)}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+34
-1
@@ -36,6 +36,10 @@
|
||||
<button type="button" id="random">From a random place</button>
|
||||
<button type="button" id="stop">Stop</button>
|
||||
</div>
|
||||
<div class="actions" style="margin-top: 8px">
|
||||
<select id="track" aria-label="A library track"><option value="">A library track…</option></select>
|
||||
<button type="button" id="replay">Replay it</button>
|
||||
</div>
|
||||
<p id="hint" style="color: GrayText; font-size: 0.85rem"></p>
|
||||
<label>Simulated time
|
||||
<select id="speedup"></select>
|
||||
@@ -50,6 +54,11 @@
|
||||
<h2>Trip</h2>
|
||||
<dl id="trip"></dl>
|
||||
</section>
|
||||
<section id="outputs" hidden>
|
||||
<h2>Outputs</h2>
|
||||
<div id="relays"></div>
|
||||
<p style="color: GrayText; font-size: 0.85rem">can.json's "outputs" (simulated: no frames sent). A click switches one (and stops its strobe); the keypad's bindings with an output do too.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
@@ -69,6 +78,15 @@
|
||||
$("route").addEventListener("click", () => send("POST", { trip: true }));
|
||||
$("random").addEventListener("click", () => send("POST", {}));
|
||||
$("stop").addEventListener("click", () => send("DELETE"));
|
||||
$("replay").addEventListener("click", () => $("track").value && send("POST", { track: $("track").value }));
|
||||
// the library's tracks (a recorded one replays at its own speed; one with no times can't)
|
||||
json("/api/library/tree").then((tree) => {
|
||||
const tracks = [];
|
||||
const walk = (node, path) => node.children.forEach((c) => (c.type === "folder" ? walk(c, c.path) : c.kinds?.includes("track") && tracks.push([c.path, [path, c.name].filter(Boolean).join(" / ")])));
|
||||
walk(tree, "");
|
||||
const esc = (s) => s.replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
$("track").innerHTML += tracks.map(([key, label]) => `<option value="${key}">${esc(label)}</option>`).join("");
|
||||
}).catch(() => {});
|
||||
$("speedup").addEventListener("change", () => send("PUT", { speedup: Number($("speedup").value) }));
|
||||
|
||||
async function refresh() {
|
||||
@@ -94,8 +112,23 @@
|
||||
$("state").innerHTML = `<span class="bad">${e.message}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
|
||||
}
|
||||
}
|
||||
// The relay modules (GET /api/outputs): a button per channel, lit when on.
|
||||
async function relays() {
|
||||
const data = await json("/api/outputs").catch(() => null);
|
||||
$("outputs").hidden = !data;
|
||||
if (!data) return;
|
||||
const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const by = (o) => data.bindings.filter((b) => (b.outputs || [b.output]).includes(o)).map((b) => `${b.input} (${b.mode || "toggle"})`).join(", ");
|
||||
$("relays").innerHTML = data.modules.map((m) => `<p>${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}</p><div class="actions">` +
|
||||
m.channels.map((c) => `<button type="button" data-output="${esc(m.name)}/${c.n}" class="${c.on ? "on" : ""}" title="${esc(by(`${m.name}.${c.n}`))}">${c.on ? "●" : "○"} ${c.n}${c.label ? ` ${esc(c.label)}` : ""}${c.level != null ? ` ${Math.round(c.level)} %` : ""}${c.strobe ? " · strobe" : ""}</button>`).join("") + "</div>").join("");
|
||||
}
|
||||
$("relays").addEventListener("click", (e) => {
|
||||
const b = e.target.closest("button[data-output]");
|
||||
if (b) json(`/api/outputs/${b.dataset.output}`, { method: "POST" }).catch((err) => alert(err.message)).then(relays);
|
||||
});
|
||||
refresh();
|
||||
setInterval(refresh, 1000);
|
||||
relays();
|
||||
setInterval(() => { refresh(); relays(); }, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user